blob: d9acc77c6d7c54a75b3a57704d04c416ad1c9c0b [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
Richard Smith32918772017-02-14 00:25:28 +0000966/// Get the index of the first template parameter that was originally from the
967/// innermost template-parameter-list. This is 0 except when we concatenate
968/// the template parameter lists of a class template and a constructor template
969/// when forming an implicit deduction guide.
970static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD) {
971 if (!FTD->isImplicit() || !FTD->getTemplatedDecl()->isDeductionGuide())
972 return 0;
973 return FTD->getDeclName().getCXXDeductionGuideTemplate()
974 ->getTemplateParameters()->size();
975}
976
977/// Determine whether a type denotes a forwarding reference.
978static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
979 // C++1z [temp.deduct.call]p3:
980 // A forwarding reference is an rvalue reference to a cv-unqualified
981 // template parameter that does not represent a template parameter of a
982 // class template.
983 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
984 if (ParamRef->getPointeeType().getQualifiers())
985 return false;
986 auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
987 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
988 }
989 return false;
990}
991
Douglas Gregorcceb9752009-06-26 18:27:22 +0000992/// \brief Deduce the template arguments by comparing the parameter type and
993/// the argument type (C++ [temp.deduct.type]).
994///
Chandler Carruthc1263112010-02-07 21:33:28 +0000995/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +0000996///
997/// \param TemplateParams the template parameters that we are deducing
998///
999/// \param ParamIn the parameter type
1000///
1001/// \param ArgIn the argument type
1002///
1003/// \param Info information about the template argument deduction itself
1004///
1005/// \param Deduced the deduced template arguments
1006///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001007/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +00001008/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +00001009///
Douglas Gregorb837ea42011-01-11 17:34:58 +00001010/// \param PartialOrdering Whether we're performing template argument deduction
1011/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1012///
Douglas Gregorcceb9752009-06-26 18:27:22 +00001013/// \returns the result of template argument deduction so far. Note that a
1014/// "success" result means that template argument deduction has not yet failed,
1015/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001016static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001017DeduceTemplateArgumentsByTypeMatch(Sema &S,
1018 TemplateParameterList *TemplateParams,
1019 QualType ParamIn, QualType ArgIn,
1020 TemplateDeductionInfo &Info,
1021 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1022 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +00001023 bool PartialOrdering,
1024 bool DeducedFromArrayBound) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001025 // We only want to look at the canonical types, since typedefs and
1026 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +00001027 QualType Param = S.Context.getCanonicalType(ParamIn);
1028 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001029
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001030 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001031 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001032 if (const PackExpansionType *ArgExpansion
1033 = dyn_cast<PackExpansionType>(Arg))
1034 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001035
Douglas Gregorb837ea42011-01-11 17:34:58 +00001036 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +00001037 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001038 // Before the partial ordering is done, certain transformations are
1039 // performed on the types used for partial ordering:
1040 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +00001041 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1042 if (ParamRef)
1043 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001044
Douglas Gregorb837ea42011-01-11 17:34:58 +00001045 // - If A is a reference type, A is replaced by the type referred to.
1046 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1047 if (ArgRef)
1048 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001049
Richard Smithed563c22015-02-20 04:45:22 +00001050 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1051 // C++11 [temp.deduct.partial]p9:
1052 // If, for a given type, deduction succeeds in both directions (i.e.,
1053 // the types are identical after the transformations above) and both
1054 // P and A were reference types [...]:
1055 // - if [one type] was an lvalue reference and [the other type] was
1056 // not, [the other type] is not considered to be at least as
1057 // specialized as [the first type]
1058 // - if [one type] is more cv-qualified than [the other type],
1059 // [the other type] is not considered to be at least as specialized
1060 // as [the first type]
1061 // Objective-C ARC adds:
1062 // - [one type] has non-trivial lifetime, [the other type] has
1063 // __unsafe_unretained lifetime, and the types are otherwise
1064 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +00001065 //
Richard Smithed563c22015-02-20 04:45:22 +00001066 // A is "considered to be at least as specialized" as P iff deduction
1067 // succeeds, so we model this as a deduction failure. Note that
1068 // [the first type] is P and [the other type] is A here; the standard
1069 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +00001070 Qualifiers ParamQuals = Param.getQualifiers();
1071 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +00001072 if ((ParamRef->isLValueReferenceType() &&
1073 !ArgRef->isLValueReferenceType()) ||
1074 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1075 (ParamQuals.hasNonTrivialObjCLifetime() &&
1076 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1077 ParamQuals.withoutObjCLifetime() ==
1078 ArgQuals.withoutObjCLifetime())) {
1079 Info.FirstArg = TemplateArgument(ParamIn);
1080 Info.SecondArg = TemplateArgument(ArgIn);
1081 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001082 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001083 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001084
Richard Smithed563c22015-02-20 04:45:22 +00001085 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001086 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001087 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001088 // version of P.
1089 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001090 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001091 // version of A.
1092 Arg = Arg.getUnqualifiedType();
1093 } else {
1094 // C++0x [temp.deduct.call]p4 bullet 1:
1095 // - If the original P is a reference type, the deduced A (i.e., the type
1096 // referred to by the reference) can be more cv-qualified than the
1097 // transformed A.
1098 if (TDF & TDF_ParamWithReferenceType) {
1099 Qualifiers Quals;
1100 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1101 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001102 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001103 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1104 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001105
Douglas Gregor85f240c2011-01-25 17:19:08 +00001106 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1107 // C++0x [temp.deduct.type]p10:
1108 // If P and A are function types that originated from deduction when
1109 // taking the address of a function template (14.8.2.2) or when deducing
1110 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001111 // Ai are parameters of the top-level parameter-type-list of P and A,
Richard Smith32918772017-02-14 00:25:28 +00001112 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1113 // is an lvalue reference, in
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001114 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001115 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1116 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001117 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001118 TDF &= ~TDF_TopLevelParameterTypeList;
Richard Smith32918772017-02-14 00:25:28 +00001119 if (isForwardingReference(Param, 0) && Arg->isLValueReferenceType())
1120 Param = Param->getPointeeType();
Douglas Gregor85f240c2011-01-25 17:19:08 +00001121 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001122 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001123
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001124 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001125 // A template type argument T, a template template argument TT or a
1126 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001127 // the following forms:
1128 //
1129 // T
1130 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001131 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001132 = Param->getAs<TemplateTypeParmType>()) {
Richard Smith87d263e2016-12-25 08:05:23 +00001133 // Just skip any attempts to deduce from a placeholder type or a parameter
1134 // at a different depth.
1135 if (Arg->isPlaceholderType() ||
1136 Info.getDeducedDepth() != TemplateTypeParm->getDepth())
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001137 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001138
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001139 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001140 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001141
Douglas Gregor60454822009-07-22 20:02:25 +00001142 // If the argument type is an array type, move the qualifiers up to the
1143 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001144 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001145 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001146 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001147 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001148 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001149 RecanonicalizeArg = true;
1150 }
1151 }
Mike Stump11289f42009-09-09 15:08:12 +00001152
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001153 // The argument type can not be less qualified than the parameter
1154 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001155 if (!(TDF & TDF_IgnoreQualifiers) &&
1156 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001157 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001158 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001159 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001160 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001161 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001162
Richard Smith87d263e2016-12-25 08:05:23 +00001163 assert(TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&
1164 "saw template type parameter with wrong depth");
Chandler Carruthc1263112010-02-07 21:33:28 +00001165 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001166 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001167
Douglas Gregor1d684c22011-04-28 00:56:09 +00001168 // Remove any qualifiers on the parameter from the deduced type.
1169 // We checked the qualifiers for consistency above.
1170 Qualifiers DeducedQs = DeducedType.getQualifiers();
1171 Qualifiers ParamQs = Param.getQualifiers();
1172 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1173 if (ParamQs.hasObjCGCAttr())
1174 DeducedQs.removeObjCGCAttr();
1175 if (ParamQs.hasAddressSpace())
1176 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001177 if (ParamQs.hasObjCLifetime())
1178 DeducedQs.removeObjCLifetime();
Simon Pilgrim728134c2016-08-12 11:43:57 +00001179
Douglas Gregore46db902011-06-17 22:11:49 +00001180 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001181 // If template deduction would produce a lifetime qualifier on a type
1182 // that is not a lifetime type, template argument deduction fails.
1183 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1184 !DeducedType->isDependentType()) {
1185 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1186 Info.FirstArg = TemplateArgument(Param);
1187 Info.SecondArg = TemplateArgument(Arg);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001188 return Sema::TDK_Underqualified;
Douglas Gregora4f2b432011-07-26 14:53:44 +00001189 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001190
Douglas Gregora4f2b432011-07-26 14:53:44 +00001191 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001192 // If template deduction would produce an argument type with lifetime type
1193 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001194 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001195 DeducedType->isObjCLifetimeType() &&
1196 !DeducedQs.hasObjCLifetime())
1197 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001198
Douglas Gregor1d684c22011-04-28 00:56:09 +00001199 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1200 DeducedQs);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001201
Douglas Gregord6605db2009-07-22 21:30:48 +00001202 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001203 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001204
Richard Smith5f274382016-09-28 23:55:27 +00001205 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001206 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001207 Deduced[Index],
1208 NewDeduced);
1209 if (Result.isNull()) {
1210 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1211 Info.FirstArg = Deduced[Index];
1212 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001213 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001214 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001215
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001216 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001217 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001218 }
1219
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001220 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001221 Info.FirstArg = TemplateArgument(ParamIn);
1222 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001223
Douglas Gregorfb322d82011-01-14 05:11:40 +00001224 // If the parameter is an already-substituted template parameter
1225 // pack, do nothing: we don't know which of its arguments to look
1226 // at, so we have to wait until all of the parameter packs in this
1227 // expansion have arguments.
1228 if (isa<SubstTemplateTypeParmPackType>(Param))
1229 return Sema::TDK_Success;
1230
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001231 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001232 CanQualType CanParam = S.Context.getCanonicalType(Param);
1233 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001234 if (!(TDF & TDF_IgnoreQualifiers)) {
1235 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001236 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001237 return Sema::TDK_NonDeducedMismatch;
John McCall08569062010-08-28 22:14:41 +00001238 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001239 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001240 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001241 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001242
Douglas Gregor194ea692012-03-11 03:29:50 +00001243 // If the parameter type is not dependent, there is nothing to deduce.
1244 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001245 if (!(TDF & TDF_SkipNonDependent)) {
1246 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1247 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1248 Param != Arg;
1249 if (NonDeduced) {
1250 return Sema::TDK_NonDeducedMismatch;
1251 }
1252 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001253 return Sema::TDK_Success;
1254 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001255 } else if (!Param->isDependentType()) {
1256 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1257 ArgUnqualType = CanArg.getUnqualifiedType();
1258 bool Success = (TDF & TDF_InOverloadResolution)?
1259 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1260 ArgUnqualType) :
1261 ParamUnqualType == ArgUnqualType;
1262 if (Success)
1263 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001264 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001265
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001266 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001267 // Non-canonical types cannot appear here.
1268#define NON_CANONICAL_TYPE(Class, Base) \
1269 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1270#define TYPE(Class, Base)
1271#include "clang/AST/TypeNodes.def"
Simon Pilgrim728134c2016-08-12 11:43:57 +00001272
Douglas Gregor39c02722011-06-15 16:02:29 +00001273 case Type::TemplateTypeParm:
1274 case Type::SubstTemplateTypeParmPack:
1275 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001276
1277 // These types cannot be dependent, so simply check whether the types are
1278 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001279 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001280 case Type::VariableArray:
1281 case Type::Vector:
1282 case Type::FunctionNoProto:
1283 case Type::Record:
1284 case Type::Enum:
1285 case Type::ObjCObject:
1286 case Type::ObjCInterface:
Douglas Gregor194ea692012-03-11 03:29:50 +00001287 case Type::ObjCObjectPointer: {
1288 if (TDF & TDF_SkipNonDependent)
1289 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001290
Douglas Gregor194ea692012-03-11 03:29:50 +00001291 if (TDF & TDF_IgnoreQualifiers) {
1292 Param = Param.getUnqualifiedType();
1293 Arg = Arg.getUnqualifiedType();
1294 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001295
Douglas Gregor194ea692012-03-11 03:29:50 +00001296 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1297 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001298
1299 // _Complex T [placeholder extension]
Douglas Gregor39c02722011-06-15 16:02:29 +00001300 case Type::Complex:
1301 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Simon Pilgrim728134c2016-08-12 11:43:57 +00001302 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1303 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001304 ComplexArg->getElementType(),
1305 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001306
1307 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001308
1309 // _Atomic T [extension]
1310 case Type::Atomic:
1311 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001312 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001313 cast<AtomicType>(Param)->getValueType(),
1314 AtomicArg->getValueType(),
1315 Info, Deduced, TDF);
1316
1317 return Sema::TDK_NonDeducedMismatch;
1318
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001319 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001320 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001321 QualType PointeeType;
1322 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1323 PointeeType = PointerArg->getPointeeType();
1324 } else if (const ObjCObjectPointerType *PointerArg
1325 = Arg->getAs<ObjCObjectPointerType>()) {
1326 PointeeType = PointerArg->getPointeeType();
1327 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001328 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001329 }
Mike Stump11289f42009-09-09 15:08:12 +00001330
Douglas Gregorfc516c92009-06-26 23:27:24 +00001331 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001332 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1333 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001334 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001335 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001336 }
Mike Stump11289f42009-09-09 15:08:12 +00001337
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001338 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001339 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001340 const LValueReferenceType *ReferenceArg =
1341 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001342 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001343 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001344
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001345 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001346 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001347 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001348 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001349
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001350 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001351 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001352 const RValueReferenceType *ReferenceArg =
1353 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001354 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001355 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001356
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001357 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1358 cast<RValueReferenceType>(Param)->getPointeeType(),
1359 ReferenceArg->getPointeeType(),
1360 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001361 }
Mike Stump11289f42009-09-09 15:08:12 +00001362
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001363 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001364 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001365 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001366 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001367 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001368 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001369
John McCallf7332682010-08-19 00:20:19 +00001370 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001371 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1372 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1373 IncompleteArrayArg->getElementType(),
1374 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001375 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001376
1377 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001378 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001379 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001380 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001381 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001382 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001383
1384 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001385 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001386 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001387 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001388
John McCallf7332682010-08-19 00:20:19 +00001389 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001390 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1391 ConstantArrayParm->getElementType(),
1392 ConstantArrayArg->getElementType(),
1393 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001394 }
1395
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001396 // type [i]
1397 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001398 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001399 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001400 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001401
John McCallf7332682010-08-19 00:20:19 +00001402 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1403
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001404 // Check the element type of the arrays
1405 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001406 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001407 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001408 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1409 DependentArrayParm->getElementType(),
1410 ArrayArg->getElementType(),
1411 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001412 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001413
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001414 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001415 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001416 = getDeducedParameterFromExpr(Info, DependentArrayParm->getSizeExpr());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001417 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001418 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001419
1420 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001421 // template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +00001422 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1423 "saw non-type template parameter with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +00001424 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001425 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1426 llvm::APSInt Size(ConstantArrayArg->getSize());
Richard Smith5f274382016-09-28 23:55:27 +00001427 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001428 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001429 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001430 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001431 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001432 if (const DependentSizedArrayType *DependentArrayArg
1433 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001434 if (DependentArrayArg->getSizeExpr())
Richard Smith5f274382016-09-28 23:55:27 +00001435 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001436 DependentArrayArg->getSizeExpr(),
1437 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001438
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001439 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001440 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001441 }
Mike Stump11289f42009-09-09 15:08:12 +00001442
1443 // type(*)(T)
1444 // T(*)()
1445 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001446 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001447 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001448 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001449 dyn_cast<FunctionProtoType>(Arg);
1450 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001451 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001452
1453 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001454 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001455
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001456 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001457 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001458 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001459 != FunctionProtoArg->getRefQualifier() ||
1460 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001461 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001462
Anders Carlsson2128ec72009-06-08 15:19:08 +00001463 // Check return types.
Alp Toker314cc812014-01-25 16:55:45 +00001464 if (Sema::TemplateDeductionResult Result =
1465 DeduceTemplateArgumentsByTypeMatch(
1466 S, TemplateParams, FunctionProtoParam->getReturnType(),
1467 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001468 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001469
Alp Toker9cacbab2014-01-20 20:26:09 +00001470 return DeduceTemplateArguments(
1471 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1472 FunctionProtoParam->getNumParams(),
1473 FunctionProtoArg->param_type_begin(),
1474 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
Anders Carlsson2128ec72009-06-08 15:19:08 +00001475 }
Mike Stump11289f42009-09-09 15:08:12 +00001476
John McCalle78aac42010-03-10 03:28:59 +00001477 case Type::InjectedClassName: {
1478 // Treat a template's injected-class-name as if the template
1479 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001480 Param = cast<InjectedClassNameType>(Param)
1481 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001482 assert(isa<TemplateSpecializationType>(Param) &&
1483 "injected class name is not a template specialization type");
1484 // fall through
1485 }
1486
Douglas Gregor705c9002009-06-26 20:57:09 +00001487 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001488 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001489 // TT<T>
1490 // TT<i>
1491 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001492 case Type::TemplateSpecialization: {
Richard Smith9b296e32016-04-25 19:09:05 +00001493 const TemplateSpecializationType *SpecParam =
1494 cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001495
Richard Smith9b296e32016-04-25 19:09:05 +00001496 // When Arg cannot be a derived class, we can just try to deduce template
1497 // arguments from the template-id.
1498 const RecordType *RecordT = Arg->getAs<RecordType>();
1499 if (!(TDF & TDF_DerivedClass) || !RecordT)
1500 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1501 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001502
Richard Smith9b296e32016-04-25 19:09:05 +00001503 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1504 Deduced.end());
Chandler Carruthc1263112010-02-07 21:33:28 +00001505
Richard Smith9b296e32016-04-25 19:09:05 +00001506 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1507 S, TemplateParams, SpecParam, Arg, Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001508
Richard Smith9b296e32016-04-25 19:09:05 +00001509 if (Result == Sema::TDK_Success)
1510 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001511
Richard Smith9b296e32016-04-25 19:09:05 +00001512 // We cannot inspect base classes as part of deduction when the type
1513 // is incomplete, so either instantiate any templates necessary to
1514 // complete the type, or skip over it if it cannot be completed.
1515 if (!S.isCompleteType(Info.getLocation(), Arg))
1516 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001517
Richard Smith9b296e32016-04-25 19:09:05 +00001518 // C++14 [temp.deduct.call] p4b3:
1519 // If P is a class and P has the form simple-template-id, then the
1520 // transformed A can be a derived class of the deduced A. Likewise if
1521 // P is a pointer to a class of the form simple-template-id, the
1522 // transformed A can be a pointer to a derived class pointed to by the
1523 // deduced A.
1524 //
1525 // These alternatives are considered only if type deduction would
1526 // otherwise fail. If they yield more than one possible deduced A, the
1527 // type deduction fails.
Mike Stump11289f42009-09-09 15:08:12 +00001528
Faisal Vali683b0742016-05-19 02:28:21 +00001529 // Reset the incorrectly deduced argument from above.
1530 Deduced = DeducedOrig;
1531
1532 // Use data recursion to crawl through the list of base classes.
1533 // Visited contains the set of nodes we have already visited, while
1534 // ToVisit is our stack of records that we still need to visit.
1535 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1536 SmallVector<const RecordType *, 8> ToVisit;
1537 ToVisit.push_back(RecordT);
Richard Smith9b296e32016-04-25 19:09:05 +00001538 bool Successful = false;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001539 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
Faisal Vali683b0742016-05-19 02:28:21 +00001540 while (!ToVisit.empty()) {
1541 // Retrieve the next class in the inheritance hierarchy.
1542 const RecordType *NextT = ToVisit.pop_back_val();
Richard Smith9b296e32016-04-25 19:09:05 +00001543
Faisal Vali683b0742016-05-19 02:28:21 +00001544 // If we have already seen this type, skip it.
1545 if (!Visited.insert(NextT).second)
1546 continue;
Richard Smith9b296e32016-04-25 19:09:05 +00001547
Faisal Vali683b0742016-05-19 02:28:21 +00001548 // If this is a base class, try to perform template argument
1549 // deduction from it.
1550 if (NextT != RecordT) {
1551 TemplateDeductionInfo BaseInfo(Info.getLocation());
1552 Sema::TemplateDeductionResult BaseResult =
1553 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1554 QualType(NextT, 0), BaseInfo, Deduced);
1555
1556 // If template argument deduction for this base was successful,
1557 // note that we had some success. Otherwise, ignore any deductions
1558 // from this base class.
1559 if (BaseResult == Sema::TDK_Success) {
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001560 // If we've already seen some success, then deduction fails due to
1561 // an ambiguity (temp.deduct.call p5).
1562 if (Successful)
1563 return Sema::TDK_MiscellaneousDeductionFailure;
1564
Faisal Vali683b0742016-05-19 02:28:21 +00001565 Successful = true;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001566 std::swap(SuccessfulDeduced, Deduced);
1567
Faisal Vali683b0742016-05-19 02:28:21 +00001568 Info.Param = BaseInfo.Param;
1569 Info.FirstArg = BaseInfo.FirstArg;
1570 Info.SecondArg = BaseInfo.SecondArg;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001571 }
1572
1573 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001574 }
Mike Stump11289f42009-09-09 15:08:12 +00001575
Faisal Vali683b0742016-05-19 02:28:21 +00001576 // Visit base classes
1577 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1578 for (const auto &Base : Next->bases()) {
1579 assert(Base.getType()->isRecordType() &&
1580 "Base class that isn't a record?");
1581 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1582 }
1583 }
Mike Stump11289f42009-09-09 15:08:12 +00001584
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001585 if (Successful) {
1586 std::swap(SuccessfulDeduced, Deduced);
Richard Smith9b296e32016-04-25 19:09:05 +00001587 return Sema::TDK_Success;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001588 }
Richard Smith9b296e32016-04-25 19:09:05 +00001589
Douglas Gregore81f3e72009-07-07 23:09:34 +00001590 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001591 }
1592
Douglas Gregor637d9982009-06-10 23:47:09 +00001593 // T type::*
1594 // T T::*
1595 // T (type::*)()
1596 // type (T::*)()
1597 // type (type::*)(T)
1598 // type (T::*)(T)
1599 // T (type::*)(T)
1600 // T (T::*)()
1601 // T (T::*)(T)
1602 case Type::MemberPointer: {
1603 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1604 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1605 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001606 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001607
David Majnemera381cda2015-11-30 20:34:28 +00001608 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1609 if (ParamPointeeType->isFunctionType())
1610 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1611 /*IsCtorOrDtor=*/false, Info.getLocation());
1612 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1613 if (ArgPointeeType->isFunctionType())
1614 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1615 /*IsCtorOrDtor=*/false, Info.getLocation());
1616
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001617 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001618 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
David Majnemera381cda2015-11-30 20:34:28 +00001619 ParamPointeeType,
1620 ArgPointeeType,
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001621 Info, Deduced,
1622 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001623 return Result;
1624
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001625 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1626 QualType(MemPtrParam->getClass(), 0),
1627 QualType(MemPtrArg->getClass(), 0),
Simon Pilgrim728134c2016-08-12 11:43:57 +00001628 Info, Deduced,
Douglas Gregor194ea692012-03-11 03:29:50 +00001629 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001630 }
1631
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001632 // (clang extension)
1633 //
Mike Stump11289f42009-09-09 15:08:12 +00001634 // type(^)(T)
1635 // T(^)()
1636 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001637 case Type::BlockPointer: {
1638 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1639 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001640
Anders Carlssona767eee2009-06-12 16:23:10 +00001641 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001642 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001643
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001644 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1645 BlockPtrParam->getPointeeType(),
1646 BlockPtrArg->getPointeeType(),
1647 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001648 }
1649
Douglas Gregor39c02722011-06-15 16:02:29 +00001650 // (clang extension)
1651 //
1652 // T __attribute__(((ext_vector_type(<integral constant>))))
1653 case Type::ExtVector: {
1654 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1655 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1656 // Make sure that the vectors have the same number of elements.
1657 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1658 return Sema::TDK_NonDeducedMismatch;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001659
Douglas Gregor39c02722011-06-15 16:02:29 +00001660 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001661 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1662 VectorParam->getElementType(),
1663 VectorArg->getElementType(),
1664 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001665 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001666
1667 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001668 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1669 // We can't check the number of elements, since the argument has a
1670 // dependent number of elements. This can only occur during partial
1671 // ordering.
1672
1673 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001674 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1675 VectorParam->getElementType(),
1676 VectorArg->getElementType(),
1677 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001678 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001679
Douglas Gregor39c02722011-06-15 16:02:29 +00001680 return Sema::TDK_NonDeducedMismatch;
1681 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001682
Douglas Gregor39c02722011-06-15 16:02:29 +00001683 // (clang extension)
1684 //
1685 // T __attribute__(((ext_vector_type(N))))
1686 case Type::DependentSizedExtVector: {
1687 const DependentSizedExtVectorType *VectorParam
1688 = cast<DependentSizedExtVectorType>(Param);
1689
1690 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1691 // Perform deduction on the element types.
1692 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001693 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1694 VectorParam->getElementType(),
1695 VectorArg->getElementType(),
1696 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001697 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001698
Douglas Gregor39c02722011-06-15 16:02:29 +00001699 // Perform deduction on the vector size, if we can.
1700 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001701 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001702 if (!NTTP)
1703 return Sema::TDK_Success;
1704
1705 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1706 ArgSize = VectorArg->getNumElements();
Richard Smith87d263e2016-12-25 08:05:23 +00001707 // Note that we use the "array bound" rules here; just like in that
1708 // case, we don't have any particular type for the vector size, but
1709 // we can provide one if necessary.
Richard Smith5f274382016-09-28 23:55:27 +00001710 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
Richard Smith87d263e2016-12-25 08:05:23 +00001711 S.Context.IntTy, true, Info,
Richard Smith593d6a12016-12-23 01:30:39 +00001712 Deduced);
Douglas Gregor39c02722011-06-15 16:02:29 +00001713 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001714
1715 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001716 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1717 // Perform deduction on the element types.
1718 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001719 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1720 VectorParam->getElementType(),
1721 VectorArg->getElementType(),
1722 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00001723 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001724
Douglas Gregor39c02722011-06-15 16:02:29 +00001725 // Perform deduction on the vector size, if we can.
1726 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001727 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00001728 if (!NTTP)
1729 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001730
Richard Smith5f274382016-09-28 23:55:27 +00001731 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1732 VectorArg->getSizeExpr(),
Douglas Gregor39c02722011-06-15 16:02:29 +00001733 Info, Deduced);
1734 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001735
Douglas Gregor39c02722011-06-15 16:02:29 +00001736 return Sema::TDK_NonDeducedMismatch;
1737 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001738
Douglas Gregor637d9982009-06-10 23:47:09 +00001739 case Type::TypeOfExpr:
1740 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00001741 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00001742 case Type::UnresolvedUsing:
1743 case Type::Decltype:
1744 case Type::UnaryTransform:
1745 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00001746 case Type::DeducedTemplateSpecialization:
Douglas Gregor39c02722011-06-15 16:02:29 +00001747 case Type::DependentTemplateSpecialization:
1748 case Type::PackExpansion:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001749 case Type::Pipe:
Douglas Gregor637d9982009-06-10 23:47:09 +00001750 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001751 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001752 }
1753
David Blaikiee4d798f2012-01-20 21:50:17 +00001754 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001755}
1756
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001757static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001758DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001759 TemplateParameterList *TemplateParams,
1760 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001761 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00001762 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00001763 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001764 // If the template argument is a pack expansion, perform template argument
1765 // deduction against the pattern of that expansion. This only occurs during
1766 // partial ordering.
1767 if (Arg.isPackExpansion())
1768 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001769
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001770 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001771 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00001772 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00001773
1774 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001775 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001776 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1777 Param.getAsType(),
1778 Arg.getAsType(),
1779 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001780 Info.FirstArg = Param;
1781 Info.SecondArg = Arg;
1782 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001783
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001784 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00001785 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001786 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001787 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00001788 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001789 Info.FirstArg = Param;
1790 Info.SecondArg = Arg;
1791 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00001792
1793 case TemplateArgument::TemplateExpansion:
1794 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001795
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001796 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001797 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00001798 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00001799 return Sema::TDK_Success;
1800
1801 Info.FirstArg = Param;
1802 Info.SecondArg = Arg;
1803 return Sema::TDK_NonDeducedMismatch;
1804
1805 case TemplateArgument::NullPtr:
1806 if (Arg.getKind() == TemplateArgument::NullPtr &&
1807 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001808 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001809
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001810 Info.FirstArg = Param;
1811 Info.SecondArg = Arg;
1812 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001813
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001814 case TemplateArgument::Integral:
1815 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001816 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001817 return Sema::TDK_Success;
1818
1819 Info.FirstArg = Param;
1820 Info.SecondArg = Arg;
1821 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001822 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001823
1824 if (Arg.getKind() == TemplateArgument::Expression) {
1825 Info.FirstArg = Param;
1826 Info.SecondArg = Arg;
1827 return Sema::TDK_NonDeducedMismatch;
1828 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001829
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001830 Info.FirstArg = Param;
1831 Info.SecondArg = Arg;
1832 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001833
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001834 case TemplateArgument::Expression: {
Mike Stump11289f42009-09-09 15:08:12 +00001835 if (NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001836 = getDeducedParameterFromExpr(Info, Param.getAsExpr())) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001837 if (Arg.getKind() == TemplateArgument::Integral)
Richard Smith5f274382016-09-28 23:55:27 +00001838 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00001839 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00001840 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001841 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001842 Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +00001843 if (Arg.getKind() == TemplateArgument::NullPtr)
Richard Smith5f274382016-09-28 23:55:27 +00001844 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
1845 Arg.getNullPtrType(),
Richard Smith38175a22016-09-28 22:08:38 +00001846 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001847 if (Arg.getKind() == TemplateArgument::Expression)
Richard Smith5f274382016-09-28 23:55:27 +00001848 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1849 Arg.getAsExpr(), Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001850 if (Arg.getKind() == TemplateArgument::Declaration)
Richard Smith5f274382016-09-28 23:55:27 +00001851 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1852 Arg.getAsDecl(),
1853 Arg.getParamTypeForDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00001854 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001855
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001856 Info.FirstArg = Param;
1857 Info.SecondArg = Arg;
1858 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001859 }
Mike Stump11289f42009-09-09 15:08:12 +00001860
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001861 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001862 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001863 }
Anders Carlssonbc343912009-06-15 17:04:53 +00001864 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00001865 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001866 }
Mike Stump11289f42009-09-09 15:08:12 +00001867
David Blaikiee4d798f2012-01-20 21:50:17 +00001868 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001869}
1870
Douglas Gregor7baabef2010-12-22 18:17:10 +00001871/// \brief Determine whether there is a template argument to be used for
1872/// deduction.
1873///
1874/// This routine "expands" argument packs in-place, overriding its input
1875/// parameters so that \c Args[ArgIdx] will be the available template argument.
1876///
1877/// \returns true if there is another template argument (which will be at
1878/// \c Args[ArgIdx]), false otherwise.
Richard Smith0bda5b52016-12-23 23:46:56 +00001879static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
1880 unsigned &ArgIdx) {
1881 if (ArgIdx == Args.size())
Douglas Gregor7baabef2010-12-22 18:17:10 +00001882 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001883
Douglas Gregor7baabef2010-12-22 18:17:10 +00001884 const TemplateArgument &Arg = Args[ArgIdx];
1885 if (Arg.getKind() != TemplateArgument::Pack)
1886 return true;
1887
Richard Smith0bda5b52016-12-23 23:46:56 +00001888 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
1889 Args = Arg.pack_elements();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001890 ArgIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001891 return ArgIdx < Args.size();
Douglas Gregor7baabef2010-12-22 18:17:10 +00001892}
1893
Douglas Gregord0ad2942010-12-23 01:24:45 +00001894/// \brief Determine whether the given set of template arguments has a pack
1895/// expansion that is not the last template argument.
Richard Smith0bda5b52016-12-23 23:46:56 +00001896static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
1897 bool FoundPackExpansion = false;
1898 for (const auto &A : Args) {
1899 if (FoundPackExpansion)
Douglas Gregord0ad2942010-12-23 01:24:45 +00001900 return true;
Richard Smith0bda5b52016-12-23 23:46:56 +00001901
1902 if (A.getKind() == TemplateArgument::Pack)
1903 return hasPackExpansionBeforeEnd(A.pack_elements());
1904
1905 if (A.isPackExpansion())
1906 FoundPackExpansion = true;
Douglas Gregord0ad2942010-12-23 01:24:45 +00001907 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001908
Douglas Gregord0ad2942010-12-23 01:24:45 +00001909 return false;
1910}
1911
Douglas Gregor7baabef2010-12-22 18:17:10 +00001912static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001913DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +00001914 ArrayRef<TemplateArgument> Params,
1915 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00001916 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001917 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1918 bool NumberOfArgumentsMustMatch) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001919 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001920 // If the template argument list of P contains a pack expansion that is not
1921 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001922 // non-deduced context.
Richard Smith0bda5b52016-12-23 23:46:56 +00001923 if (hasPackExpansionBeforeEnd(Params))
Douglas Gregord0ad2942010-12-23 01:24:45 +00001924 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001925
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001926 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001927 // If P has a form that contains <T> or <i>, then each argument Pi of the
1928 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001929 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001930 unsigned ArgIdx = 0, ParamIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00001931 for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) {
Douglas Gregor7baabef2010-12-22 18:17:10 +00001932 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001933 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001934
Douglas Gregor7baabef2010-12-22 18:17:10 +00001935 // Check whether we have enough arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +00001936 if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
Richard Smithec7176e2017-01-05 02:31:32 +00001937 return NumberOfArgumentsMustMatch
1938 ? Sema::TDK_MiscellaneousDeductionFailure
1939 : Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001940
Richard Smith26b86ea2016-12-31 21:41:23 +00001941 // C++1z [temp.deduct.type]p9:
1942 // During partial ordering, if Ai was originally a pack expansion [and]
1943 // Pi is not a pack expansion, template argument deduction fails.
1944 if (Args[ArgIdx].isPackExpansion())
Richard Smith44ecdbd2013-01-31 05:19:49 +00001945 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001946
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001947 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00001948 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001949 = DeduceTemplateArguments(S, TemplateParams,
1950 Params[ParamIdx], Args[ArgIdx],
1951 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001952 return Result;
1953
Douglas Gregor7baabef2010-12-22 18:17:10 +00001954 // Move to the next argument.
1955 ++ArgIdx;
1956 continue;
1957 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001958
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001959 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001960
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001961 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001962 // If Pi is a pack expansion, then the pattern of Pi is compared with
1963 // each remaining argument in the template argument list of A. Each
1964 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001965 // template parameter packs expanded by Pi.
1966 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001967
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001968 // FIXME: If there are no remaining arguments, we can bail out early
1969 // and set any deduced parameter packs to an empty argument pack.
1970 // The latter part of this is a (minor) correctness issue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001971
Richard Smith0a80d572014-05-29 01:12:14 +00001972 // Prepare to deduce the packs within the pattern.
1973 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001974
1975 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001976 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001977 // template argument (the inner SmallVectors).
Richard Smith0bda5b52016-12-23 23:46:56 +00001978 for (; hasTemplateArgumentForDeduction(Args, ArgIdx); ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001979 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001980 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001981 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1982 Info, Deduced))
1983 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001984
Richard Smith0a80d572014-05-29 01:12:14 +00001985 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001986 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001987
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001988 // Build argument packs for each of the parameter packs expanded by this
1989 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00001990 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001991 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00001992 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001993
Douglas Gregor7baabef2010-12-22 18:17:10 +00001994 return Sema::TDK_Success;
1995}
1996
Mike Stump11289f42009-09-09 15:08:12 +00001997static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00001998DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001999 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002000 const TemplateArgumentList &ParamList,
2001 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00002002 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00002003 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith0bda5b52016-12-23 23:46:56 +00002004 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
Richard Smith26b86ea2016-12-31 21:41:23 +00002005 ArgList.asArray(), Info, Deduced,
2006 /*NumberOfArgumentsMustMatch*/false);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002007}
2008
Douglas Gregor705c9002009-06-26 20:57:09 +00002009/// \brief Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00002010static bool isSameTemplateArg(ASTContext &Context,
Richard Smith0e617ec2016-12-27 07:56:27 +00002011 TemplateArgument X,
2012 const TemplateArgument &Y,
2013 bool PackExpansionMatchesPack = false) {
2014 // If we're checking deduced arguments (X) against original arguments (Y),
2015 // we will have flattened packs to non-expansions in X.
2016 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
2017 X = X.getPackExpansionPattern();
2018
Douglas Gregor705c9002009-06-26 20:57:09 +00002019 if (X.getKind() != Y.getKind())
2020 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002021
Douglas Gregor705c9002009-06-26 20:57:09 +00002022 switch (X.getKind()) {
2023 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00002024 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00002025
Douglas Gregor705c9002009-06-26 20:57:09 +00002026 case TemplateArgument::Type:
2027 return Context.getCanonicalType(X.getAsType()) ==
2028 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00002029
Douglas Gregor705c9002009-06-26 20:57:09 +00002030 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00002031 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00002032
2033 case TemplateArgument::NullPtr:
2034 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00002035
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002036 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002037 case TemplateArgument::TemplateExpansion:
2038 return Context.getCanonicalTemplateName(
2039 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2040 Context.getCanonicalTemplateName(
2041 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002042
Douglas Gregor705c9002009-06-26 20:57:09 +00002043 case TemplateArgument::Integral:
Richard Smith993f2032016-12-25 20:21:12 +00002044 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
Mike Stump11289f42009-09-09 15:08:12 +00002045
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002046 case TemplateArgument::Expression: {
2047 llvm::FoldingSetNodeID XID, YID;
2048 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002049 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002050 return XID == YID;
2051 }
Mike Stump11289f42009-09-09 15:08:12 +00002052
Douglas Gregor705c9002009-06-26 20:57:09 +00002053 case TemplateArgument::Pack:
2054 if (X.pack_size() != Y.pack_size())
2055 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002056
2057 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2058 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00002059 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002060 XP != XPEnd; ++XP, ++YP)
Richard Smith0e617ec2016-12-27 07:56:27 +00002061 if (!isSameTemplateArg(Context, *XP, *YP, PackExpansionMatchesPack))
Douglas Gregor705c9002009-06-26 20:57:09 +00002062 return false;
2063
2064 return true;
2065 }
2066
David Blaikiee4d798f2012-01-20 21:50:17 +00002067 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00002068}
2069
Douglas Gregorca4686d2011-01-04 23:35:54 +00002070/// \brief Allocate a TemplateArgumentLoc where all locations have
2071/// been initialized to the given location.
2072///
James Dennett634962f2012-06-14 21:40:34 +00002073/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00002074/// location information for.
2075///
2076/// \param NTTPType For a declaration template argument, the type of
2077/// the non-type template parameter that corresponds to this template
Richard Smith93417902016-12-23 02:00:24 +00002078/// argument. Can be null if no type sugar is available to add to the
2079/// type from the template argument.
Douglas Gregorca4686d2011-01-04 23:35:54 +00002080///
2081/// \param Loc The source location to use for the resulting template
2082/// argument.
Richard Smith7873de02016-08-11 22:25:46 +00002083TemplateArgumentLoc
2084Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2085 QualType NTTPType, SourceLocation Loc) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002086 switch (Arg.getKind()) {
2087 case TemplateArgument::Null:
2088 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002089
Douglas Gregorca4686d2011-01-04 23:35:54 +00002090 case TemplateArgument::Type:
Richard Smith7873de02016-08-11 22:25:46 +00002091 return TemplateArgumentLoc(
2092 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002093
Douglas Gregorca4686d2011-01-04 23:35:54 +00002094 case TemplateArgument::Declaration: {
Richard Smith93417902016-12-23 02:00:24 +00002095 if (NTTPType.isNull())
2096 NTTPType = Arg.getParamTypeForDecl();
Richard Smith7873de02016-08-11 22:25:46 +00002097 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2098 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002099 return TemplateArgumentLoc(TemplateArgument(E), E);
2100 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002101
Eli Friedmanb826a002012-09-26 02:36:12 +00002102 case TemplateArgument::NullPtr: {
Richard Smith93417902016-12-23 02:00:24 +00002103 if (NTTPType.isNull())
2104 NTTPType = Arg.getNullPtrType();
Richard Smith7873de02016-08-11 22:25:46 +00002105 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2106 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002107 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2108 E);
2109 }
2110
Douglas Gregorca4686d2011-01-04 23:35:54 +00002111 case TemplateArgument::Integral: {
Richard Smith7873de02016-08-11 22:25:46 +00002112 Expr *E =
2113 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002114 return TemplateArgumentLoc(TemplateArgument(E), E);
2115 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002116
Douglas Gregor9d802122011-03-02 17:09:35 +00002117 case TemplateArgument::Template:
2118 case TemplateArgument::TemplateExpansion: {
2119 NestedNameSpecifierLocBuilder Builder;
2120 TemplateName Template = Arg.getAsTemplate();
2121 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002122 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002123 else if (QualifiedTemplateName *QTN =
2124 Template.getAsQualifiedTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002125 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
Simon Pilgrim728134c2016-08-12 11:43:57 +00002126
Douglas Gregor9d802122011-03-02 17:09:35 +00002127 if (Arg.getKind() == TemplateArgument::Template)
Richard Smith7873de02016-08-11 22:25:46 +00002128 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002129 Loc);
Richard Smith7873de02016-08-11 22:25:46 +00002130
2131 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002132 Loc, Loc);
2133 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002134
Douglas Gregorca4686d2011-01-04 23:35:54 +00002135 case TemplateArgument::Expression:
2136 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002137
Douglas Gregorca4686d2011-01-04 23:35:54 +00002138 case TemplateArgument::Pack:
2139 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2140 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002141
David Blaikiee4d798f2012-01-20 21:50:17 +00002142 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002143}
2144
2145
2146/// \brief Convert the given deduced template argument and add it to the set of
2147/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002148static bool
2149ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2150 DeducedTemplateArgument Arg,
2151 NamedDecl *Template,
Craig Topper79653572013-07-08 04:13:06 +00002152 TemplateDeductionInfo &Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002153 bool IsDeduced,
Craig Topper79653572013-07-08 04:13:06 +00002154 SmallVectorImpl<TemplateArgument> &Output) {
Richard Smith37acb792016-02-03 20:15:01 +00002155 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2156 unsigned ArgumentPackIndex) {
2157 // Convert the deduced template argument into a template
2158 // argument that we can check, almost as if the user had written
2159 // the template argument explicitly.
2160 TemplateArgumentLoc ArgLoc =
Richard Smith93417902016-12-23 02:00:24 +00002161 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
Richard Smith37acb792016-02-03 20:15:01 +00002162
2163 // Check the template argument, converting it as necessary.
2164 return S.CheckTemplateArgument(
2165 Param, ArgLoc, Template, Template->getLocation(),
2166 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
Richard Smith87d263e2016-12-25 08:05:23 +00002167 IsDeduced
Richard Smith37acb792016-02-03 20:15:01 +00002168 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2169 : Sema::CTAK_Deduced)
2170 : Sema::CTAK_Specified);
2171 };
2172
Douglas Gregorca4686d2011-01-04 23:35:54 +00002173 if (Arg.getKind() == TemplateArgument::Pack) {
2174 // This is a template argument pack, so check each of its arguments against
2175 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002176 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002177 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002178 // When converting the deduced template argument, append it to the
2179 // general output list. We need to do this so that the template argument
2180 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002181 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002182 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
Richard Smith37acb792016-02-03 20:15:01 +00002183 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2184 "deduced nested pack");
Richard Smith539e8e32017-01-04 01:48:55 +00002185 if (P.isNull()) {
2186 // We deduced arguments for some elements of this pack, but not for
2187 // all of them. This happens if we get a conditionally-non-deduced
2188 // context in a pack expansion (such as an overload set in one of the
2189 // arguments).
2190 S.Diag(Param->getLocation(),
2191 diag::err_template_arg_deduced_incomplete_pack)
2192 << Arg << Param;
2193 return true;
2194 }
Richard Smith37acb792016-02-03 20:15:01 +00002195 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002196 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002197
Douglas Gregor51bc5712011-01-05 20:52:18 +00002198 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002199 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002200 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002201
Richard Smithdf18ee92016-02-03 20:40:30 +00002202 // If the pack is empty, we still need to substitute into the parameter
Richard Smith93417902016-12-23 02:00:24 +00002203 // itself, in case that substitution fails.
2204 if (PackedArgsBuilder.empty()) {
Richard Smithdf18ee92016-02-03 20:40:30 +00002205 LocalInstantiationScope Scope(S);
Richard Smithe8247752016-12-22 07:24:39 +00002206 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
Richard Smith93417902016-12-23 02:00:24 +00002207 MultiLevelTemplateArgumentList Args(TemplateArgs);
2208
2209 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2210 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2211 NTTP, Output,
2212 Template->getSourceRange());
Simon Pilgrim6f3e1ea2016-12-26 18:11:49 +00002213 if (Inst.isInvalid() ||
Richard Smith93417902016-12-23 02:00:24 +00002214 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2215 NTTP->getDeclName()).isNull())
2216 return true;
2217 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2218 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2219 TTP, Output,
2220 Template->getSourceRange());
2221 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2222 return true;
2223 }
2224 // For type parameters, no substitution is ever required.
Richard Smithdf18ee92016-02-03 20:40:30 +00002225 }
Richard Smith37acb792016-02-03 20:15:01 +00002226
Douglas Gregorca4686d2011-01-04 23:35:54 +00002227 // Create the resulting argument pack.
Benjamin Kramercce63472015-08-05 09:40:22 +00002228 Output.push_back(
2229 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002230 return false;
2231 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002232
Richard Smith37acb792016-02-03 20:15:01 +00002233 return ConvertArg(Arg, 0);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002234}
2235
Richard Smith1f5be4d2016-12-21 01:10:31 +00002236// FIXME: This should not be a template, but
2237// ClassTemplatePartialSpecializationDecl sadly does not derive from
2238// TemplateDecl.
2239template<typename TemplateDeclT>
2240static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002241 Sema &S, TemplateDeclT *Template, bool IsDeduced,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002242 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2243 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2244 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
Richard Smith86a1b132017-02-16 03:49:44 +00002245 unsigned NumAlreadyConverted = 0, bool SkipNonDeduced = false) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002246 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2247
2248 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2249 NamedDecl *Param = TemplateParams->getParam(I);
2250
2251 if (!Deduced[I].isNull()) {
2252 if (I < NumAlreadyConverted) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002253 // We may have had explicitly-specified template arguments for a
2254 // template parameter pack (that may or may not have been extended
2255 // via additional deduced arguments).
Richard Smith9c0c9862017-01-05 20:27:28 +00002256 if (Param->isParameterPack() && CurrentInstantiationScope &&
2257 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2258 // Forget the partially-substituted pack; its substitution is now
2259 // complete.
2260 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2261 // We still need to check the argument in case it was extended by
2262 // deduction.
2263 } else {
2264 // We have already fully type-checked and converted this
2265 // argument, because it was explicitly-specified. Just record the
2266 // presence of this argument.
2267 Builder.push_back(Deduced[I]);
2268 continue;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002269 }
Richard Smith1f5be4d2016-12-21 01:10:31 +00002270 }
2271
Richard Smith9c0c9862017-01-05 20:27:28 +00002272 // We may have deduced this argument, so it still needs to be
Richard Smith1f5be4d2016-12-21 01:10:31 +00002273 // checked and converted.
2274 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002275 IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002276 Info.Param = makeTemplateParameter(Param);
2277 // FIXME: These template arguments are temporary. Free them!
2278 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2279 return Sema::TDK_SubstitutionFailure;
2280 }
2281
2282 continue;
2283 }
2284
2285 // C++0x [temp.arg.explicit]p3:
2286 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2287 // be deduced to an empty sequence of template arguments.
2288 // FIXME: Where did the word "trailing" come from?
2289 if (Param->isTemplateParameterPack()) {
2290 // We may have had explicitly-specified template arguments for this
2291 // template parameter pack. If so, our empty deduction extends the
2292 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2293 const TemplateArgument *ExplicitArgs;
2294 unsigned NumExplicitArgs;
2295 if (CurrentInstantiationScope &&
2296 CurrentInstantiationScope->getPartiallySubstitutedPack(
2297 &ExplicitArgs, &NumExplicitArgs) == Param) {
2298 Builder.push_back(TemplateArgument(
2299 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
2300
2301 // Forget the partially-substituted pack; its substitution is now
2302 // complete.
2303 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2304 } else {
2305 // Go through the motions of checking the empty argument pack against
2306 // the parameter pack.
2307 DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
Richard Smith87d263e2016-12-25 08:05:23 +00002308 if (ConvertDeducedTemplateArgument(S, Param, DeducedPack, Template,
2309 Info, IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002310 Info.Param = makeTemplateParameter(Param);
2311 // FIXME: These template arguments are temporary. Free them!
2312 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2313 return Sema::TDK_SubstitutionFailure;
2314 }
2315 }
2316 continue;
2317 }
2318
2319 // Substitute into the default template argument, if available.
2320 bool HasDefaultArg = false;
2321 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2322 if (!TD) {
2323 assert(isa<ClassTemplatePartialSpecializationDecl>(Template));
2324 return Sema::TDK_Incomplete;
2325 }
2326
2327 TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2328 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2329 HasDefaultArg);
2330
2331 // If there was no default argument, deduction is incomplete.
2332 if (DefArg.getArgument().isNull()) {
Richard Smith86a1b132017-02-16 03:49:44 +00002333 if (SkipNonDeduced) {
2334 Builder.push_back(TemplateArgument());
2335 continue;
2336 }
2337
Richard Smith1f5be4d2016-12-21 01:10:31 +00002338 Info.Param = makeTemplateParameter(
2339 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2340 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
Richard Smith1f5be4d2016-12-21 01:10:31 +00002341 return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2342 : Sema::TDK_Incomplete;
2343 }
2344
2345 // Check whether we can actually use the default argument.
2346 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2347 TD->getSourceRange().getEnd(), 0, Builder,
2348 Sema::CTAK_Specified)) {
2349 Info.Param = makeTemplateParameter(
2350 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2351 // FIXME: These template arguments are temporary. Free them!
2352 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2353 return Sema::TDK_SubstitutionFailure;
2354 }
2355
2356 // If we get here, we successfully used the default template argument.
2357 }
2358
2359 return Sema::TDK_Success;
2360}
2361
Benjamin Kramer357c9e12017-02-11 12:21:17 +00002362static DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
Richard Smith0da6dc42016-12-24 16:40:51 +00002363 if (auto *DC = dyn_cast<DeclContext>(D))
2364 return DC;
2365 return D->getDeclContext();
2366}
2367
2368template<typename T> struct IsPartialSpecialization {
2369 static constexpr bool value = false;
2370};
2371template<>
2372struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
2373 static constexpr bool value = true;
2374};
2375template<>
2376struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
2377 static constexpr bool value = true;
2378};
2379
2380/// Complete template argument deduction for a partial specialization.
2381template <typename T>
2382static typename std::enable_if<IsPartialSpecialization<T>::value,
2383 Sema::TemplateDeductionResult>::type
2384FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00002385 Sema &S, T *Partial, bool IsPartialOrdering,
2386 const TemplateArgumentList &TemplateArgs,
Richard Smith0da6dc42016-12-24 16:40:51 +00002387 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2388 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002389 // Unevaluated SFINAE context.
2390 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002391 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002392
Richard Smith0da6dc42016-12-24 16:40:51 +00002393 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
Douglas Gregor684268d2010-04-29 06:21:43 +00002394
2395 // C++ [temp.deduct.type]p2:
2396 // [...] or if any template argument remains neither deduced nor
2397 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002398 SmallVector<TemplateArgument, 4> Builder;
Richard Smith87d263e2016-12-25 08:05:23 +00002399 if (auto Result = ConvertDeducedTemplateArguments(
2400 S, Partial, IsPartialOrdering, Deduced, Info, Builder))
Richard Smith1f5be4d2016-12-21 01:10:31 +00002401 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002402
Douglas Gregor684268d2010-04-29 06:21:43 +00002403 // Form the template argument list from the deduced template arguments.
2404 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002405 = TemplateArgumentList::CreateCopy(S.Context, Builder);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002406
Douglas Gregor684268d2010-04-29 06:21:43 +00002407 Info.reset(DeducedArgumentList);
2408
2409 // Substitute the deduced template arguments into the template
2410 // arguments of the class template partial specialization, and
2411 // verify that the instantiated template arguments are both valid
2412 // and are equivalent to the template arguments originally provided
2413 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002414 LocalInstantiationScope InstScope(S);
Richard Smith0da6dc42016-12-24 16:40:51 +00002415 auto *Template = Partial->getSpecializedTemplate();
2416 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2417 Partial->getTemplateArgsAsWritten();
2418 const TemplateArgumentLoc *PartialTemplateArgs =
2419 PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002420
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002421 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2422 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002423
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002424 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002425 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2426 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2427 if (ParamIdx >= Partial->getTemplateParameters()->size())
2428 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2429
Richard Smith0da6dc42016-12-24 16:40:51 +00002430 Decl *Param = const_cast<NamedDecl *>(
2431 Partial->getTemplateParameters()->getParam(ParamIdx));
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002432 Info.Param = makeTemplateParameter(Param);
2433 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2434 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002435 }
2436
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002437 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Richard Smith0da6dc42016-12-24 16:40:51 +00002438 if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2439 false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002440 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002441
Richard Smith0da6dc42016-12-24 16:40:51 +00002442 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002443 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002444 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002445 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002446 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002447 Info.FirstArg = TemplateArgs[I];
2448 Info.SecondArg = InstArg;
2449 return Sema::TDK_NonDeducedMismatch;
2450 }
2451 }
2452
2453 if (Trap.hasErrorOccurred())
2454 return Sema::TDK_SubstitutionFailure;
2455
2456 return Sema::TDK_Success;
2457}
2458
Richard Smith0e617ec2016-12-27 07:56:27 +00002459/// Complete template argument deduction for a class or variable template,
2460/// when partial ordering against a partial specialization.
2461// FIXME: Factor out duplication with partial specialization version above.
Benjamin Kramer357c9e12017-02-11 12:21:17 +00002462static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
Richard Smith0e617ec2016-12-27 07:56:27 +00002463 Sema &S, TemplateDecl *Template, bool PartialOrdering,
2464 const TemplateArgumentList &TemplateArgs,
2465 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2466 TemplateDeductionInfo &Info) {
2467 // Unevaluated SFINAE context.
2468 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2469 Sema::SFINAETrap Trap(S);
2470
2471 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
2472
2473 // C++ [temp.deduct.type]p2:
2474 // [...] or if any template argument remains neither deduced nor
2475 // explicitly specified, template argument deduction fails.
2476 SmallVector<TemplateArgument, 4> Builder;
2477 if (auto Result = ConvertDeducedTemplateArguments(
2478 S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder))
2479 return Result;
2480
2481 // Check that we produced the correct argument list.
2482 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2483 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2484 TemplateArgument InstArg = Builder[I];
2485 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
2486 /*PackExpansionMatchesPack*/true)) {
2487 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2488 Info.FirstArg = TemplateArgs[I];
2489 Info.SecondArg = InstArg;
2490 return Sema::TDK_NonDeducedMismatch;
2491 }
2492 }
2493
2494 if (Trap.hasErrorOccurred())
2495 return Sema::TDK_SubstitutionFailure;
2496
2497 return Sema::TDK_Success;
2498}
2499
2500
Douglas Gregor170bc422009-06-12 22:31:52 +00002501/// \brief Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002502/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002503/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002504Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002505Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002506 const TemplateArgumentList &TemplateArgs,
2507 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002508 if (Partial->isInvalidDecl())
2509 return TDK_Invalid;
2510
Douglas Gregor170bc422009-06-12 22:31:52 +00002511 // C++ [temp.class.spec.match]p2:
2512 // A partial specialization matches a given actual template
2513 // argument list if the template arguments of the partial
2514 // specialization can be deduced from the actual template argument
2515 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002516
2517 // Unevaluated SFINAE context.
2518 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002519 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002520
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002521 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002522 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002523 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002524 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002525 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002526 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002527 TemplateArgs, Info, Deduced))
2528 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002529
Richard Smith80934652012-07-16 01:09:10 +00002530 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002531 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2532 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002533 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002534 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002535
Douglas Gregore1416332009-06-14 08:02:22 +00002536 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002537 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002538
Richard Smith87d263e2016-12-25 08:05:23 +00002539 return ::FinishTemplateArgumentDeduction(
2540 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002541}
Douglas Gregor91772d12009-06-13 00:26:55 +00002542
Larisse Voufo39a1e502013-08-06 01:03:05 +00002543/// \brief Perform template argument deduction to determine whether
2544/// the given template arguments match the given variable template
2545/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo39a1e502013-08-06 01:03:05 +00002546Sema::TemplateDeductionResult
2547Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2548 const TemplateArgumentList &TemplateArgs,
2549 TemplateDeductionInfo &Info) {
2550 if (Partial->isInvalidDecl())
2551 return TDK_Invalid;
2552
2553 // C++ [temp.class.spec.match]p2:
2554 // A partial specialization matches a given actual template
2555 // argument list if the template arguments of the partial
2556 // specialization can be deduced from the actual template argument
2557 // list (14.8.2).
2558
2559 // Unevaluated SFINAE context.
2560 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2561 SFINAETrap Trap(*this);
2562
2563 SmallVector<DeducedTemplateArgument, 4> Deduced;
2564 Deduced.resize(Partial->getTemplateParameters()->size());
2565 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2566 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2567 TemplateArgs, Info, Deduced))
2568 return Result;
2569
2570 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002571 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2572 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002573 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002574 return TDK_InstantiationDepth;
2575
2576 if (Trap.hasErrorOccurred())
2577 return Sema::TDK_SubstitutionFailure;
2578
Richard Smith87d263e2016-12-25 08:05:23 +00002579 return ::FinishTemplateArgumentDeduction(
2580 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002581}
2582
Douglas Gregorfc516c92009-06-26 23:27:24 +00002583/// \brief Determine whether the given type T is a simple-template-id type.
2584static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002585 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002586 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002587 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002588
Douglas Gregorfc516c92009-06-26 23:27:24 +00002589 return false;
2590}
Douglas Gregor9b146582009-07-08 20:55:45 +00002591
Richard Smithde0d34a2017-01-09 07:14:40 +00002592static void
2593MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
2594 bool OnlyDeduced,
2595 unsigned Level,
2596 llvm::SmallBitVector &Deduced);
2597
Douglas Gregor9b146582009-07-08 20:55:45 +00002598/// \brief Substitute the explicitly-provided template arguments into the
2599/// given function template according to C++ [temp.arg.explicit].
2600///
2601/// \param FunctionTemplate the function template into which the explicit
2602/// template arguments will be substituted.
2603///
James Dennett634962f2012-06-14 21:40:34 +00002604/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002605/// arguments.
2606///
Mike Stump11289f42009-09-09 15:08:12 +00002607/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002608/// with the converted and checked explicit template arguments.
2609///
Mike Stump11289f42009-09-09 15:08:12 +00002610/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002611/// parameters.
2612///
2613/// \param FunctionType if non-NULL, the result type of the function template
2614/// will also be instantiated and the pointed-to value will be updated with
2615/// the instantiated function type.
2616///
2617/// \param Info if substitution fails for any reason, this object will be
2618/// populated with more information about the failure.
2619///
2620/// \returns TDK_Success if substitution was successful, or some failure
2621/// condition.
2622Sema::TemplateDeductionResult
2623Sema::SubstituteExplicitTemplateArguments(
2624 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002625 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002626 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2627 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002628 QualType *FunctionType,
2629 TemplateDeductionInfo &Info) {
2630 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2631 TemplateParameterList *TemplateParams
2632 = FunctionTemplate->getTemplateParameters();
2633
John McCall6b51f282009-11-23 01:53:49 +00002634 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002635 // No arguments to substitute; just copy over the parameter types and
2636 // fill in the function type.
David Majnemer59f77922016-06-24 04:05:48 +00002637 for (auto P : Function->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002638 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002639
Douglas Gregor9b146582009-07-08 20:55:45 +00002640 if (FunctionType)
2641 *FunctionType = Function->getType();
2642 return TDK_Success;
2643 }
Mike Stump11289f42009-09-09 15:08:12 +00002644
Eli Friedman77dcc722012-02-08 03:07:05 +00002645 // Unevaluated SFINAE context.
2646 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002647 SFINAETrap Trap(*this);
2648
Douglas Gregor9b146582009-07-08 20:55:45 +00002649 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002650 // Template arguments that are present shall be specified in the
2651 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002652 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002653 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002654 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002655
2656 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002657 // explicitly-specified template arguments against this function template,
2658 // and then substitute them into the function parameter types.
Richard Smithde0d34a2017-01-09 07:14:40 +00002659 SmallVector<TemplateArgument, 4> DeducedArgs;
Nick Lewycky56412332014-01-11 02:37:12 +00002660 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2661 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002662 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2663 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002664 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00002665 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00002666
Richard Smith11255ec2017-01-18 19:19:22 +00002667 if (CheckTemplateArgumentList(FunctionTemplate, SourceLocation(),
2668 ExplicitTemplateArgs, true, Builder, false) ||
2669 Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002670 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00002671 if (Index >= TemplateParams->size())
2672 Index = TemplateParams->size() - 1;
2673 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00002674 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00002675 }
Mike Stump11289f42009-09-09 15:08:12 +00002676
Douglas Gregor9b146582009-07-08 20:55:45 +00002677 // Form the template argument list from the explicitly-specified
2678 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00002679 TemplateArgumentList *ExplicitArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002680 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor9b146582009-07-08 20:55:45 +00002681 Info.reset(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002682
John McCall036855a2010-10-12 19:40:14 +00002683 // Template argument deduction and the final substitution should be
2684 // done in the context of the templated declaration. Explicit
2685 // argument substitution, on the other hand, needs to happen in the
2686 // calling context.
2687 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2688
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002689 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002690 // note that the template argument pack is partially substituted and record
2691 // the explicit template arguments. They'll be used as part of deduction
2692 // for this template parameter pack.
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002693 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2694 const TemplateArgument &Arg = Builder[I];
2695 if (Arg.getKind() == TemplateArgument::Pack) {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002696 CurrentInstantiationScope->SetPartiallySubstitutedPack(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002697 TemplateParams->getParam(I),
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002698 Arg.pack_begin(),
2699 Arg.pack_size());
2700 break;
2701 }
2702 }
2703
Richard Smith5e580292012-02-10 09:58:53 +00002704 const FunctionProtoType *Proto
2705 = Function->getType()->getAs<FunctionProtoType>();
2706 assert(Proto && "Function template does not have a prototype?");
2707
Richard Smith70b13042015-01-09 01:19:56 +00002708 // Isolate our substituted parameters from our caller.
2709 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2710
John McCallc8e321d2016-03-01 02:09:25 +00002711 ExtParameterInfoBuilder ExtParamInfos;
2712
Douglas Gregor9b146582009-07-08 20:55:45 +00002713 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00002714 // explicitly-specified template arguments. If the function has a trailing
2715 // return type, substitute it after the arguments to ensure we substitute
2716 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00002717 if (Proto->hasTrailingReturn()) {
David Majnemer59f77922016-06-24 04:05:48 +00002718 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002719 Proto->getExtParameterInfosOrNull(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002720 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002721 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Douglas Gregor3024f072012-04-16 07:05:22 +00002722 return TDK_SubstitutionFailure;
2723 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002724
Richard Smith5e580292012-02-10 09:58:53 +00002725 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00002726 QualType ResultType;
2727 {
2728 // C++11 [expr.prim.general]p3:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002729 // If a declaration declares a member function or member function
2730 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00002731 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Simon Pilgrim728134c2016-08-12 11:43:57 +00002732 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00002733 // declarator.
2734 unsigned ThisTypeQuals = 0;
Craig Topperc3ec1492014-05-26 06:22:03 +00002735 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002736 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2737 ThisContext = Method->getParent();
2738 ThisTypeQuals = Method->getTypeQualifiers();
2739 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002740
Douglas Gregor3024f072012-04-16 07:05:22 +00002741 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002742 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00002743
2744 ResultType =
2745 SubstType(Proto->getReturnType(),
2746 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2747 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00002748 if (ResultType.isNull() || Trap.hasErrorOccurred())
2749 return TDK_SubstitutionFailure;
2750 }
John McCallc8e321d2016-03-01 02:09:25 +00002751
Richard Smith5e580292012-02-10 09:58:53 +00002752 // Instantiate the types of each of the function parameters given the
2753 // explicitly-specified template arguments if we didn't do so earlier.
2754 if (!Proto->hasTrailingReturn() &&
David Majnemer59f77922016-06-24 04:05:48 +00002755 SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00002756 Proto->getExtParameterInfosOrNull(),
Richard Smith5e580292012-02-10 09:58:53 +00002757 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00002758 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Richard Smith5e580292012-02-10 09:58:53 +00002759 return TDK_SubstitutionFailure;
2760
Douglas Gregor9b146582009-07-08 20:55:45 +00002761 if (FunctionType) {
John McCallc8e321d2016-03-01 02:09:25 +00002762 auto EPI = Proto->getExtProtoInfo();
2763 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
Jordan Rose5c382722013-03-08 21:51:21 +00002764 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002765 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00002766 Function->getDeclName(),
John McCallc8e321d2016-03-01 02:09:25 +00002767 EPI);
Douglas Gregor9b146582009-07-08 20:55:45 +00002768 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2769 return TDK_SubstitutionFailure;
2770 }
Mike Stump11289f42009-09-09 15:08:12 +00002771
Douglas Gregor9b146582009-07-08 20:55:45 +00002772 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002773 // Trailing template arguments that can be deduced (14.8.2) may be
2774 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00002775 // template arguments can be deduced, they may all be omitted; in this
2776 // case, the empty template argument list <> itself may also be omitted.
2777 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002778 // Take all of the explicitly-specified arguments and put them into
2779 // the set of deduced template arguments. Explicitly-specified
2780 // parameter packs, however, will be set to NULL since the deduction
2781 // mechanisms handle explicitly-specified argument packs directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00002782 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002783 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2784 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2785 if (Arg.getKind() == TemplateArgument::Pack)
2786 Deduced.push_back(DeducedTemplateArgument());
2787 else
2788 Deduced.push_back(Arg);
2789 }
Mike Stump11289f42009-09-09 15:08:12 +00002790
Douglas Gregor9b146582009-07-08 20:55:45 +00002791 return TDK_Success;
2792}
2793
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002794/// \brief Check whether the deduced argument type for a call to a function
2795/// template matches the actual argument type per C++ [temp.deduct.call]p4.
Simon Pilgrim728134c2016-08-12 11:43:57 +00002796static bool
2797CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002798 QualType DeducedA) {
2799 ASTContext &Context = S.Context;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002800
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002801 QualType A = OriginalArg.OriginalArgType;
2802 QualType OriginalParamType = OriginalArg.OriginalParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002803
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002804 // Check for type equality (top-level cv-qualifiers are ignored).
2805 if (Context.hasSameUnqualifiedType(A, DeducedA))
2806 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002807
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002808 // Strip off references on the argument types; they aren't needed for
2809 // the following checks.
2810 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2811 DeducedA = DeducedARef->getPointeeType();
2812 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2813 A = ARef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002814
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002815 // C++ [temp.deduct.call]p4:
2816 // [...] However, there are three cases that allow a difference:
Simon Pilgrim728134c2016-08-12 11:43:57 +00002817 // - If the original P is a reference type, the deduced A (i.e., the
2818 // type referred to by the reference) can be more cv-qualified than
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002819 // the transformed A.
2820 if (const ReferenceType *OriginalParamRef
2821 = OriginalParamType->getAs<ReferenceType>()) {
2822 // We don't want to keep the reference around any more.
2823 OriginalParamType = OriginalParamRef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00002824
Richard Smith1be59c52016-10-22 01:32:19 +00002825 // FIXME: Resolve core issue (no number yet): if the original P is a
2826 // reference type and the transformed A is function type "noexcept F",
2827 // the deduced A can be F.
2828 QualType Tmp;
2829 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
2830 return false;
2831
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002832 Qualifiers AQuals = A.getQualifiers();
2833 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00002834
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002835 // Under Objective-C++ ARC, the deduced type may have implicitly
2836 // been given strong or (when dealing with a const reference)
2837 // unsafe_unretained lifetime. If so, update the original
2838 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00002839 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002840 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2841 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2842 (DeducedAQuals.hasConst() &&
2843 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2844 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00002845 }
2846
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002847 if (AQuals == DeducedAQuals) {
2848 // Qualifiers match; there's nothing to do.
2849 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Douglas Gregorddaae522011-06-17 14:36:00 +00002850 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002851 } else {
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002852 // Qualifiers are compatible, so have the argument type adopt the
2853 // deduced argument type's qualifiers as if we had performed the
2854 // qualification conversion.
2855 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2856 }
2857 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002858
2859 // - The transformed A can be another pointer or pointer to member
Richard Smith3c4f8d22016-10-16 17:54:23 +00002860 // type that can be converted to the deduced A via a function pointer
2861 // conversion and/or a qualification conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00002862 //
Richard Smith1be59c52016-10-22 01:32:19 +00002863 // Also allow conversions which merely strip __attribute__((noreturn)) from
2864 // function types (recursively).
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002865 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00002866 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002867 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00002868 (S.IsQualificationConversion(A, DeducedA, false,
2869 ObjCLifetimeConversion) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +00002870 S.IsFunctionConversion(A, DeducedA, ResultTy)))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002871 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002872
Simon Pilgrim728134c2016-08-12 11:43:57 +00002873 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002874 // transformed A can be a derived class of the deduced A. [...]
Simon Pilgrim728134c2016-08-12 11:43:57 +00002875 // [...] Likewise, if P is a pointer to a class of the form
2876 // simple-template-id, the transformed A can be a pointer to a
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002877 // derived class pointed to by the deduced A.
2878 if (const PointerType *OriginalParamPtr
2879 = OriginalParamType->getAs<PointerType>()) {
2880 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2881 if (const PointerType *APtr = A->getAs<PointerType>()) {
2882 if (A->getPointeeType()->isRecordType()) {
2883 OriginalParamType = OriginalParamPtr->getPointeeType();
2884 DeducedA = DeducedAPtr->getPointeeType();
2885 A = APtr->getPointeeType();
2886 }
2887 }
2888 }
2889 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002890
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002891 if (Context.hasSameUnqualifiedType(A, DeducedA))
2892 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002893
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002894 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith0f59cb32015-12-18 21:45:41 +00002895 S.IsDerivedFrom(SourceLocation(), A, DeducedA))
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002896 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002897
Douglas Gregor2ead4c42011-06-17 05:18:17 +00002898 return true;
2899}
2900
Richard Smithc92d2062017-01-05 23:02:44 +00002901/// Find the pack index for a particular parameter index in an instantiation of
2902/// a function template with specific arguments.
2903///
2904/// \return The pack index for whichever pack produced this parameter, or -1
2905/// if this was not produced by a parameter. Intended to be used as the
2906/// ArgumentPackSubstitutionIndex for further substitutions.
2907// FIXME: We should track this in OriginalCallArgs so we don't need to
2908// reconstruct it here.
2909static unsigned getPackIndexForParam(Sema &S,
2910 FunctionTemplateDecl *FunctionTemplate,
2911 const MultiLevelTemplateArgumentList &Args,
2912 unsigned ParamIdx) {
2913 unsigned Idx = 0;
2914 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
2915 if (PD->isParameterPack()) {
2916 unsigned NumExpansions =
2917 S.getNumArgumentsInExpansion(PD->getType(), Args).getValueOr(1);
2918 if (Idx + NumExpansions > ParamIdx)
2919 return ParamIdx - Idx;
2920 Idx += NumExpansions;
2921 } else {
2922 if (Idx == ParamIdx)
2923 return -1; // Not a pack expansion
2924 ++Idx;
2925 }
2926 }
2927
2928 llvm_unreachable("parameter index would not be produced from template");
2929}
2930
Mike Stump11289f42009-09-09 15:08:12 +00002931/// \brief Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00002932/// checking the deduced template arguments for completeness and forming
2933/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00002934///
2935/// \param OriginalCallArgs If non-NULL, the original call arguments against
2936/// which the deduced argument types should be compared.
Richard Smith6eedfe72017-01-09 08:01:21 +00002937Sema::TemplateDeductionResult Sema::FinishTemplateArgumentDeduction(
2938 FunctionTemplateDecl *FunctionTemplate,
2939 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2940 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
2941 TemplateDeductionInfo &Info,
2942 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2943 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002944 // Unevaluated SFINAE context.
2945 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002946 SFINAETrap Trap(*this);
2947
Douglas Gregor9b146582009-07-08 20:55:45 +00002948 // Enter a new template instantiation context while we instantiate the
2949 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00002950 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002951 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2952 DeducedArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002953 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2954 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002955 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00002956 return TDK_InstantiationDepth;
2957
John McCalle23b8712010-04-29 01:18:58 +00002958 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00002959
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002960 // C++ [temp.deduct.type]p2:
2961 // [...] or if any template argument remains neither deduced nor
2962 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002963 SmallVector<TemplateArgument, 4> Builder;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002964 if (auto Result = ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002965 *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002966 CurrentInstantiationScope, NumExplicitlySpecified,
2967 PartialOverloading))
2968 return Result;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002969
Richard Smith6eedfe72017-01-09 08:01:21 +00002970 // C++ [temp.deduct.call]p10: [DR1391]
2971 // If deduction succeeds for all parameters that contain
2972 // template-parameters that participate in template argument deduction,
2973 // and all template arguments are explicitly specified, deduced, or
2974 // obtained from default template arguments, remaining parameters are then
2975 // compared with the corresponding arguments. For each remaining parameter
2976 // P with a type that was non-dependent before substitution of any
2977 // explicitly-specified template arguments, if the corresponding argument
2978 // A cannot be implicitly converted to P, deduction fails.
2979 if (CheckNonDependent())
2980 return TDK_NonDependentConversionFailure;
2981
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002982 // Form the template argument list from the deduced template arguments.
2983 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002984 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00002985 Info.reset(DeducedArgumentList);
2986
Mike Stump11289f42009-09-09 15:08:12 +00002987 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00002988 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00002989 DeclContext *Owner = FunctionTemplate->getDeclContext();
2990 if (FunctionTemplate->getFriendObjectKind())
2991 Owner = FunctionTemplate->getLexicalDeclContext();
Richard Smithc92d2062017-01-05 23:02:44 +00002992 MultiLevelTemplateArgumentList SubstArgs(*DeducedArgumentList);
Douglas Gregor9b146582009-07-08 20:55:45 +00002993 Specialization = cast_or_null<FunctionDecl>(
Richard Smithc92d2062017-01-05 23:02:44 +00002994 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, SubstArgs));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00002995 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00002996 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00002997
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002998 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00002999 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003000
Mike Stump11289f42009-09-09 15:08:12 +00003001 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00003002 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00003003 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
3004 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00003005 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00003006
Douglas Gregorebcfbb52011-10-12 20:35:48 +00003007 // There may have been an error that did not prevent us from constructing a
3008 // declaration. Mark the declaration invalid and return with a substitution
3009 // failure.
3010 if (Trap.hasErrorOccurred()) {
3011 Specialization->setInvalidDecl(true);
3012 return TDK_SubstitutionFailure;
3013 }
3014
Douglas Gregore65aacb2011-06-16 16:50:48 +00003015 if (OriginalCallArgs) {
3016 // C++ [temp.deduct.call]p4:
3017 // In general, the deduction process attempts to find template argument
Simon Pilgrim728134c2016-08-12 11:43:57 +00003018 // values that will make the deduced A identical to A (after the type A
Douglas Gregore65aacb2011-06-16 16:50:48 +00003019 // is transformed as described above). [...]
Richard Smithc92d2062017-01-05 23:02:44 +00003020 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
Douglas Gregore65aacb2011-06-16 16:50:48 +00003021 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
3022 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Simon Pilgrim728134c2016-08-12 11:43:57 +00003023
Richard Smithc92d2062017-01-05 23:02:44 +00003024 auto ParamIdx = OriginalArg.ArgIdx;
Douglas Gregore65aacb2011-06-16 16:50:48 +00003025 if (ParamIdx >= Specialization->getNumParams())
Richard Smithc92d2062017-01-05 23:02:44 +00003026 // FIXME: This presumably means a pack ended up smaller than we
3027 // expected while deducing. Should this not result in deduction
3028 // failure? Can it even happen?
Douglas Gregore65aacb2011-06-16 16:50:48 +00003029 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003030
Richard Smithc92d2062017-01-05 23:02:44 +00003031 QualType DeducedA;
3032 if (!OriginalArg.DecomposedParam) {
3033 // P is one of the function parameters, just look up its substituted
3034 // type.
3035 DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
3036 } else {
3037 // P is a decomposed element of a parameter corresponding to a
3038 // braced-init-list argument. Substitute back into P to find the
3039 // deduced A.
3040 QualType &CacheEntry =
3041 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
3042 if (CacheEntry.isNull()) {
3043 ArgumentPackSubstitutionIndexRAII PackIndex(
3044 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
3045 ParamIdx));
3046 CacheEntry =
3047 SubstType(OriginalArg.OriginalParamType, SubstArgs,
3048 Specialization->getTypeSpecStartLoc(),
3049 Specialization->getDeclName());
3050 }
3051 DeducedA = CacheEntry;
3052 }
3053
Richard Smith9b534542015-12-31 02:02:54 +00003054 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
3055 Info.FirstArg = TemplateArgument(DeducedA);
3056 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3057 Info.CallArgIndex = OriginalArg.ArgIdx;
Richard Smithc92d2062017-01-05 23:02:44 +00003058 return OriginalArg.DecomposedParam ? TDK_DeducedMismatchNested
3059 : TDK_DeducedMismatch;
Richard Smith9b534542015-12-31 02:02:54 +00003060 }
Douglas Gregore65aacb2011-06-16 16:50:48 +00003061 }
3062 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003063
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003064 // If we suppressed any diagnostics while performing template argument
3065 // deduction, and if we haven't already instantiated this declaration,
3066 // keep track of these diagnostics. They'll be emitted if this specialization
3067 // is actually used.
3068 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00003069 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003070 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
3071 if (Pos == SuppressedDiagnostics.end())
3072 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
3073 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003074 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003075
Mike Stump11289f42009-09-09 15:08:12 +00003076 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003077}
3078
John McCall8d08b9b2010-08-27 09:08:28 +00003079/// Gets the type of a function for template-argument-deducton
3080/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00003081static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00003082 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003083 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003084 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00003085 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Richard Smith2a7d4812013-05-04 07:00:32 +00003086 return QualType();
3087
John McCallc1f69982010-02-02 02:21:27 +00003088 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00003089 if (Method->isInstance()) {
3090 // An instance method that's referenced in a form that doesn't
3091 // look like a member pointer is just invalid.
3092 if (!R.HasFormOfMemberPointer) return QualType();
3093
Richard Smith2a7d4812013-05-04 07:00:32 +00003094 return S.Context.getMemberPointerType(Fn->getType(),
3095 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00003096 }
3097
3098 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003099 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00003100}
3101
3102/// Apply the deduction rules for overload sets.
3103///
3104/// \return the null type if this argument should be treated as an
3105/// undeduced context
3106static QualType
3107ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003108 Expr *Arg, QualType ParamType,
3109 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003110
John McCall8d08b9b2010-08-27 09:08:28 +00003111 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00003112
John McCall8d08b9b2010-08-27 09:08:28 +00003113 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00003114
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003115 // C++0x [temp.deduct.call]p4
3116 unsigned TDF = 0;
3117 if (ParamWasReference)
3118 TDF |= TDF_ParamWithReferenceType;
3119 if (R.IsAddressOfOperand)
3120 TDF |= TDF_IgnoreQualifiers;
3121
John McCallc1f69982010-02-02 02:21:27 +00003122 // C++0x [temp.deduct.call]p6:
3123 // When P is a function type, pointer to function type, or pointer
3124 // to member function type:
3125
3126 if (!ParamType->isFunctionType() &&
3127 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003128 !ParamType->isMemberFunctionPointerType()) {
3129 if (Ovl->hasExplicitTemplateArgs()) {
3130 // But we can still look for an explicit specialization.
3131 if (FunctionDecl *ExplicitSpec
3132 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003133 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003134 }
John McCallc1f69982010-02-02 02:21:27 +00003135
George Burgess IVcc2f3552016-03-19 21:51:45 +00003136 DeclAccessPair DAP;
3137 if (FunctionDecl *Viable =
3138 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3139 return GetTypeOfFunction(S, R, Viable);
3140
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003141 return QualType();
3142 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003143
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003144 // Gather the explicit template arguments, if any.
3145 TemplateArgumentListInfo ExplicitTemplateArgs;
3146 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003147 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003148 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003149 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3150 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003151 NamedDecl *D = (*I)->getUnderlyingDecl();
3152
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003153 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3154 // - If the argument is an overload set containing one or more
3155 // function templates, the parameter is treated as a
3156 // non-deduced context.
3157 if (!Ovl->hasExplicitTemplateArgs())
3158 return QualType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003159
3160 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003161 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003162 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003163 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3164 Specialization, Info))
3165 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003166
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003167 D = Specialization;
3168 }
John McCallc1f69982010-02-02 02:21:27 +00003169
3170 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003171 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003172 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003173
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003174 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003175 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003176 ArgType->isFunctionType())
3177 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003178
John McCallc1f69982010-02-02 02:21:27 +00003179 // - If the argument is an overload set (not containing function
3180 // templates), trial argument deduction is attempted using each
3181 // of the members of the set. If deduction succeeds for only one
3182 // of the overload set members, that member is used as the
3183 // argument value for the deduction. If deduction succeeds for
3184 // more than one member of the overload set the parameter is
3185 // treated as a non-deduced context.
3186
3187 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3188 // Type deduction is done independently for each P/A pair, and
3189 // the deduced template argument values are then combined.
3190 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003191 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003192 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003193 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003194 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003195 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3196 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003197 if (Result) continue;
3198 if (!Match.isNull()) return QualType();
3199 Match = ArgType;
3200 }
3201
3202 return Match;
3203}
3204
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003205/// \brief Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003206/// described in C++ [temp.deduct.call].
3207///
3208/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003209/// argument deduction based on this P/A pair because the argument is an
3210/// overloaded function set that could not be resolved.
Richard Smith32918772017-02-14 00:25:28 +00003211static bool AdjustFunctionParmAndArgTypesForDeduction(
3212 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3213 QualType &ParamType, QualType &ArgType, Expr *Arg, unsigned &TDF) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003214 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003215 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003216 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003217 if (ParamType.hasQualifiers())
3218 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003219
3220 // [...] If P is a reference type, the type referred to by P is
3221 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003222 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003223 if (ParamRefType)
3224 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003225
Nathan Sidwell96090022015-01-16 15:20:14 +00003226 // Overload sets usually make this parameter an undeduced context,
3227 // but there are sometimes special circumstances. Typically
3228 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003229 if (ArgType == S.Context.OverloadTy) {
3230 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3231 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003232 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003233 if (ArgType.isNull())
3234 return true;
3235 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003236
Douglas Gregor7825bf32011-01-06 22:09:01 +00003237 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003238 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003239 if (ArgType->isIncompleteArrayType()) {
3240 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003241 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003242 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003243
Richard Smith32918772017-02-14 00:25:28 +00003244 // C++1z [temp.deduct.call]p3:
3245 // If P is a forwarding reference and the argument is an lvalue, the type
3246 // "lvalue reference to A" is used in place of A for type deduction.
3247 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003248 Arg->isLValue())
3249 ArgType = S.Context.getLValueReferenceType(ArgType);
3250 } else {
3251 // C++ [temp.deduct.call]p2:
3252 // If P is not a reference type:
3253 // - If A is an array type, the pointer type produced by the
3254 // array-to-pointer standard conversion (4.2) is used in place of
3255 // A for type deduction; otherwise,
3256 if (ArgType->isArrayType())
3257 ArgType = S.Context.getArrayDecayedType(ArgType);
3258 // - If A is a function type, the pointer type produced by the
3259 // function-to-pointer standard conversion (4.3) is used in place
3260 // of A for type deduction; otherwise,
3261 else if (ArgType->isFunctionType())
3262 ArgType = S.Context.getPointerType(ArgType);
3263 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003264 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003265 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003266 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003267 }
3268 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003269
Douglas Gregor7825bf32011-01-06 22:09:01 +00003270 // C++0x [temp.deduct.call]p4:
3271 // In general, the deduction process attempts to find template argument
3272 // values that will make the deduced A identical to A (after the type A
3273 // is transformed as described above). [...]
3274 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003275
Douglas Gregor7825bf32011-01-06 22:09:01 +00003276 // - If the original P is a reference type, the deduced A (i.e., the
3277 // type referred to by the reference) can be more cv-qualified than
3278 // the transformed A.
3279 if (ParamRefType)
3280 TDF |= TDF_ParamWithReferenceType;
3281 // - The transformed A can be another pointer or pointer to member
3282 // type that can be converted to the deduced A via a qualification
3283 // conversion (4.4).
3284 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3285 ArgType->isObjCObjectPointerType())
3286 TDF |= TDF_IgnoreQualifiers;
3287 // - If P is a class and P has the form simple-template-id, then the
3288 // transformed A can be a derived class of the deduced A. Likewise,
3289 // if P is a pointer to a class of the form simple-template-id, the
3290 // transformed A can be a pointer to a derived class pointed to by
3291 // the deduced A.
3292 if (isSimpleTemplateIdType(ParamType) ||
3293 (isa<PointerType>(ParamType) &&
3294 isSimpleTemplateIdType(
3295 ParamType->getAs<PointerType>()->getPointeeType())))
3296 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003297
Douglas Gregor7825bf32011-01-06 22:09:01 +00003298 return false;
3299}
3300
Richard Smith86a1b132017-02-16 03:49:44 +00003301static bool hasDeducibleTemplateParameters(Sema &S,
3302 TemplateParameterList *Params,
3303 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003304
Richard Smith707eab62017-01-05 04:08:31 +00003305static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003306 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3307 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
Richard Smith707eab62017-01-05 04:08:31 +00003308 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3309 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
Richard Smithc92d2062017-01-05 23:02:44 +00003310 bool DecomposedParam, unsigned ArgIdx, unsigned TDF);
Hubert Tong3280b332015-06-25 00:25:49 +00003311
3312/// \brief Attempt template argument deduction from an initializer list
3313/// deemed to be an argument in a function call.
Richard Smith707eab62017-01-05 04:08:31 +00003314static Sema::TemplateDeductionResult DeduceFromInitializerList(
3315 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
3316 InitListExpr *ILE, TemplateDeductionInfo &Info,
3317 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00003318 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
3319 unsigned TDF) {
Richard Smitha7d5ec92017-01-04 19:47:19 +00003320 // C++ [temp.deduct.call]p1: (CWG 1591)
3321 // If removing references and cv-qualifiers from P gives
3322 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
3323 // a non-empty initializer list, then deduction is performed instead for
3324 // each element of the initializer list, taking P0 as a function template
3325 // parameter type and the initializer element as its argument
3326 //
Richard Smith707eab62017-01-05 04:08:31 +00003327 // We've already removed references and cv-qualifiers here.
Richard Smith9c5534c2017-01-05 04:16:30 +00003328 if (!ILE->getNumInits())
3329 return Sema::TDK_Success;
3330
Richard Smitha7d5ec92017-01-04 19:47:19 +00003331 QualType ElTy;
3332 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
3333 if (ArrTy)
3334 ElTy = ArrTy->getElementType();
3335 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
3336 // Otherwise, an initializer list argument causes the parameter to be
3337 // considered a non-deduced context
3338 return Sema::TDK_Success;
Hubert Tong3280b332015-06-25 00:25:49 +00003339 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003340
Faisal Valif6dfdb32015-12-10 05:36:39 +00003341 // Deduction only needs to be done for dependent types.
3342 if (ElTy->isDependentType()) {
3343 for (Expr *E : ILE->inits()) {
Richard Smith707eab62017-01-05 04:08:31 +00003344 if (auto Result = DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003345 S, TemplateParams, 0, ElTy, E, Info, Deduced, OriginalCallArgs, true,
Richard Smithc92d2062017-01-05 23:02:44 +00003346 ArgIdx, TDF))
Richard Smitha7d5ec92017-01-04 19:47:19 +00003347 return Result;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003348 }
3349 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003350
3351 // in the P0[N] case, if N is a non-type template parameter, N is deduced
3352 // from the length of the initializer list.
Richard Smitha7d5ec92017-01-04 19:47:19 +00003353 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003354 // Determine the array bound is something we can deduce.
3355 if (NonTypeTemplateParmDecl *NTTP =
Richard Smitha7d5ec92017-01-04 19:47:19 +00003356 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003357 // We can perform template argument deduction for the given non-type
3358 // template parameter.
Faisal Valif6dfdb32015-12-10 05:36:39 +00003359 llvm::APInt Size(S.Context.getIntWidth(NTTP->getType()),
3360 ILE->getNumInits());
Richard Smitha7d5ec92017-01-04 19:47:19 +00003361 if (auto Result = DeduceNonTypeTemplateArgument(
3362 S, TemplateParams, NTTP, llvm::APSInt(Size), NTTP->getType(),
3363 /*ArrayBound=*/true, Info, Deduced))
3364 return Result;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003365 }
3366 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003367
3368 return Sema::TDK_Success;
Hubert Tong3280b332015-06-25 00:25:49 +00003369}
3370
Richard Smith707eab62017-01-05 04:08:31 +00003371/// \brief Perform template argument deduction per [temp.deduct.call] for a
3372/// single parameter / argument pair.
3373static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003374 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3375 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
Richard Smith707eab62017-01-05 04:08:31 +00003376 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3377 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
Richard Smithc92d2062017-01-05 23:02:44 +00003378 bool DecomposedParam, unsigned ArgIdx, unsigned TDF) {
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003379 QualType ArgType = Arg->getType();
Richard Smith707eab62017-01-05 04:08:31 +00003380 QualType OrigParamType = ParamType;
3381
3382 // If P is a reference type [...]
3383 // If P is a cv-qualified type [...]
Richard Smith32918772017-02-14 00:25:28 +00003384 if (AdjustFunctionParmAndArgTypesForDeduction(
3385 S, TemplateParams, FirstInnerIndex, ParamType, ArgType, Arg, TDF))
Richard Smith363ae812017-01-04 22:03:59 +00003386 return Sema::TDK_Success;
3387
Richard Smith707eab62017-01-05 04:08:31 +00003388 // If [...] the argument is a non-empty initializer list [...]
3389 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg))
3390 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
Richard Smithc92d2062017-01-05 23:02:44 +00003391 Deduced, OriginalCallArgs, ArgIdx, TDF);
Richard Smith707eab62017-01-05 04:08:31 +00003392
3393 // [...] the deduction process attempts to find template argument values
3394 // that will make the deduced A identical to A
3395 //
3396 // Keep track of the argument type and corresponding parameter index,
3397 // so we can check for compatibility between the deduced A and A.
Richard Smithc92d2062017-01-05 23:02:44 +00003398 OriginalCallArgs.push_back(
3399 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
Sebastian Redl19181662012-03-15 21:40:51 +00003400 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003401 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003402}
3403
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003404/// \brief Perform template argument deduction from a function call
3405/// (C++ [temp.deduct.call]).
3406///
3407/// \param FunctionTemplate the function template for which we are performing
3408/// template argument deduction.
3409///
James Dennett18348b62012-06-22 08:52:37 +00003410/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003411/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003412///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003413/// \param Args the function call arguments
3414///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003415/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003416/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003417/// template argument deduction.
3418///
3419/// \param Info the argument will be updated to provide additional information
3420/// about template argument deduction.
3421///
Richard Smith6eedfe72017-01-09 08:01:21 +00003422/// \param CheckNonDependent A callback to invoke to check conversions for
3423/// non-dependent parameters, between deduction and substitution, per DR1391.
3424/// If this returns true, substitution will be skipped and we return
3425/// TDK_NonDependentConversionFailure. The callback is passed the parameter
3426/// types (after substituting explicit template arguments).
3427///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003428/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003429Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3430 FunctionTemplateDecl *FunctionTemplate,
3431 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003432 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
Richard Smith6eedfe72017-01-09 08:01:21 +00003433 bool PartialOverloading,
3434 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003435 if (FunctionTemplate->isInvalidDecl())
3436 return TDK_Invalid;
3437
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003438 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003439 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003440
Richard Smith32918772017-02-14 00:25:28 +00003441 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
3442
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003443 // C++ [temp.deduct.call]p1:
3444 // Template argument deduction is done by comparing each function template
3445 // parameter type (call it P) with the type of the corresponding argument
3446 // of the call (call it A) as described below.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003447 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003448 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003449 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003450 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003451 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003452 if (Proto->isTemplateVariadic())
3453 /* Do nothing */;
Richard Smithde0d34a2017-01-09 07:14:40 +00003454 else if (!Proto->isVariadic())
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003455 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003456 }
Mike Stump11289f42009-09-09 15:08:12 +00003457
Douglas Gregor89026b52009-06-30 23:57:56 +00003458 // The types of the parameters from which we will perform template argument
3459 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003460 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003461 TemplateParameterList *TemplateParams
3462 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003463 SmallVector<DeducedTemplateArgument, 4> Deduced;
Richard Smith6eedfe72017-01-09 08:01:21 +00003464 SmallVector<QualType, 8> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003465 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003466 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003467 TemplateDeductionResult Result =
3468 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003469 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003470 Deduced,
3471 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003472 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003473 Info);
3474 if (Result)
3475 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003476
3477 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003478 } else {
3479 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003480 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003481 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3482 }
Mike Stump11289f42009-09-09 15:08:12 +00003483
Richard Smith6eedfe72017-01-09 08:01:21 +00003484 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
Richard Smitha7d5ec92017-01-04 19:47:19 +00003485
3486 // Deduce an argument of type ParamType from an expression with index ArgIdx.
3487 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx) {
Richard Smith707eab62017-01-05 04:08:31 +00003488 // C++ [demp.deduct.call]p1: (DR1391)
3489 // Template argument deduction is done by comparing each function template
3490 // parameter that contains template-parameters that participate in
3491 // template argument deduction ...
Richard Smith86a1b132017-02-16 03:49:44 +00003492 if (!hasDeducibleTemplateParameters(*this, TemplateParams, ParamType))
Richard Smitha7d5ec92017-01-04 19:47:19 +00003493 return Sema::TDK_Success;
3494
Richard Smith707eab62017-01-05 04:08:31 +00003495 // ... with the type of the corresponding argument
3496 return DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003497 *this, TemplateParams, FirstInnerIndex, ParamType, Args[ArgIdx], Info, Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00003498 OriginalCallArgs, /*Decomposed*/false, ArgIdx, /*TDF*/ 0);
Richard Smitha7d5ec92017-01-04 19:47:19 +00003499 };
3500
Douglas Gregor89026b52009-06-30 23:57:56 +00003501 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003502 Deduced.resize(TemplateParams->size());
Richard Smith6eedfe72017-01-09 08:01:21 +00003503 SmallVector<QualType, 8> ParamTypesForArgChecking;
Richard Smitha7d5ec92017-01-04 19:47:19 +00003504 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003505 ParamIdx != NumParamTypes; ++ParamIdx) {
Richard Smitha7d5ec92017-01-04 19:47:19 +00003506 QualType ParamType = ParamTypes[ParamIdx];
Simon Pilgrim728134c2016-08-12 11:43:57 +00003507
Richard Smitha7d5ec92017-01-04 19:47:19 +00003508 const PackExpansionType *ParamExpansion =
3509 dyn_cast<PackExpansionType>(ParamType);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003510 if (!ParamExpansion) {
3511 // Simple case: matching a function parameter to a function argument.
Richard Smithde0d34a2017-01-09 07:14:40 +00003512 if (ArgIdx >= Args.size())
Douglas Gregor7825bf32011-01-06 22:09:01 +00003513 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003514
Richard Smith6eedfe72017-01-09 08:01:21 +00003515 ParamTypesForArgChecking.push_back(ParamType);
Richard Smitha7d5ec92017-01-04 19:47:19 +00003516 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003517 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003518
Douglas Gregor7825bf32011-01-06 22:09:01 +00003519 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003520 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003521
Richard Smithde0d34a2017-01-09 07:14:40 +00003522 QualType ParamPattern = ParamExpansion->getPattern();
3523 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3524 ParamPattern);
3525
Douglas Gregor7825bf32011-01-06 22:09:01 +00003526 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003527 // For a function parameter pack that occurs at the end of the
3528 // parameter-declaration-list, the type A of each remaining argument of
3529 // the call is compared with the type P of the declarator-id of the
3530 // function parameter pack. Each comparison deduces template arguments
3531 // for subsequent positions in the template parameter packs expanded by
Richard Smithde0d34a2017-01-09 07:14:40 +00003532 // the function parameter pack. When a function parameter pack appears
3533 // in a non-deduced context [not at the end of the list], the type of
3534 // that parameter pack is never deduced.
3535 //
3536 // FIXME: The above rule allows the size of the parameter pack to change
3537 // after we skip it (in the non-deduced case). That makes no sense, so
3538 // we instead notionally deduce the pack against N arguments, where N is
3539 // the length of the explicitly-specified pack if it's expanded by the
3540 // parameter pack and 0 otherwise, and we treat each deduction as a
3541 // non-deduced context.
3542 if (ParamIdx + 1 == NumParamTypes) {
Richard Smith6eedfe72017-01-09 08:01:21 +00003543 for (; ArgIdx < Args.size(); PackScope.nextPackElement(), ++ArgIdx) {
3544 ParamTypesForArgChecking.push_back(ParamPattern);
Richard Smithde0d34a2017-01-09 07:14:40 +00003545 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx))
3546 return Result;
Richard Smith6eedfe72017-01-09 08:01:21 +00003547 }
Richard Smithde0d34a2017-01-09 07:14:40 +00003548 } else {
3549 // If the parameter type contains an explicitly-specified pack that we
3550 // could not expand, skip the number of parameters notionally created
3551 // by the expansion.
3552 Optional<unsigned> NumExpansions = ParamExpansion->getNumExpansions();
Richard Smith6eedfe72017-01-09 08:01:21 +00003553 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
Richard Smithde0d34a2017-01-09 07:14:40 +00003554 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00003555 ++I, ++ArgIdx) {
3556 ParamTypesForArgChecking.push_back(ParamPattern);
Richard Smithde0d34a2017-01-09 07:14:40 +00003557 // FIXME: Should we add OriginalCallArgs for these? What if the
3558 // corresponding argument is a list?
3559 PackScope.nextPackElement();
Richard Smith6eedfe72017-01-09 08:01:21 +00003560 }
3561 }
Richard Smithde0d34a2017-01-09 07:14:40 +00003562 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003563
Douglas Gregor7825bf32011-01-06 22:09:01 +00003564 // Build argument packs for each of the parameter packs expanded by this
3565 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00003566 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003567 return Result;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003568 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003569
Richard Smith6eedfe72017-01-09 08:01:21 +00003570 return FinishTemplateArgumentDeduction(
3571 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
3572 &OriginalCallArgs, PartialOverloading,
3573 [&]() { return CheckNonDependent(ParamTypesForArgChecking); });
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003574}
3575
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003576QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
Richard Smithbaa47832016-12-01 02:11:49 +00003577 QualType FunctionType,
3578 bool AdjustExceptionSpec) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003579 if (ArgFunctionType.isNull())
3580 return ArgFunctionType;
3581
3582 const FunctionProtoType *FunctionTypeP =
3583 FunctionType->castAs<FunctionProtoType>();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003584 const FunctionProtoType *ArgFunctionTypeP =
3585 ArgFunctionType->getAs<FunctionProtoType>();
Richard Smithbaa47832016-12-01 02:11:49 +00003586
3587 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
3588 bool Rebuild = false;
3589
3590 CallingConv CC = FunctionTypeP->getCallConv();
3591 if (EPI.ExtInfo.getCC() != CC) {
3592 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
3593 Rebuild = true;
3594 }
3595
3596 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3597 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
3598 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
3599 Rebuild = true;
3600 }
3601
3602 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
3603 ArgFunctionTypeP->hasExceptionSpec())) {
3604 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
3605 Rebuild = true;
3606 }
3607
3608 if (!Rebuild)
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003609 return ArgFunctionType;
3610
Richard Smithbaa47832016-12-01 02:11:49 +00003611 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
3612 ArgFunctionTypeP->getParamTypes(), EPI);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003613}
3614
Douglas Gregor9b146582009-07-08 20:55:45 +00003615/// \brief Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003616/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3617/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003618///
3619/// \param FunctionTemplate the function template for which we are performing
3620/// template argument deduction.
3621///
James Dennett18348b62012-06-22 08:52:37 +00003622/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003623/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003624///
3625/// \param ArgFunctionType the function type that will be used as the
3626/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003627/// function template's function type. This type may be NULL, if there is no
3628/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00003629///
3630/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003631/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00003632/// template argument deduction.
3633///
3634/// \param Info the argument will be updated to provide additional information
3635/// about template argument deduction.
3636///
Richard Smithbaa47832016-12-01 02:11:49 +00003637/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3638/// the address of a function template per [temp.deduct.funcaddr] and
3639/// [over.over]. If \c false, we are looking up a function template
3640/// specialization based on its signature, per [temp.deduct.decl].
3641///
Douglas Gregor9b146582009-07-08 20:55:45 +00003642/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00003643Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3644 FunctionTemplateDecl *FunctionTemplate,
3645 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
3646 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3647 bool IsAddressOfFunction) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003648 if (FunctionTemplate->isInvalidDecl())
3649 return TDK_Invalid;
3650
Douglas Gregor9b146582009-07-08 20:55:45 +00003651 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3652 TemplateParameterList *TemplateParams
3653 = FunctionTemplate->getTemplateParameters();
3654 QualType FunctionType = Function->getType();
Richard Smithbaa47832016-12-01 02:11:49 +00003655
3656 // When taking the address of a function, we require convertibility of
3657 // the resulting function type. Otherwise, we allow arbitrary mismatches
3658 // of calling convention, noreturn, and noexcept.
3659 if (!IsAddressOfFunction)
3660 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
3661 /*AdjustExceptionSpec*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003662
Douglas Gregor9b146582009-07-08 20:55:45 +00003663 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00003664 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003665 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003666 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003667 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00003668 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003669 if (TemplateDeductionResult Result
3670 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003671 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00003672 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003673 &FunctionType, Info))
3674 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003675
3676 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00003677 }
3678
Eli Friedman77dcc722012-02-08 03:07:05 +00003679 // Unevaluated SFINAE context.
3680 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003681 SFINAETrap Trap(*this);
3682
John McCallc1f69982010-02-02 02:21:27 +00003683 Deduced.resize(TemplateParams->size());
3684
Richard Smith2a7d4812013-05-04 07:00:32 +00003685 // If the function has a deduced return type, substitute it for a dependent
Richard Smithbaa47832016-12-01 02:11:49 +00003686 // type so that we treat it as a non-deduced context in what follows. If we
3687 // are looking up by signature, the signature type should also have a deduced
3688 // return type, which we instead expect to exactly match.
Richard Smithc58f38f2013-08-14 20:16:31 +00003689 bool HasDeducedReturnType = false;
Richard Smithbaa47832016-12-01 02:11:49 +00003690 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
Alp Toker314cc812014-01-25 16:55:45 +00003691 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003692 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00003693 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00003694 }
3695
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003696 if (!ArgFunctionType.isNull()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00003697 unsigned TDF = TDF_TopLevelParameterTypeList;
Richard Smithbaa47832016-12-01 02:11:49 +00003698 if (IsAddressOfFunction)
3699 TDF |= TDF_InOverloadResolution;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003700 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003701 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003702 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00003703 FunctionType, ArgFunctionType,
3704 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003705 return Result;
3706 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003707
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003708 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003709 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3710 NumExplicitlySpecified,
3711 Specialization, Info))
3712 return Result;
3713
Richard Smith2a7d4812013-05-04 07:00:32 +00003714 // If the function has a deduced return type, deduce it now, so we can check
3715 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00003716 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00003717 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003718 DeduceReturnType(Specialization, Info.getLocation(), false))
3719 return TDK_MiscellaneousDeductionFailure;
3720
Richard Smith9095e5b2016-11-01 01:31:23 +00003721 // If the function has a dependent exception specification, resolve it now,
3722 // so we can check that the exception specification matches.
3723 auto *SpecializationFPT =
3724 Specialization->getType()->castAs<FunctionProtoType>();
3725 if (getLangOpts().CPlusPlus1z &&
3726 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
3727 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
3728 return TDK_MiscellaneousDeductionFailure;
3729
Richard Smithbaa47832016-12-01 02:11:49 +00003730 // Adjust the exception specification of the argument again to match the
3731 // substituted and resolved type we just formed. (Calling convention and
3732 // noreturn can't be dependent, so we don't actually need this for them
3733 // right now.)
3734 QualType SpecializationType = Specialization->getType();
3735 if (!IsAddressOfFunction)
3736 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
3737 /*AdjustExceptionSpec*/true);
3738
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003739 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00003740 // specialization with respect to arguments of compatible pointer to function
3741 // types, template argument deduction fails.
3742 if (!ArgFunctionType.isNull()) {
Richard Smithbaa47832016-12-01 02:11:49 +00003743 if (IsAddressOfFunction &&
3744 !isSameOrCompatibleFunctionType(
3745 Context.getCanonicalType(SpecializationType),
3746 Context.getCanonicalType(ArgFunctionType)))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003747 return TDK_MiscellaneousDeductionFailure;
Richard Smithbaa47832016-12-01 02:11:49 +00003748
3749 if (!IsAddressOfFunction &&
3750 !Context.hasSameType(SpecializationType, ArgFunctionType))
Douglas Gregor19a41f12013-04-17 08:45:07 +00003751 return TDK_MiscellaneousDeductionFailure;
3752 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00003753
3754 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003755}
3756
Simon Pilgrim728134c2016-08-12 11:43:57 +00003757/// \brief Given a function declaration (e.g. a generic lambda conversion
3758/// function) that contains an 'auto' in its result type, substitute it
Faisal Vali2b3a3012013-10-24 23:40:02 +00003759/// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3760/// to replace 'auto' with and not the actual result type you want
3761/// to set the function to.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003762static inline void
3763SubstAutoWithinFunctionReturnType(FunctionDecl *F,
Faisal Vali571df122013-09-29 08:45:24 +00003764 QualType TypeToReplaceAutoWith, Sema &S) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003765 assert(!TypeToReplaceAutoWith->getContainedAutoType());
Alp Toker314cc812014-01-25 16:55:45 +00003766 QualType AutoResultType = F->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003767 assert(AutoResultType->getContainedAutoType());
3768 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
Faisal Vali571df122013-09-29 08:45:24 +00003769 TypeToReplaceAutoWith);
3770 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3771}
Faisal Vali2b3a3012013-10-24 23:40:02 +00003772
Simon Pilgrim728134c2016-08-12 11:43:57 +00003773/// \brief Given a specialized conversion operator of a generic lambda
3774/// create the corresponding specializations of the call operator and
3775/// the static-invoker. If the return type of the call operator is auto,
3776/// deduce its return type and check if that matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003777/// return type of the destination function ptr.
3778
Simon Pilgrim728134c2016-08-12 11:43:57 +00003779static inline Sema::TemplateDeductionResult
Faisal Vali2b3a3012013-10-24 23:40:02 +00003780SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3781 CXXConversionDecl *ConversionSpecialized,
3782 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3783 QualType ReturnTypeOfDestFunctionPtr,
3784 TemplateDeductionInfo &TDInfo,
3785 Sema &S) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003786
Faisal Vali2b3a3012013-10-24 23:40:02 +00003787 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003788 assert(LambdaClass && LambdaClass->isGenericLambda());
3789
Faisal Vali2b3a3012013-10-24 23:40:02 +00003790 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
Alp Toker314cc812014-01-25 16:55:45 +00003791 QualType CallOpResultType = CallOpGeneric->getReturnType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003792 const bool GenericLambdaCallOperatorHasDeducedReturnType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003793 CallOpResultType->getContainedAutoType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003794
3795 FunctionTemplateDecl *CallOpTemplate =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003796 CallOpGeneric->getDescribedFunctionTemplate();
3797
Craig Topperc3ec1492014-05-26 06:22:03 +00003798 FunctionDecl *CallOpSpecialized = nullptr;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003799 // Use the deduced arguments of the conversion function, to specialize our
Faisal Vali2b3a3012013-10-24 23:40:02 +00003800 // generic lambda's call operator.
3801 if (Sema::TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003802 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3803 DeducedArguments,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003804 0, CallOpSpecialized, TDInfo))
3805 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003806
Faisal Vali2b3a3012013-10-24 23:40:02 +00003807 // If we need to deduce the return type, do so (instantiates the callop).
Alp Toker314cc812014-01-25 16:55:45 +00003808 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3809 CallOpSpecialized->getReturnType()->isUndeducedType())
Simon Pilgrim728134c2016-08-12 11:43:57 +00003810 S.DeduceReturnType(CallOpSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003811 CallOpSpecialized->getPointOfInstantiation(),
3812 /*Diagnose*/ true);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003813
Faisal Vali2b3a3012013-10-24 23:40:02 +00003814 // Check to see if the return type of the destination ptr-to-function
3815 // matches the return type of the call operator.
Alp Toker314cc812014-01-25 16:55:45 +00003816 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
Faisal Vali2b3a3012013-10-24 23:40:02 +00003817 ReturnTypeOfDestFunctionPtr))
3818 return Sema::TDK_NonDeducedMismatch;
3819 // Since we have succeeded in matching the source and destination
Simon Pilgrim728134c2016-08-12 11:43:57 +00003820 // ptr-to-functions (now including return type), and have successfully
Faisal Vali2b3a3012013-10-24 23:40:02 +00003821 // specialized our corresponding call operator, we are ready to
3822 // specialize the static invoker with the deduced arguments of our
3823 // ptr-to-function.
Craig Topperc3ec1492014-05-26 06:22:03 +00003824 FunctionDecl *InvokerSpecialized = nullptr;
Faisal Vali2b3a3012013-10-24 23:40:02 +00003825 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3826 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3827
Yaron Kerenf428fcf2015-05-13 17:56:46 +00003828#ifndef NDEBUG
3829 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3830#endif
Simon Pilgrim728134c2016-08-12 11:43:57 +00003831 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003832 InvokerSpecialized, TDInfo);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003833 assert(Result == Sema::TDK_Success &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003834 "If the call operator succeeded so should the invoker!");
3835 // Set the result type to match the corresponding call operator
3836 // specialization's result type.
Alp Toker314cc812014-01-25 16:55:45 +00003837 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3838 InvokerSpecialized->getReturnType()->isUndeducedType()) {
Faisal Vali2b3a3012013-10-24 23:40:02 +00003839 // Be sure to get the type to replace 'auto' with and not
Simon Pilgrim728134c2016-08-12 11:43:57 +00003840 // the full result type of the call op specialization
Faisal Vali2b3a3012013-10-24 23:40:02 +00003841 // to substitute into the 'auto' of the invoker and conversion
3842 // function.
3843 // For e.g.
3844 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3845 // We don't want to subst 'int*' into 'auto' to get int**.
3846
Alp Toker314cc812014-01-25 16:55:45 +00003847 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3848 ->getContainedAutoType()
3849 ->getDeducedType();
Faisal Vali2b3a3012013-10-24 23:40:02 +00003850 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3851 TypeToReplaceAutoWith, S);
Simon Pilgrim728134c2016-08-12 11:43:57 +00003852 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003853 TypeToReplaceAutoWith, S);
3854 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003855
Faisal Vali2b3a3012013-10-24 23:40:02 +00003856 // Ensure that static invoker doesn't have a const qualifier.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003857 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
Faisal Vali2b3a3012013-10-24 23:40:02 +00003858 // do not use the CallOperator's TypeSourceInfo which allows
Simon Pilgrim728134c2016-08-12 11:43:57 +00003859 // the const qualifier to leak through.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003860 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3861 getType().getTypePtr()->castAs<FunctionProtoType>();
3862 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3863 EPI.TypeQuals = 0;
3864 InvokerSpecialized->setType(S.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003865 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
Faisal Vali2b3a3012013-10-24 23:40:02 +00003866 return Sema::TDK_Success;
3867}
Douglas Gregor05155d82009-08-21 23:19:43 +00003868/// \brief Deduce template arguments for a templated conversion
3869/// function (C++ [temp.deduct.conv]) and, if successful, produce a
3870/// conversion function template specialization.
3871Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00003872Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00003873 QualType ToType,
3874 CXXConversionDecl *&Specialization,
3875 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00003876 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003877 return TDK_Invalid;
3878
Faisal Vali2b3a3012013-10-24 23:40:02 +00003879 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00003880 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3881
Faisal Vali2b3a3012013-10-24 23:40:02 +00003882 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00003883
3884 // Canonicalize the types for deduction.
3885 QualType P = Context.getCanonicalType(FromType);
3886 QualType A = Context.getCanonicalType(ToType);
3887
Douglas Gregord99609a2011-03-06 09:03:20 +00003888 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00003889 // If P is a reference type, the type referred to by P is used for
3890 // type deduction.
3891 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3892 P = PRef->getPointeeType();
3893
Douglas Gregord99609a2011-03-06 09:03:20 +00003894 // C++0x [temp.deduct.conv]p4:
3895 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00003896 // for type deduction.
3897 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
Douglas Gregord99609a2011-03-06 09:03:20 +00003898 A = ARef->getPointeeType().getUnqualifiedType();
3899 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00003900 //
Mike Stump11289f42009-09-09 15:08:12 +00003901 // If A is not a reference type:
Douglas Gregor05155d82009-08-21 23:19:43 +00003902 else {
3903 assert(!A->isReferenceType() && "Reference types were handled above");
3904
3905 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00003906 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00003907 // of P for type deduction; otherwise,
3908 if (P->isArrayType())
3909 P = Context.getArrayDecayedType(P);
3910 // - If P is a function type, the pointer type produced by the
3911 // function-to-pointer standard conversion (4.3) is used in
3912 // place of P for type deduction; otherwise,
3913 else if (P->isFunctionType())
3914 P = Context.getPointerType(P);
3915 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003916 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003917 else
3918 P = P.getUnqualifiedType();
3919
Douglas Gregord99609a2011-03-06 09:03:20 +00003920 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003921 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00003922 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00003923 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00003924 A = A.getUnqualifiedType();
3925 }
3926
Eli Friedman77dcc722012-02-08 03:07:05 +00003927 // Unevaluated SFINAE context.
3928 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003929 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003930
3931 // C++ [temp.deduct.conv]p1:
3932 // Template argument deduction is done by comparing the return
3933 // type of the template conversion function (call it P) with the
3934 // type that is required as the result of the conversion (call it
3935 // A) as described in 14.8.2.4.
3936 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00003937 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003938 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00003939 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00003940
3941 // C++0x [temp.deduct.conv]p4:
3942 // In general, the deduction process attempts to find template
3943 // argument values that will make the deduced A identical to
3944 // A. However, there are two cases that allow a difference:
3945 unsigned TDF = 0;
3946 // - If the original A is a reference type, A can be more
3947 // cv-qualified than the deduced A (i.e., the type referred to
3948 // by the reference)
3949 if (ToType->isReferenceType())
3950 TDF |= TDF_ParamWithReferenceType;
3951 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003952 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00003953 // conversion.
3954 //
3955 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3956 // both P and A are pointers or member pointers. In this case, we
3957 // just ignore cv-qualifiers completely).
3958 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00003959 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00003960 TDF |= TDF_IgnoreQualifiers;
3961 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003962 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3963 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00003964 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00003965
3966 // Create an Instantiation Scope for finalizing the operator.
3967 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00003968 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00003969 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00003970 TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00003971 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00003972 ConversionSpecialized, Info);
3973 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3974
3975 // If the conversion operator is being invoked on a lambda closure to convert
Nico Weberc153d242014-07-28 00:02:09 +00003976 // to a ptr-to-function, use the deduced arguments from the conversion
3977 // function to specialize the corresponding call operator.
Faisal Vali2b3a3012013-10-24 23:40:02 +00003978 // e.g., int (*fp)(int) = [](auto a) { return a; };
3979 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
Simon Pilgrim728134c2016-08-12 11:43:57 +00003980
Faisal Vali2b3a3012013-10-24 23:40:02 +00003981 // Get the return type of the destination ptr-to-function we are converting
Simon Pilgrim728134c2016-08-12 11:43:57 +00003982 // to. This is necessary for matching the lambda call operator's return
Faisal Vali2b3a3012013-10-24 23:40:02 +00003983 // type to that of the destination ptr-to-function's return type.
Simon Pilgrim728134c2016-08-12 11:43:57 +00003984 assert(A->isPointerType() &&
Faisal Vali2b3a3012013-10-24 23:40:02 +00003985 "Can only convert from lambda to ptr-to-function");
Simon Pilgrim728134c2016-08-12 11:43:57 +00003986 const FunctionType *ToFunType =
Faisal Vali2b3a3012013-10-24 23:40:02 +00003987 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003988 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3989
Simon Pilgrim728134c2016-08-12 11:43:57 +00003990 // Create the corresponding specializations of the call operator and
3991 // the static-invoker; and if the return type is auto,
3992 // deduce the return type and check if it matches the
Faisal Vali2b3a3012013-10-24 23:40:02 +00003993 // DestFunctionPtrReturnType.
3994 // For instance:
3995 // auto L = [](auto a) { return f(a); };
3996 // int (*fp)(int) = L;
3997 // char (*fp2)(int) = L; <-- Not OK.
3998
3999 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
Simon Pilgrim728134c2016-08-12 11:43:57 +00004000 Specialization, Deduced, DestFunctionPtrReturnType,
Faisal Vali2b3a3012013-10-24 23:40:02 +00004001 Info, *this);
4002 }
Douglas Gregor05155d82009-08-21 23:19:43 +00004003 return Result;
4004}
4005
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004006/// \brief Deduce template arguments for a function template when there is
4007/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
4008///
4009/// \param FunctionTemplate the function template for which we are performing
4010/// template argument deduction.
4011///
James Dennett18348b62012-06-22 08:52:37 +00004012/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004013/// arguments.
4014///
4015/// \param Specialization if template argument deduction was successful,
4016/// this will be set to the function template specialization produced by
4017/// template argument deduction.
4018///
4019/// \param Info the argument will be updated to provide additional information
4020/// about template argument deduction.
4021///
Richard Smithbaa47832016-12-01 02:11:49 +00004022/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4023/// the address of a function template in a context where we do not have a
4024/// target type, per [over.over]. If \c false, we are looking up a function
4025/// template specialization based on its signature, which only happens when
4026/// deducing a function parameter type from an argument that is a template-id
4027/// naming a function template specialization.
4028///
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004029/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00004030Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
4031 FunctionTemplateDecl *FunctionTemplate,
4032 TemplateArgumentListInfo *ExplicitTemplateArgs,
4033 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4034 bool IsAddressOfFunction) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004035 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00004036 QualType(), Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +00004037 IsAddressOfFunction);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004038}
4039
Richard Smith30482bc2011-02-20 03:19:35 +00004040namespace {
Richard Smith60437622017-02-09 19:17:44 +00004041 /// Substitute the 'auto' specifier or deduced template specialization type
4042 /// specifier within a type for a given replacement type.
4043 class SubstituteDeducedTypeTransform :
4044 public TreeTransform<SubstituteDeducedTypeTransform> {
Richard Smith30482bc2011-02-20 03:19:35 +00004045 QualType Replacement;
Richard Smith60437622017-02-09 19:17:44 +00004046 bool UseTypeSugar;
Richard Smith30482bc2011-02-20 03:19:35 +00004047 public:
Richard Smith60437622017-02-09 19:17:44 +00004048 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
4049 bool UseTypeSugar = true)
4050 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
4051 Replacement(Replacement), UseTypeSugar(UseTypeSugar) {}
4052
4053 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
4054 assert(isa<TemplateTypeParmType>(Replacement) &&
4055 "unexpected unsugared replacement kind");
4056 QualType Result = Replacement;
4057 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
4058 NewTL.setNameLoc(TL.getNameLoc());
4059 return Result;
4060 }
Nico Weberc153d242014-07-28 00:02:09 +00004061
Richard Smith30482bc2011-02-20 03:19:35 +00004062 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
4063 // If we're building the type pattern to deduce against, don't wrap the
4064 // substituted type in an AutoType. Certain template deduction rules
4065 // apply only when a template type parameter appears directly (and not if
4066 // the parameter is found through desugaring). For instance:
4067 // auto &&lref = lvalue;
4068 // must transform into "rvalue reference to T" not "rvalue reference to
4069 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith60437622017-02-09 19:17:44 +00004070 //
4071 // FIXME: Is this still necessary?
4072 if (!UseTypeSugar)
4073 return TransformDesugared(TLB, TL);
4074
4075 QualType Result = SemaRef.Context.getAutoType(
4076 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull());
4077 auto NewTL = TLB.push<AutoTypeLoc>(Result);
4078 NewTL.setNameLoc(TL.getNameLoc());
4079 return Result;
4080 }
4081
4082 QualType TransformDeducedTemplateSpecializationType(
4083 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
4084 if (!UseTypeSugar)
4085 return TransformDesugared(TLB, TL);
4086
4087 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
4088 TL.getTypePtr()->getTemplateName(),
4089 Replacement, Replacement.isNull());
4090 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
4091 NewTL.setNameLoc(TL.getNameLoc());
4092 return Result;
Richard Smith30482bc2011-02-20 03:19:35 +00004093 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00004094
4095 ExprResult TransformLambdaExpr(LambdaExpr *E) {
4096 // Lambdas never need to be transformed.
4097 return E;
4098 }
Richard Smith061f1e22013-04-30 21:23:01 +00004099
Richard Smith2a7d4812013-05-04 07:00:32 +00004100 QualType Apply(TypeLoc TL) {
4101 // Create some scratch storage for the transformed type locations.
4102 // FIXME: We're just going to throw this information away. Don't build it.
4103 TypeLocBuilder TLB;
4104 TLB.reserve(TL.getFullDataSize());
4105 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00004106 }
Richard Smith30482bc2011-02-20 03:19:35 +00004107 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004108}
Richard Smith30482bc2011-02-20 03:19:35 +00004109
Richard Smith2a7d4812013-05-04 07:00:32 +00004110Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004111Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result,
4112 Optional<unsigned> DependentDeductionDepth) {
4113 return DeduceAutoType(Type->getTypeLoc(), Init, Result,
4114 DependentDeductionDepth);
Richard Smith2a7d4812013-05-04 07:00:32 +00004115}
4116
Richard Smith061f1e22013-04-30 21:23:01 +00004117/// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00004118///
Richard Smith87d263e2016-12-25 08:05:23 +00004119/// Note that this is done even if the initializer is dependent. (This is
4120/// necessary to support partial ordering of templates using 'auto'.)
4121/// A dependent type will be produced when deducing from a dependent type.
4122///
Richard Smith30482bc2011-02-20 03:19:35 +00004123/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00004124/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00004125/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00004126/// deduced type.
Richard Smith87d263e2016-12-25 08:05:23 +00004127/// \param DependentDeductionDepth Set if we should permit deduction in
4128/// dependent cases. This is necessary for template partial ordering with
4129/// 'auto' template parameters. The value specified is the template
4130/// parameter depth at which we should perform 'auto' deduction.
Sebastian Redl09edce02012-01-23 22:09:39 +00004131Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004132Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result,
4133 Optional<unsigned> DependentDeductionDepth) {
John McCalld5c98ae2011-11-15 01:35:18 +00004134 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004135 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4136 if (NonPlaceholder.isInvalid())
4137 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004138 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00004139 }
4140
Richard Smith87d263e2016-12-25 08:05:23 +00004141 if (!DependentDeductionDepth &&
4142 (Type.getType()->isDependentType() || Init->isTypeDependent())) {
Richard Smith60437622017-02-09 19:17:44 +00004143 Result = SubstituteDeducedTypeTransform(*this, QualType()).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004144 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00004145 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004146 }
4147
Richard Smith87d263e2016-12-25 08:05:23 +00004148 // Find the depth of template parameter to synthesize.
4149 unsigned Depth = DependentDeductionDepth.getValueOr(0);
4150
Richard Smith74aeef52013-04-26 16:15:35 +00004151 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4152 // Since 'decltype(auto)' can only occur at the top of the type, we
4153 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004154 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004155 if (AT->isDecltypeAuto()) {
4156 if (isa<InitListExpr>(Init)) {
4157 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4158 return DAR_FailedAlreadyDiagnosed;
4159 }
4160
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00004161 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004162 if (Deduced.isNull())
4163 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004164 // FIXME: Support a non-canonical deduced type for 'auto'.
4165 Deduced = Context.getCanonicalType(Deduced);
Richard Smith60437622017-02-09 19:17:44 +00004166 Result = SubstituteDeducedTypeTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004167 if (Result.isNull())
4168 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004169 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004170 } else if (!getLangOpts().CPlusPlus) {
4171 if (isa<InitListExpr>(Init)) {
4172 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4173 return DAR_FailedAlreadyDiagnosed;
4174 }
Richard Smith74aeef52013-04-26 16:15:35 +00004175 }
4176 }
4177
Richard Smith30482bc2011-02-20 03:19:35 +00004178 SourceLocation Loc = Init->getExprLoc();
4179
4180 LocalInstantiationScope InstScope(*this);
4181
4182 // Build template<class TemplParam> void Func(FuncParam);
Richard Smith87d263e2016-12-25 08:05:23 +00004183 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
4184 Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004185 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4186 NamedDecl *TemplParamPtr = TemplParam;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00004187 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4188 Loc, Loc, TemplParamPtr, Loc, nullptr);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004189
Richard Smith87d263e2016-12-25 08:05:23 +00004190 QualType FuncParam =
Richard Smith60437622017-02-09 19:17:44 +00004191 SubstituteDeducedTypeTransform(*this, TemplArg, /*UseTypeSugar*/false)
Richard Smith87d263e2016-12-25 08:05:23 +00004192 .Apply(Type);
Richard Smith061f1e22013-04-30 21:23:01 +00004193 assert(!FuncParam.isNull() &&
4194 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004195
4196 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004197 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004198 Deduced.resize(1);
Richard Smith30482bc2011-02-20 03:19:35 +00004199
Richard Smith87d263e2016-12-25 08:05:23 +00004200 TemplateDeductionInfo Info(Loc, Depth);
4201
4202 // If deduction failed, don't diagnose if the initializer is dependent; it
4203 // might acquire a matching type in the instantiation.
4204 auto DeductionFailed = [&]() -> DeduceAutoResult {
4205 if (Init->isTypeDependent()) {
Richard Smith60437622017-02-09 19:17:44 +00004206 Result = SubstituteDeducedTypeTransform(*this, QualType()).Apply(Type);
Richard Smith87d263e2016-12-25 08:05:23 +00004207 assert(!Result.isNull() && "substituting DependentTy can't fail");
4208 return DAR_Succeeded;
4209 }
4210 return DAR_Failed;
4211 };
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004212
Richard Smith707eab62017-01-05 04:08:31 +00004213 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
4214
Richard Smith74801c82012-07-08 04:13:07 +00004215 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004216 if (InitList) {
Richard Smithc8a32e52017-01-05 23:12:16 +00004217 // Notionally, we substitute std::initializer_list<T> for 'auto' and deduce
4218 // against that. Such deduction only succeeds if removing cv-qualifiers and
4219 // references results in std::initializer_list<T>.
4220 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
4221 return DAR_Failed;
4222
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004223 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
Richard Smith707eab62017-01-05 04:08:31 +00004224 if (DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00004225 *this, TemplateParamsSt.get(), 0, TemplArg, InitList->getInit(i),
Richard Smithc92d2062017-01-05 23:02:44 +00004226 Info, Deduced, OriginalCallArgs, /*Decomposed*/ true,
4227 /*ArgIdx*/ 0, /*TDF*/ 0))
Richard Smith87d263e2016-12-25 08:05:23 +00004228 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004229 }
4230 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004231 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4232 Diag(Loc, diag::err_auto_bitfield);
4233 return DAR_FailedAlreadyDiagnosed;
4234 }
4235
Richard Smith707eab62017-01-05 04:08:31 +00004236 if (DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00004237 *this, TemplateParamsSt.get(), 0, FuncParam, Init, Info, Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00004238 OriginalCallArgs, /*Decomposed*/ false, /*ArgIdx*/ 0, /*TDF*/ 0))
Richard Smith87d263e2016-12-25 08:05:23 +00004239 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004240 }
Richard Smith30482bc2011-02-20 03:19:35 +00004241
Richard Smith87d263e2016-12-25 08:05:23 +00004242 // Could be null if somehow 'auto' appears in a non-deduced context.
Eli Friedmane4310952012-11-06 23:56:42 +00004243 if (Deduced[0].getKind() != TemplateArgument::Type)
Richard Smith87d263e2016-12-25 08:05:23 +00004244 return DeductionFailed();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004245
Eli Friedmane4310952012-11-06 23:56:42 +00004246 QualType DeducedType = Deduced[0].getAsType();
4247
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004248 if (InitList) {
4249 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4250 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004251 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004252 }
4253
Richard Smith60437622017-02-09 19:17:44 +00004254 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004255 if (Result.isNull())
Richard Smith87d263e2016-12-25 08:05:23 +00004256 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004257
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004258 // Check that the deduced argument type is compatible with the original
4259 // argument type per C++ [temp.deduct.call]p4.
Richard Smithc92d2062017-01-05 23:02:44 +00004260 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
Richard Smith707eab62017-01-05 04:08:31 +00004261 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
Richard Smithc92d2062017-01-05 23:02:44 +00004262 assert((bool)InitList == OriginalArg.DecomposedParam &&
4263 "decomposed non-init-list in auto deduction?");
4264 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
Richard Smith707eab62017-01-05 04:08:31 +00004265 Result = QualType();
4266 return DeductionFailed();
4267 }
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004268 }
4269
Sebastian Redl09edce02012-01-23 22:09:39 +00004270 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004271}
4272
Simon Pilgrim728134c2016-08-12 11:43:57 +00004273QualType Sema::SubstAutoType(QualType TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004274 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004275 if (TypeToReplaceAuto->isDependentType())
4276 TypeToReplaceAuto = QualType();
Richard Smith60437622017-02-09 19:17:44 +00004277 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
Richard Smith87d263e2016-12-25 08:05:23 +00004278 .TransformType(TypeWithAuto);
Faisal Vali2b391ab2013-09-26 19:54:12 +00004279}
4280
Richard Smith60437622017-02-09 19:17:44 +00004281TypeSourceInfo *Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4282 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004283 if (TypeToReplaceAuto->isDependentType())
4284 TypeToReplaceAuto = QualType();
Richard Smith60437622017-02-09 19:17:44 +00004285 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
Richard Smith87d263e2016-12-25 08:05:23 +00004286 .TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004287}
4288
Richard Smith33c33c32017-02-04 01:28:01 +00004289QualType Sema::ReplaceAutoType(QualType TypeWithAuto,
4290 QualType TypeToReplaceAuto) {
Richard Smith60437622017-02-09 19:17:44 +00004291 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
4292 /*UseTypeSugar*/ false)
Richard Smith33c33c32017-02-04 01:28:01 +00004293 .TransformType(TypeWithAuto);
4294}
4295
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004296void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4297 if (isa<InitListExpr>(Init))
4298 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004299 VDecl->isInitCapture()
4300 ? diag::err_init_capture_deduction_failure_from_init_list
4301 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004302 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4303 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004304 Diag(VDecl->getLocation(),
4305 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4306 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004307 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4308 << Init->getSourceRange();
4309}
4310
Richard Smith2a7d4812013-05-04 07:00:32 +00004311bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4312 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004313 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004314
4315 if (FD->getTemplateInstantiationPattern())
4316 InstantiateFunctionDefinition(Loc, FD);
4317
Alp Toker314cc812014-01-25 16:55:45 +00004318 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004319 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4320 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4321 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4322 }
4323
4324 return StillUndeduced;
4325}
4326
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004327/// \brief If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004328static void
4329AddImplicitObjectParameterType(ASTContext &Context,
4330 CXXMethodDecl *Method,
4331 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004332 // C++11 [temp.func.order]p3:
4333 // [...] The new parameter is of type "reference to cv A," where cv are
4334 // the cv-qualifiers of the function template (if any) and A is
4335 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004336 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004337 // The standard doesn't say explicitly, but we pick the appropriate kind of
4338 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004339 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4340 ArgTy = Context.getQualifiedType(ArgTy,
4341 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004342 if (Method->getRefQualifier() == RQ_RValue)
4343 ArgTy = Context.getRValueReferenceType(ArgTy);
4344 else
4345 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004346 ArgTypes.push_back(ArgTy);
4347}
4348
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004349/// \brief Determine whether the function template \p FT1 is at least as
4350/// specialized as \p FT2.
4351static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004352 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004353 FunctionTemplateDecl *FT1,
4354 FunctionTemplateDecl *FT2,
4355 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004356 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004357 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004358 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004359 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4360 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004361
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004362 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4363 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004364 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004365 Deduced.resize(TemplateParams->size());
4366
4367 // C++0x [temp.deduct.partial]p3:
4368 // The types used to determine the ordering depend on the context in which
4369 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004370 TemplateDeductionInfo Info(Loc);
Richard Smith86a1b132017-02-16 03:49:44 +00004371 SmallVector<QualType, 4> Args1;
Richard Smithe5b52202013-09-11 00:52:39 +00004372 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004373 switch (TPOC) {
4374 case TPOC_Call: {
4375 // - In the context of a function call, the function parameter types are
4376 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004377 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4378 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004379
Eli Friedman3b5774a2012-09-19 23:27:04 +00004380 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004381 // [...] If only one of the function templates is a non-static
4382 // member, that function template is considered to have a new
4383 // first parameter inserted in its function parameter list. The
4384 // new parameter is of type "reference to cv A," where cv are
4385 // the cv-qualifiers of the function template (if any) and A is
4386 // the class of which the function template is a member.
4387 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004388 // Note that we interpret this to mean "if one of the function
4389 // templates is a non-static member and the other is a non-member";
4390 // otherwise, the ordering rules for static functions against non-static
4391 // functions don't make any sense.
4392 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004393 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4394 // it as wording was broken prior to it.
Richard Smithe5b52202013-09-11 00:52:39 +00004395 unsigned NumComparedArguments = NumCallArguments1;
4396
4397 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004398 // Compare 'this' from Method1 against first parameter from Method2.
4399 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4400 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004401 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004402 // Compare 'this' from Method2 against first parameter from Method1.
4403 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004404 }
4405
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004406 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004407 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004408 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004409 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004410
Douglas Gregorb837ea42011-01-11 17:34:58 +00004411 // C++ [temp.func.order]p5:
4412 // The presence of unused ellipsis and default arguments has no effect on
4413 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004414 if (Args1.size() > NumComparedArguments)
4415 Args1.resize(NumComparedArguments);
4416 if (Args2.size() > NumComparedArguments)
4417 Args2.resize(NumComparedArguments);
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004418 break;
4419 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004420
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004421 case TPOC_Conversion:
4422 // - In the context of a call to a conversion operator, the return types
4423 // of the conversion function templates are used.
Richard Smith86a1b132017-02-16 03:49:44 +00004424 Args1.push_back(Proto1->getReturnType());
4425 Args2.push_back(Proto2->getReturnType());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004426 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004427
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004428 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004429 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004430 // is used.
Richard Smith86a1b132017-02-16 03:49:44 +00004431 Args1.push_back(FD1->getType());
4432 Args2.push_back(FD2->getType());
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004433 break;
4434 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004435
Richard Smith86a1b132017-02-16 03:49:44 +00004436 // FIXME: C++1z [temp.deduct.partial]p4:
4437 // If a particular P contains no template-parameters that participate in
4438 // template argument deduction, that P is not used to determine the
4439 // ordering.
4440 // We do not implement this because it has highly undesirable consequences;
4441 // for instance, it means a non-dependent template is never more specialized
4442 // than any other.
4443
4444 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4445 Args1.data(), Args1.size(), Info, Deduced,
4446 TDF_None, /*PartialOrdering=*/true))
4447 return false;
4448
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004449 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004450 // In most cases, all template parameters must have values in order for
4451 // deduction to succeed, but for partial ordering purposes a template
4452 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004453 // types being used for partial ordering. [ Note: a template parameter used
4454 // in a non-deduced context is considered used. -end note]
4455 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4456 for (; ArgIdx != NumArgs; ++ArgIdx)
4457 if (Deduced[ArgIdx].isNull())
4458 break;
4459
Richard Smith86a1b132017-02-16 03:49:44 +00004460 if (ArgIdx != NumArgs) {
4461 // At least one template argument was not deduced. Check whether we deduced
4462 // everything that was used in the types used for ordering.
Richard Smithcf824862016-12-30 04:32:02 +00004463
Richard Smith86a1b132017-02-16 03:49:44 +00004464 // Figure out which template parameters were used.
4465 llvm::SmallBitVector UsedParameters(TemplateParams->size());
4466 for (QualType T : Args2)
4467 ::MarkUsedTemplateParameters(S.Context, T, false,
4468 TemplateParams->getDepth(), UsedParameters);
4469
4470 for (; ArgIdx != NumArgs; ++ArgIdx)
4471 // If this argument had no value deduced but was used in one of the types
4472 // used for partial ordering, then deduction fails.
4473 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4474 return false;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004475 }
4476
Richard Smith86a1b132017-02-16 03:49:44 +00004477 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
4478 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004479
Richard Smith86a1b132017-02-16 03:49:44 +00004480 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
4481 Sema::InstantiatingTemplate Inst(
4482 S, Info.getLocation(), FT2, DeducedArgs,
4483 Sema::ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
4484 Info);
4485 if (Inst.isInvalid())
4486 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004487
Richard Smith86a1b132017-02-16 03:49:44 +00004488 SmallVector<TemplateArgument, 4> Builder;
4489 if (ConvertDeducedTemplateArguments(S, FT2, true, Deduced, Info, Builder,
4490 nullptr, 0, /*SkipNonDeduced*/true))
4491 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004492
Richard Smith86a1b132017-02-16 03:49:44 +00004493 // C++1z [temp.deduct.type]p1:
4494 // an attempt is made to find template argument values (a type for a type
4495 // parameter, a value for a non-type parameter, or a template for a
4496 // template parameter) that will make P, after substitution of the deduced
4497 // values (call it the deduced A), compatible with A.
4498 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Builder);
4499 MultiLevelTemplateArgumentList Args(TemplateArgs);
4500 auto *TrailingPack =
4501 Args2.empty() ? nullptr : dyn_cast<PackExpansionType>(Args2.back());
4502 unsigned PackIndex = Args2.size() - 1;
4503 for (unsigned I = 0, N = Args1.size(); I != N; ++I) {
4504 // Per C++ [temp.deduct.partial]p8, we're supposed to have formed separate
4505 // P/A pairs for each parameter of template 1 for a trailing pack in
4506 // template 2. Reconstruct those now if necessary.
4507 QualType DeducedA;
4508 if (TrailingPack && I >= PackIndex) {
4509 Sema::ArgumentPackSubstitutionIndexRAII Index(S, I - PackIndex);
4510 DeducedA = S.SubstType(TrailingPack->getPattern(), Args,
4511 Info.getLocation(), FT2->getDeclName());
4512 } else {
4513 DeducedA = S.SubstType(Args2[I], Args, Info.getLocation(),
4514 FT2->getDeclName());
4515 }
4516 if (DeducedA.isNull())
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004517 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004518
Richard Smith86a1b132017-02-16 03:49:44 +00004519 QualType A = Args1[I];
4520 if (auto *AsPack = dyn_cast<PackExpansionType>(A))
4521 A = AsPack->getPattern();
4522
4523 // Per [temp.deduct.partial]p5-7, we strip off top-level references and
4524 // cv-qualifications before this check.
4525 if (!S.Context.hasSameUnqualifiedType(DeducedA.getNonReferenceType(),
4526 A.getNonReferenceType()))
4527 return false;
4528 }
4529
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004530 return true;
4531}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004532
Douglas Gregorcef1a032011-01-16 16:03:23 +00004533/// \brief Determine whether this a function template whose parameter-type-list
4534/// ends with a function parameter pack.
4535static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4536 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4537 unsigned NumParams = Function->getNumParams();
4538 if (NumParams == 0)
4539 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004540
Douglas Gregorcef1a032011-01-16 16:03:23 +00004541 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4542 if (!Last->isParameterPack())
4543 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004544
Douglas Gregorcef1a032011-01-16 16:03:23 +00004545 // Make sure that no previous parameter is a parameter pack.
4546 while (--NumParams > 0) {
4547 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4548 return false;
4549 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004550
Douglas Gregorcef1a032011-01-16 16:03:23 +00004551 return true;
4552}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004553
Douglas Gregorbe999392009-09-15 16:23:51 +00004554/// \brief Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004555/// to the rules of function template partial ordering (C++ [temp.func.order]).
4556///
4557/// \param FT1 the first function template
4558///
4559/// \param FT2 the second function template
4560///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004561/// \param TPOC the context in which we are performing partial ordering of
4562/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004563///
Richard Smithe5b52202013-09-11 00:52:39 +00004564/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4565/// only when \c TPOC is \c TPOC_Call.
4566///
4567/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4568/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004569///
Douglas Gregorbe999392009-09-15 16:23:51 +00004570/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004571/// template is more specialized, returns NULL.
4572FunctionTemplateDecl *
4573Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4574 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004575 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004576 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004577 unsigned NumCallArguments1,
4578 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004579 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004580 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004581 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004582 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004583
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004584 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004585 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004586
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004587 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004588 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004589
Douglas Gregorcef1a032011-01-16 16:03:23 +00004590 // FIXME: This mimics what GCC implements, but doesn't match up with the
4591 // proposed resolution for core issue 692. This area needs to be sorted out,
4592 // but for now we attempt to maintain compatibility.
4593 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4594 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4595 if (Variadic1 != Variadic2)
4596 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004597
Craig Topperc3ec1492014-05-26 06:22:03 +00004598 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004599}
Douglas Gregor9b146582009-07-08 20:55:45 +00004600
Douglas Gregor450f00842009-09-25 18:43:00 +00004601/// \brief Determine if the two templates are equivalent.
4602static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4603 if (T1 == T2)
4604 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004605
Douglas Gregor450f00842009-09-25 18:43:00 +00004606 if (!T1 || !T2)
4607 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004608
Douglas Gregor450f00842009-09-25 18:43:00 +00004609 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4610}
4611
4612/// \brief Retrieve the most specialized of the given function template
4613/// specializations.
4614///
John McCall58cc69d2010-01-27 01:50:18 +00004615/// \param SpecBegin the start iterator of the function template
4616/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004617///
John McCall58cc69d2010-01-27 01:50:18 +00004618/// \param SpecEnd the end iterator of the function template
4619/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004620///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004621/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004622/// diagnostic should occur.
4623///
4624/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4625/// no matching candidates.
4626///
4627/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4628/// occurs.
4629///
4630/// \param CandidateDiag partial diagnostic used for each function template
4631/// specialization that is a candidate in the ambiguous ordering. One parameter
4632/// in this diagnostic should be unbound, which will correspond to the string
4633/// describing the template arguments for the function template specialization.
4634///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004635/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004636/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004637UnresolvedSetIterator Sema::getMostSpecialized(
4638 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4639 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004640 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4641 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4642 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004643 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004644 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004645 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004646 FailedCandidates.NoteCandidates(*this, Loc);
4647 }
John McCall58cc69d2010-01-27 01:50:18 +00004648 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004649 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004650
4651 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004652 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004653
Douglas Gregor450f00842009-09-25 18:43:00 +00004654 // Find the function template that is better than all of the templates it
4655 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004656 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004657 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004658 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004659 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004660 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4661 FunctionTemplateDecl *Challenger
4662 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004663 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004664 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004665 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004666 Challenger)) {
4667 Best = I;
4668 BestTemplate = Challenger;
4669 }
4670 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004671
Douglas Gregor450f00842009-09-25 18:43:00 +00004672 // Make sure that the "best" function template is more specialized than all
4673 // of the others.
4674 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004675 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4676 FunctionTemplateDecl *Challenger
4677 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004678 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004679 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004680 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004681 BestTemplate)) {
4682 Ambiguous = true;
4683 break;
4684 }
4685 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004686
Douglas Gregor450f00842009-09-25 18:43:00 +00004687 if (!Ambiguous) {
4688 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004689 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004690 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004691
Douglas Gregor450f00842009-09-25 18:43:00 +00004692 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004693 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004694 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004695
Richard Smithb875c432013-05-04 01:51:08 +00004696 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004697 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4698 PartialDiagnostic PD = CandidateDiag;
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004699 const auto *FD = cast<FunctionDecl>(*I);
4700 PD << FD << getTemplateArgumentBindingsText(
4701 FD->getPrimaryTemplate()->getTemplateParameters(),
4702 *FD->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004703 if (!TargetType.isNull())
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004704 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
Richard Trieucaff2472011-11-23 22:32:32 +00004705 Diag((*I)->getLocation(), PD);
4706 }
Richard Smithb875c432013-05-04 01:51:08 +00004707 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004708
John McCall58cc69d2010-01-27 01:50:18 +00004709 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004710}
4711
Richard Smith0da6dc42016-12-24 16:40:51 +00004712/// Determine whether one partial specialization, P1, is at least as
4713/// specialized than another, P2.
Douglas Gregorbe999392009-09-15 16:23:51 +00004714///
Richard Smith26b86ea2016-12-31 21:41:23 +00004715/// \tparam TemplateLikeDecl The kind of P2, which must be a
4716/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
Richard Smith0da6dc42016-12-24 16:40:51 +00004717/// \param T1 The injected-class-name of P1 (faked for a variable template).
4718/// \param T2 The injected-class-name of P2 (faked for a variable template).
Richard Smith26b86ea2016-12-31 21:41:23 +00004719template<typename TemplateLikeDecl>
Richard Smith0da6dc42016-12-24 16:40:51 +00004720static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
Richard Smith26b86ea2016-12-31 21:41:23 +00004721 TemplateLikeDecl *P2,
Richard Smith0e617ec2016-12-27 07:56:27 +00004722 TemplateDeductionInfo &Info) {
Douglas Gregorbe999392009-09-15 16:23:51 +00004723 // C++ [temp.class.order]p1:
4724 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004725 // specialized as the second if, given the following rewrite to two
4726 // function templates, the first function template is at least as
4727 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00004728 // templates (14.6.6.2):
4729 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004730 // first partial specialization and has a single function parameter
4731 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004732 // arguments of the first partial specialization, and
4733 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004734 // second partial specialization and has a single function parameter
4735 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00004736 // arguments of the second partial specialization.
4737 //
Douglas Gregor684268d2010-04-29 06:21:43 +00004738 // Rather than synthesize function templates, we merely perform the
4739 // equivalent partial ordering by performing deduction directly on
4740 // the template arguments of the class template partial
4741 // specializations. This computation is slightly simpler than the
4742 // general problem of function template partial ordering, because
4743 // class template partial specializations are more constrained. We
4744 // know that every template parameter is deducible from the class
4745 // template partial specialization's template arguments, for
4746 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004747 SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2408e322010-04-27 00:57:59 +00004748
Richard Smith0da6dc42016-12-24 16:40:51 +00004749 // Determine whether P1 is at least as specialized as P2.
4750 Deduced.resize(P2->getTemplateParameters()->size());
4751 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
4752 T2, T1, Info, Deduced, TDF_None,
4753 /*PartialOrdering=*/true))
4754 return false;
4755
4756 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4757 Deduced.end());
Richard Smith0e617ec2016-12-27 07:56:27 +00004758 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
4759 Info);
Richard Smith0da6dc42016-12-24 16:40:51 +00004760 auto *TST1 = T1->castAs<TemplateSpecializationType>();
4761 if (FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00004762 S, P2, /*PartialOrdering=*/true,
4763 TemplateArgumentList(TemplateArgumentList::OnStack,
4764 TST1->template_arguments()),
Richard Smith0da6dc42016-12-24 16:40:51 +00004765 Deduced, Info))
4766 return false;
4767
4768 return true;
4769}
4770
4771/// \brief Returns the more specialized class template partial specialization
4772/// according to the rules of partial ordering of class template partial
4773/// specializations (C++ [temp.class.order]).
4774///
4775/// \param PS1 the first class template partial specialization
4776///
4777/// \param PS2 the second class template partial specialization
4778///
4779/// \returns the more specialized class template partial specialization. If
4780/// neither partial specialization is more specialized, returns NULL.
4781ClassTemplatePartialSpecializationDecl *
4782Sema::getMoreSpecializedPartialSpecialization(
4783 ClassTemplatePartialSpecializationDecl *PS1,
4784 ClassTemplatePartialSpecializationDecl *PS2,
4785 SourceLocation Loc) {
John McCall2408e322010-04-27 00:57:59 +00004786 QualType PT1 = PS1->getInjectedSpecializationType();
4787 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004788
Richard Smith0e617ec2016-12-27 07:56:27 +00004789 TemplateDeductionInfo Info(Loc);
4790 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4791 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004792
4793 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004794 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004795
4796 return Better1 ? PS1 : PS2;
4797}
4798
Richard Smith0e617ec2016-12-27 07:56:27 +00004799bool Sema::isMoreSpecializedThanPrimary(
4800 ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4801 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
4802 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
4803 QualType PartialT = Spec->getInjectedSpecializationType();
4804 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
4805 return false;
4806 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
4807 Info.clearSFINAEDiagnostic();
4808 return false;
4809 }
4810 return true;
4811}
4812
Larisse Voufo39a1e502013-08-06 01:03:05 +00004813VarTemplatePartialSpecializationDecl *
4814Sema::getMoreSpecializedPartialSpecialization(
4815 VarTemplatePartialSpecializationDecl *PS1,
4816 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
Richard Smith0da6dc42016-12-24 16:40:51 +00004817 // Pretend the variable template specializations are class template
4818 // specializations and form a fake injected class name type for comparison.
Richard Smithf04fd0b2013-12-12 23:14:16 +00004819 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00004820 "the partial specializations being compared should specialize"
4821 " the same template.");
4822 TemplateName Name(PS1->getSpecializedTemplate());
4823 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4824 QualType PT1 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004825 CanonTemplate, PS1->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004826 QualType PT2 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00004827 CanonTemplate, PS2->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00004828
Richard Smith0e617ec2016-12-27 07:56:27 +00004829 TemplateDeductionInfo Info(Loc);
4830 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4831 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004832
Douglas Gregorbe999392009-09-15 16:23:51 +00004833 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00004834 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004835
Richard Smith0da6dc42016-12-24 16:40:51 +00004836 return Better1 ? PS1 : PS2;
Douglas Gregorbe999392009-09-15 16:23:51 +00004837}
4838
Richard Smith0e617ec2016-12-27 07:56:27 +00004839bool Sema::isMoreSpecializedThanPrimary(
4840 VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4841 TemplateDecl *Primary = Spec->getSpecializedTemplate();
4842 // FIXME: Cache the injected template arguments rather than recomputing
4843 // them for each partial specialization.
4844 SmallVector<TemplateArgument, 8> PrimaryArgs;
4845 Context.getInjectedTemplateArgs(Primary->getTemplateParameters(),
4846 PrimaryArgs);
4847
4848 TemplateName CanonTemplate =
4849 Context.getCanonicalTemplateName(TemplateName(Primary));
4850 QualType PrimaryT = Context.getTemplateSpecializationType(
4851 CanonTemplate, PrimaryArgs);
4852 QualType PartialT = Context.getTemplateSpecializationType(
4853 CanonTemplate, Spec->getTemplateArgs().asArray());
4854 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
4855 return false;
4856 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
4857 Info.clearSFINAEDiagnostic();
4858 return false;
4859 }
4860 return true;
4861}
4862
Richard Smith26b86ea2016-12-31 21:41:23 +00004863bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
4864 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) {
4865 // C++1z [temp.arg.template]p4: (DR 150)
4866 // A template template-parameter P is at least as specialized as a
4867 // template template-argument A if, given the following rewrite to two
4868 // function templates...
4869
4870 // Rather than synthesize function templates, we merely perform the
4871 // equivalent partial ordering by performing deduction directly on
4872 // the template parameter lists of the template template parameters.
4873 //
4874 // Given an invented class template X with the template parameter list of
4875 // A (including default arguments):
4876 TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg));
4877 TemplateParameterList *A = AArg->getTemplateParameters();
4878
4879 // - Each function template has a single function parameter whose type is
4880 // a specialization of X with template arguments corresponding to the
4881 // template parameters from the respective function template
4882 SmallVector<TemplateArgument, 8> AArgs;
4883 Context.getInjectedTemplateArgs(A, AArgs);
4884
4885 // Check P's arguments against A's parameter list. This will fill in default
4886 // template arguments as needed. AArgs are already correct by construction.
4887 // We can't just use CheckTemplateIdType because that will expand alias
4888 // templates.
4889 SmallVector<TemplateArgument, 4> PArgs;
4890 {
4891 SFINAETrap Trap(*this);
4892
4893 Context.getInjectedTemplateArgs(P, PArgs);
4894 TemplateArgumentListInfo PArgList(P->getLAngleLoc(), P->getRAngleLoc());
4895 for (unsigned I = 0, N = P->size(); I != N; ++I) {
4896 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
4897 // expansions, to form an "as written" argument list.
4898 TemplateArgument Arg = PArgs[I];
4899 if (Arg.getKind() == TemplateArgument::Pack) {
4900 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
4901 Arg = *Arg.pack_begin();
4902 }
4903 PArgList.addArgument(getTrivialTemplateArgumentLoc(
4904 Arg, QualType(), P->getParam(I)->getLocation()));
4905 }
4906 PArgs.clear();
4907
4908 // C++1z [temp.arg.template]p3:
4909 // If the rewrite produces an invalid type, then P is not at least as
4910 // specialized as A.
4911 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, PArgs) ||
4912 Trap.hasErrorOccurred())
4913 return false;
4914 }
4915
4916 QualType AType = Context.getTemplateSpecializationType(X, AArgs);
4917 QualType PType = Context.getTemplateSpecializationType(X, PArgs);
4918
Richard Smith26b86ea2016-12-31 21:41:23 +00004919 // ... the function template corresponding to P is at least as specialized
4920 // as the function template corresponding to A according to the partial
4921 // ordering rules for function templates.
4922 TemplateDeductionInfo Info(Loc, A->getDepth());
4923 return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info);
4924}
4925
Mike Stump11289f42009-09-09 15:08:12 +00004926static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004927MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004928 const TemplateArgument &TemplateArg,
4929 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004930 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004931 llvm::SmallBitVector &Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004932
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004933/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00004934/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00004935static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004936MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004937 const Expr *E,
4938 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004939 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004940 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004941 // We can deduce from a pack expansion.
4942 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4943 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004944
Richard Smith34349002012-07-09 03:07:20 +00004945 // Skip through any implicit casts we added while type-checking, and any
4946 // substitutions performed by template alias expansion.
4947 while (1) {
4948 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4949 E = ICE->getSubExpr();
4950 else if (const SubstNonTypeTemplateParmExpr *Subst =
4951 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4952 E = Subst->getReplacement();
4953 else
4954 break;
4955 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004956
4957 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004958 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00004959 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00004960 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00004961 return;
4962
Mike Stump11289f42009-09-09 15:08:12 +00004963 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00004964 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4965 if (!NTTP)
4966 return;
4967
Douglas Gregor21610382009-10-29 00:04:11 +00004968 if (NTTP->getDepth() == Depth)
4969 Used[NTTP->getIndex()] = true;
Richard Smith5f274382016-09-28 23:55:27 +00004970
4971 // In C++1z mode, additional arguments may be deduced from the type of a
4972 // non-type argument.
4973 if (Ctx.getLangOpts().CPlusPlus1z)
4974 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00004975}
4976
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004977/// \brief Mark the template parameters that are used by the given
4978/// nested name specifier.
4979static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004980MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004981 NestedNameSpecifier *NNS,
4982 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00004983 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00004984 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004985 if (!NNS)
4986 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004987
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004988 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00004989 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004990 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00004991 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004992}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004993
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004994/// \brief Mark the template parameters that are used by the given
4995/// template name.
4996static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00004997MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00004998 TemplateName Name,
4999 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005000 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005001 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005002 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
5003 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00005004 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
5005 if (TTP->getDepth() == Depth)
5006 Used[TTP->getIndex()] = true;
5007 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005008 return;
5009 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005010
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005011 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005012 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005013 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005014 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005015 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005016 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005017}
5018
5019/// \brief Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00005020/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005021static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005022MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005023 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005024 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005025 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005026 if (T.isNull())
5027 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005028
Douglas Gregor91772d12009-06-13 00:26:55 +00005029 // Non-dependent types have nothing deducible
5030 if (!T->isDependentType())
5031 return;
5032
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005033 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00005034 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005035 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005036 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005037 cast<PointerType>(T)->getPointeeType(),
5038 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005039 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005040 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005041 break;
5042
5043 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005044 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005045 cast<BlockPointerType>(T)->getPointeeType(),
5046 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005047 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005048 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005049 break;
5050
5051 case Type::LValueReference:
5052 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005053 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005054 cast<ReferenceType>(T)->getPointeeType(),
5055 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005056 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005057 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005058 break;
5059
5060 case Type::MemberPointer: {
5061 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005062 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005063 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005064 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00005065 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005066 break;
5067 }
5068
5069 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005070 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005071 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00005072 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005073 // Fall through to check the element type
5074
5075 case Type::ConstantArray:
5076 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005077 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005078 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005079 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005080 break;
5081
5082 case Type::Vector:
5083 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005084 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005085 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005086 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005087 break;
5088
Douglas Gregor758a8692009-06-17 21:51:59 +00005089 case Type::DependentSizedExtVector: {
5090 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005091 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005092 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005093 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005094 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005095 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00005096 break;
5097 }
5098
Douglas Gregor91772d12009-06-13 00:26:55 +00005099 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005100 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00005101 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
5102 Used);
Alp Toker9cacbab2014-01-20 20:26:09 +00005103 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
5104 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005105 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005106 break;
5107 }
5108
Douglas Gregor21610382009-10-29 00:04:11 +00005109 case Type::TemplateTypeParm: {
5110 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
5111 if (TTP->getDepth() == Depth)
5112 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00005113 break;
Douglas Gregor21610382009-10-29 00:04:11 +00005114 }
Douglas Gregor91772d12009-06-13 00:26:55 +00005115
Douglas Gregorfb322d82011-01-14 05:11:40 +00005116 case Type::SubstTemplateTypeParmPack: {
5117 const SubstTemplateTypeParmPackType *Subst
5118 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005119 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00005120 QualType(Subst->getReplacedParameter(), 0),
5121 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005122 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00005123 OnlyDeduced, Depth, Used);
5124 break;
5125 }
5126
John McCall2408e322010-04-27 00:57:59 +00005127 case Type::InjectedClassName:
5128 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
5129 // fall through
5130
Douglas Gregor91772d12009-06-13 00:26:55 +00005131 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00005132 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005133 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005134 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005135 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005136
Douglas Gregord0ad2942010-12-23 01:24:45 +00005137 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00005138 // If the template argument list of P contains a pack expansion that is
5139 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005140 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005141 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005142 hasPackExpansionBeforeEnd(Spec->template_arguments()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005143 break;
5144
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005145 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005146 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00005147 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005148 break;
5149 }
5150
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005151 case Type::Complex:
5152 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005153 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005154 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005155 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005156 break;
5157
Eli Friedman0dfb8892011-10-06 23:00:33 +00005158 case Type::Atomic:
5159 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005160 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00005161 cast<AtomicType>(T)->getValueType(),
5162 OnlyDeduced, Depth, Used);
5163 break;
5164
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005165 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005166 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005167 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005168 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00005169 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005170 break;
5171
John McCallc392f372010-06-11 00:33:02 +00005172 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00005173 // C++14 [temp.deduct.type]p5:
5174 // The non-deduced contexts are:
5175 // -- The nested-name-specifier of a type that was specified using a
5176 // qualified-id
5177 //
5178 // C++14 [temp.deduct.type]p6:
5179 // When a type name is specified in a way that includes a non-deduced
5180 // context, all of the types that comprise that type name are also
5181 // non-deduced.
5182 if (OnlyDeduced)
5183 break;
5184
John McCallc392f372010-06-11 00:33:02 +00005185 const DependentTemplateSpecializationType *Spec
5186 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005187
Richard Smith50d5b972015-12-30 20:56:05 +00005188 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
5189 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00005190
John McCallc392f372010-06-11 00:33:02 +00005191 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005192 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00005193 Used);
5194 break;
5195 }
5196
John McCallbd8d9bd2010-03-01 23:49:17 +00005197 case Type::TypeOf:
5198 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005199 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005200 cast<TypeOfType>(T)->getUnderlyingType(),
5201 OnlyDeduced, Depth, Used);
5202 break;
5203
5204 case Type::TypeOfExpr:
5205 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005206 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005207 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
5208 OnlyDeduced, Depth, Used);
5209 break;
5210
5211 case Type::Decltype:
5212 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005213 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005214 cast<DecltypeType>(T)->getUnderlyingExpr(),
5215 OnlyDeduced, Depth, Used);
5216 break;
5217
Alexis Hunte852b102011-05-24 22:41:36 +00005218 case Type::UnaryTransform:
5219 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005220 MarkUsedTemplateParameters(Ctx,
Richard Smith5f274382016-09-28 23:55:27 +00005221 cast<UnaryTransformType>(T)->getUnderlyingType(),
Alexis Hunte852b102011-05-24 22:41:36 +00005222 OnlyDeduced, Depth, Used);
5223 break;
5224
Douglas Gregord2fa7662010-12-20 02:24:11 +00005225 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005226 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00005227 cast<PackExpansionType>(T)->getPattern(),
5228 OnlyDeduced, Depth, Used);
5229 break;
5230
Richard Smith30482bc2011-02-20 03:19:35 +00005231 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00005232 case Type::DeducedTemplateSpecialization:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005233 MarkUsedTemplateParameters(Ctx,
Richard Smith600b5262017-01-26 20:40:47 +00005234 cast<DeducedType>(T)->getDeducedType(),
Richard Smith30482bc2011-02-20 03:19:35 +00005235 OnlyDeduced, Depth, Used);
5236
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005237 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00005238 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00005239 case Type::VariableArray:
5240 case Type::FunctionNoProto:
5241 case Type::Record:
5242 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00005243 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00005244 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00005245 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00005246 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00005247 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00005248#define TYPE(Class, Base)
5249#define ABSTRACT_TYPE(Class, Base)
5250#define DEPENDENT_TYPE(Class, Base)
5251#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5252#include "clang/AST/TypeNodes.def"
5253 break;
5254 }
5255}
5256
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005257/// \brief Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00005258/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00005259static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005260MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005261 const TemplateArgument &TemplateArg,
5262 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005263 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005264 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005265 switch (TemplateArg.getKind()) {
5266 case TemplateArgument::Null:
5267 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005268 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00005269 break;
Mike Stump11289f42009-09-09 15:08:12 +00005270
Eli Friedmanb826a002012-09-26 02:36:12 +00005271 case TemplateArgument::NullPtr:
5272 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5273 Depth, Used);
5274 break;
5275
Douglas Gregor91772d12009-06-13 00:26:55 +00005276 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005277 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005278 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005279 break;
5280
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005281 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005282 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005283 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005284 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005285 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005286 break;
5287
5288 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005289 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005290 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005291 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005292
Anders Carlssonbc343912009-06-15 17:04:53 +00005293 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005294 for (const auto &P : TemplateArg.pack_elements())
5295 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005296 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005297 }
5298}
5299
James Dennett41725122012-06-22 10:16:05 +00005300/// \brief Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005301/// template argument list.
5302///
5303/// \param TemplateArgs the template argument list from which template
5304/// parameters will be deduced.
5305///
James Dennett41725122012-06-22 10:16:05 +00005306/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005307/// to indicate when the corresponding template parameter will be
5308/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005309void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005310Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005311 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005312 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005313 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005314 // If the template argument list of P contains a pack expansion that is not
5315 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005316 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005317 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005318 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005319 return;
5320
Douglas Gregor91772d12009-06-13 00:26:55 +00005321 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005322 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005323 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005324}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005325
5326/// \brief Marks all of the template parameters that will be deduced by a
5327/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005328void Sema::MarkDeducedTemplateParameters(
5329 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5330 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005331 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005332 = FunctionTemplate->getTemplateParameters();
5333 Deduced.clear();
5334 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005335
Douglas Gregorce23bae2009-09-18 23:21:38 +00005336 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5337 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005338 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005339 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005340}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005341
Richard Smith86a1b132017-02-16 03:49:44 +00005342bool hasDeducibleTemplateParameters(Sema &S, TemplateParameterList *Params,
Douglas Gregore65aacb2011-06-16 16:50:48 +00005343 QualType T) {
5344 if (!T->isDependentType())
5345 return false;
5346
Richard Smith86a1b132017-02-16 03:49:44 +00005347 llvm::SmallBitVector Deduced(Params->size());
5348 ::MarkUsedTemplateParameters(S.Context, T, true, Params->getDepth(), Deduced);
Douglas Gregore65aacb2011-06-16 16:50:48 +00005349
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005350 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005351}