blob: c191ee0a1725012ee42f8922f5e59d99b0c46113 [file] [log] [blame]
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00001//===- SemaTemplateDeduction.cpp - Template Argument Deduction ------------===//
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Douglas Gregor55ca8f62009-06-04 00:03:07 +00006//
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00007//===----------------------------------------------------------------------===//
Douglas Gregor55ca8f62009-06-04 00:03:07 +00008//
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00009// This file implements C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===//
Douglas Gregor55ca8f62009-06-04 00:03:07 +000012
John McCall19c1bfd2010-08-25 05:32:35 +000013#include "clang/Sema/TemplateDeduction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "TreeTransform.h"
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000015#include "TypeLocBuilder.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000016#include "clang/AST/ASTContext.h"
Faisal Vali571df122013-09-29 08:45:24 +000017#include "clang/AST/ASTLambda.h"
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000018#include "clang/AST/Decl.h"
19#include "clang/AST/DeclAccessPair.h"
20#include "clang/AST/DeclBase.h"
21#include "clang/AST/DeclCXX.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000022#include "clang/AST/DeclTemplate.h"
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000023#include "clang/AST/DeclarationName.h"
Douglas Gregor55ca8f62009-06-04 00:03:07 +000024#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000026#include "clang/AST/NestedNameSpecifier.h"
27#include "clang/AST/TemplateBase.h"
28#include "clang/AST/TemplateName.h"
29#include "clang/AST/Type.h"
30#include "clang/AST/TypeLoc.h"
31#include "clang/AST/UnresolvedSet.h"
32#include "clang/Basic/AddressSpaces.h"
33#include "clang/Basic/ExceptionSpecificationType.h"
34#include "clang/Basic/LLVM.h"
35#include "clang/Basic/LangOptions.h"
36#include "clang/Basic/PartialDiagnostic.h"
37#include "clang/Basic/SourceLocation.h"
38#include "clang/Basic/Specifiers.h"
39#include "clang/Sema/Ownership.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "clang/Sema/Sema.h"
41#include "clang/Sema/Template.h"
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000042#include "llvm/ADT/APInt.h"
43#include "llvm/ADT/APSInt.h"
44#include "llvm/ADT/ArrayRef.h"
45#include "llvm/ADT/DenseMap.h"
46#include "llvm/ADT/FoldingSet.h"
47#include "llvm/ADT/Optional.h"
Benjamin Kramere0513cb2012-01-30 16:17:39 +000048#include "llvm/ADT/SmallBitVector.h"
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000049#include "llvm/ADT/SmallPtrSet.h"
50#include "llvm/ADT/SmallVector.h"
51#include "llvm/Support/Casting.h"
52#include "llvm/Support/Compiler.h"
53#include "llvm/Support/ErrorHandling.h"
Douglas Gregor0ff7d922009-09-14 18:39:43 +000054#include <algorithm>
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000055#include <cassert>
56#include <tuple>
57#include <utility>
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000058
59namespace clang {
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000060
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000061 /// Various flags that control template argument deduction.
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000062 ///
63 /// These flags can be bitwise-OR'd together.
64 enum TemplateDeductionFlags {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000065 /// No template argument deduction flags, which indicates the
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000066 /// strictest results for template argument deduction (as used for, e.g.,
67 /// matching class template partial specializations).
68 TDF_None = 0,
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000069
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000070 /// Within template argument deduction from a function call, we are
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000071 /// matching with a parameter type for which the original parameter was
72 /// a reference.
73 TDF_ParamWithReferenceType = 0x1,
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000074
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000075 /// Within template argument deduction from a function call, we
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000076 /// are matching in a case where we ignore cv-qualifiers.
77 TDF_IgnoreQualifiers = 0x02,
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000078
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000079 /// Within template argument deduction from a function call,
Douglas Gregorcf0b47d2009-06-26 23:10:12 +000080 /// we are matching in a case where we can perform template argument
Douglas Gregorfc516c92009-06-26 23:27:24 +000081 /// deduction from a template-id of a derived class of the argument type.
Douglas Gregor406f6342009-09-14 20:00:47 +000082 TDF_DerivedClass = 0x04,
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000083
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000084 /// Allow non-dependent types to differ, e.g., when performing
Douglas Gregor406f6342009-09-14 20:00:47 +000085 /// template argument deduction from a function call where conversions
86 /// may apply.
Douglas Gregor85f240c2011-01-25 17:19:08 +000087 TDF_SkipNonDependent = 0x08,
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000088
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000089 /// Whether we are performing template argument deduction for
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000090 /// parameters and arguments in a top-level template argument
Douglas Gregor19a41f12013-04-17 08:45:07 +000091 TDF_TopLevelParameterTypeList = 0x10,
Eugene Zelenko82eb70f2018-02-22 22:35:17 +000092
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000093 /// Within template argument deduction from overload resolution per
Douglas Gregor19a41f12013-04-17 08:45:07 +000094 /// C++ [over.over] allow matching function types that are compatible in
Richard Smithcd198152017-06-07 21:46:22 +000095 /// terms of noreturn and default calling convention adjustments, or
96 /// similarly matching a declared template specialization against a
97 /// possible template, per C++ [temp.deduct.decl]. In either case, permit
98 /// deduction where the parameter is a function type that can be converted
99 /// to the argument type.
100 TDF_AllowCompatibleFunctionType = 0x20,
Richard Smithb884ed12018-07-11 23:19:41 +0000101
102 /// Within template argument deduction for a conversion function, we are
103 /// matching with an argument type for which the original argument was
104 /// a reference.
105 TDF_ArgWithReferenceType = 0x40,
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000106 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000107}
Douglas Gregorcf0b47d2009-06-26 23:10:12 +0000108
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000109using namespace clang;
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000110using namespace sema;
Douglas Gregor55ca8f62009-06-04 00:03:07 +0000111
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000112/// Compare two APSInts, extending and switching the sign as
Douglas Gregor0a29a052010-03-26 05:50:28 +0000113/// necessary to compare their values regardless of underlying type.
114static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
115 if (Y.getBitWidth() > X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +0000116 X = X.extend(Y.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +0000117 else if (Y.getBitWidth() < X.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +0000118 Y = Y.extend(X.getBitWidth());
Douglas Gregor0a29a052010-03-26 05:50:28 +0000119
120 // If there is a signedness mismatch, correct it.
121 if (X.isSigned() != Y.isSigned()) {
122 // If the signed value is negative, then the values cannot be the same.
123 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
124 return false;
125
126 Y.setIsSigned(true);
127 X.setIsSigned(true);
128 }
129
130 return X == Y;
131}
132
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000133static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000134DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000135 TemplateParameterList *TemplateParams,
136 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +0000137 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000138 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000139 SmallVectorImpl<DeducedTemplateArgument> &Deduced);
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000140
Douglas Gregor7baabef2010-12-22 18:17:10 +0000141static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +0000142DeduceTemplateArgumentsByTypeMatch(Sema &S,
143 TemplateParameterList *TemplateParams,
144 QualType Param,
145 QualType Arg,
146 TemplateDeductionInfo &Info,
147 SmallVectorImpl<DeducedTemplateArgument> &
148 Deduced,
149 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +0000150 bool PartialOrdering = false,
151 bool DeducedFromArrayBound = false);
Douglas Gregor5499af42011-01-05 23:12:31 +0000152
153static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000154DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +0000155 ArrayRef<TemplateArgument> Params,
156 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +0000157 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000158 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
159 bool NumberOfArgumentsMustMatch);
Douglas Gregor7baabef2010-12-22 18:17:10 +0000160
Richard Smith130cc442017-02-21 23:49:18 +0000161static void MarkUsedTemplateParameters(ASTContext &Ctx,
162 const TemplateArgument &TemplateArg,
163 bool OnlyDeduced, unsigned Depth,
164 llvm::SmallBitVector &Used);
165
166static void MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
167 bool OnlyDeduced, unsigned Level,
168 llvm::SmallBitVector &Deduced);
169
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000170/// If the given expression is of a form that permits the deduction
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000171/// of a non-type template parameter, return the declaration of that
172/// non-type template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +0000173static NonTypeTemplateParmDecl *
174getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) {
Richard Smith7ebb07c2012-07-08 04:37:51 +0000175 // If we are within an alias template, the expression may have undergone
176 // any number of parameter substitutions already.
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000177 while (true) {
Richard Smith7ebb07c2012-07-08 04:37:51 +0000178 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
179 E = IC->getSubExpr();
Fangrui Song407659a2018-11-30 23:41:18 +0000180 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(E))
181 E = CE->getSubExpr();
Richard Smith7ebb07c2012-07-08 04:37:51 +0000182 else if (SubstNonTypeTemplateParmExpr *Subst =
183 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
184 E = Subst->getReplacement();
185 else
186 break;
187 }
Mike Stump11289f42009-09-09 15:08:12 +0000188
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000189 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smith87d263e2016-12-25 08:05:23 +0000190 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
191 if (NTTP->getDepth() == Info.getDeducedDepth())
192 return NTTP;
Mike Stump11289f42009-09-09 15:08:12 +0000193
Craig Topperc3ec1492014-05-26 06:22:03 +0000194 return nullptr;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000195}
196
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000197/// Determine whether two declaration pointers refer to the same
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000198/// declaration.
199static bool isSameDeclaration(Decl *X, Decl *Y) {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000200 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
201 X = NX->getUnderlyingDecl();
202 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
203 Y = NY->getUnderlyingDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000204
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000205 return X->getCanonicalDecl() == Y->getCanonicalDecl();
206}
207
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000208/// Verify that the given, deduced template arguments are compatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000209///
210/// \returns The deduced template argument, or a NULL template argument if
211/// the deduced template arguments were incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000212static DeducedTemplateArgument
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000213checkDeducedTemplateArguments(ASTContext &Context,
214 const DeducedTemplateArgument &X,
215 const DeducedTemplateArgument &Y) {
216 // We have no deduction for one or both of the arguments; they're compatible.
217 if (X.isNull())
218 return Y;
219 if (Y.isNull())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000220 return X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000221
Richard Smith593d6a12016-12-23 01:30:39 +0000222 // If we have two non-type template argument values deduced for the same
223 // parameter, they must both match the type of the parameter, and thus must
224 // match each other's type. As we're only keeping one of them, we must check
225 // for that now. The exception is that if either was deduced from an array
226 // bound, the type is permitted to differ.
227 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
228 QualType XType = X.getNonTypeTemplateArgumentType();
229 if (!XType.isNull()) {
230 QualType YType = Y.getNonTypeTemplateArgumentType();
231 if (YType.isNull() || !Context.hasSameType(XType, YType))
232 return DeducedTemplateArgument();
233 }
234 }
235
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000236 switch (X.getKind()) {
237 case TemplateArgument::Null:
238 llvm_unreachable("Non-deduced template arguments handled above");
239
240 case TemplateArgument::Type:
241 // If two template type arguments have the same type, they're compatible.
242 if (Y.getKind() == TemplateArgument::Type &&
243 Context.hasSameType(X.getAsType(), Y.getAsType()))
244 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000245
Richard Smith5f274382016-09-28 23:55:27 +0000246 // If one of the two arguments was deduced from an array bound, the other
247 // supersedes it.
248 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
249 return X.wasDeducedFromArrayBound() ? Y : X;
250
251 // The arguments are not compatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000252 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000253
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000254 case TemplateArgument::Integral:
255 // If we deduced a constant in one case and either a dependent expression or
256 // declaration in another case, keep the integral constant.
257 // If both are integral constants with the same value, keep that value.
258 if (Y.getKind() == TemplateArgument::Expression ||
259 Y.getKind() == TemplateArgument::Declaration ||
260 (Y.getKind() == TemplateArgument::Integral &&
Benjamin Kramer6003ad52012-06-07 15:09:51 +0000261 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
Richard Smith593d6a12016-12-23 01:30:39 +0000262 return X.wasDeducedFromArrayBound() ? Y : X;
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000263
264 // All other combinations are incompatible.
265 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000266
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000267 case TemplateArgument::Template:
268 if (Y.getKind() == TemplateArgument::Template &&
269 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
270 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000271
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000272 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000273 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000274
275 case TemplateArgument::TemplateExpansion:
276 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000277 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000278 Y.getAsTemplateOrTemplatePattern()))
279 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000280
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000281 // All other combinations are incompatible.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000282 return DeducedTemplateArgument();
Douglas Gregore4ff4b52011-01-05 18:58:31 +0000283
Richard Smith593d6a12016-12-23 01:30:39 +0000284 case TemplateArgument::Expression: {
285 if (Y.getKind() != TemplateArgument::Expression)
286 return checkDeducedTemplateArguments(Context, Y, X);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000287
Richard Smith593d6a12016-12-23 01:30:39 +0000288 // Compare the expressions for equality
289 llvm::FoldingSetNodeID ID1, ID2;
290 X.getAsExpr()->Profile(ID1, Context, true);
291 Y.getAsExpr()->Profile(ID2, Context, true);
292 if (ID1 == ID2)
293 return X.wasDeducedFromArrayBound() ? Y : X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000294
Richard Smith593d6a12016-12-23 01:30:39 +0000295 // Differing dependent expressions are incompatible.
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000296 return DeducedTemplateArgument();
Richard Smith593d6a12016-12-23 01:30:39 +0000297 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000298
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000299 case TemplateArgument::Declaration:
Richard Smith593d6a12016-12-23 01:30:39 +0000300 assert(!X.wasDeducedFromArrayBound());
301
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000302 // If we deduced a declaration and a dependent expression, keep the
303 // declaration.
304 if (Y.getKind() == TemplateArgument::Expression)
305 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000306
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000307 // If we deduced a declaration and an integral constant, keep the
Richard Smith593d6a12016-12-23 01:30:39 +0000308 // integral constant and whichever type did not come from an array
309 // bound.
310 if (Y.getKind() == TemplateArgument::Integral) {
311 if (Y.wasDeducedFromArrayBound())
312 return TemplateArgument(Context, Y.getAsIntegral(),
313 X.getParamTypeForDecl());
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000314 return Y;
Richard Smith593d6a12016-12-23 01:30:39 +0000315 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000316
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000317 // If we deduced two declarations, make sure that they refer to the
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000318 // same declaration.
319 if (Y.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +0000320 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +0000321 return X;
322
323 // All other combinations are incompatible.
324 return DeducedTemplateArgument();
325
326 case TemplateArgument::NullPtr:
327 // If we deduced a null pointer and a dependent expression, keep the
328 // null pointer.
329 if (Y.getKind() == TemplateArgument::Expression)
330 return X;
331
332 // If we deduced a null pointer and an integral constant, keep the
333 // integral constant.
334 if (Y.getKind() == TemplateArgument::Integral)
335 return Y;
336
Richard Smith593d6a12016-12-23 01:30:39 +0000337 // If we deduced two null pointers, they are the same.
338 if (Y.getKind() == TemplateArgument::NullPtr)
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000339 return X;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000340
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000341 // All other combinations are incompatible.
342 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000343
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000344 case TemplateArgument::Pack: {
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000345 if (Y.getKind() != TemplateArgument::Pack ||
346 X.pack_size() != Y.pack_size())
347 return DeducedTemplateArgument();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000348
Richard Smith539e8e32017-01-04 01:48:55 +0000349 llvm::SmallVector<TemplateArgument, 8> NewPack;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000350 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000351 XAEnd = X.pack_end(),
352 YA = Y.pack_begin();
353 XA != XAEnd; ++XA, ++YA) {
Richard Smith539e8e32017-01-04 01:48:55 +0000354 TemplateArgument Merged = checkDeducedTemplateArguments(
355 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
356 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()));
357 if (Merged.isNull())
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000358 return DeducedTemplateArgument();
Richard Smith539e8e32017-01-04 01:48:55 +0000359 NewPack.push_back(Merged);
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000360 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000361
Richard Smith539e8e32017-01-04 01:48:55 +0000362 return DeducedTemplateArgument(
363 TemplateArgument::CreatePackCopy(Context, NewPack),
364 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000365 }
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000366 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000367
David Blaikiee4d798f2012-01-20 21:50:17 +0000368 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000369}
370
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000371/// Deduce the value of the given non-type template parameter
Richard Smith5d102892016-12-27 03:59:58 +0000372/// as the given deduced template argument. All non-type template parameter
373/// deduction is funneled through here.
Benjamin Kramer7320b992016-06-15 14:20:56 +0000374static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000375 Sema &S, TemplateParameterList *TemplateParams,
Richard Smith5d102892016-12-27 03:59:58 +0000376 NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced,
377 QualType ValueType, TemplateDeductionInfo &Info,
Benjamin Kramer7320b992016-06-15 14:20:56 +0000378 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith87d263e2016-12-25 08:05:23 +0000379 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
380 "deducing non-type template argument with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +0000381
Richard Smith5d102892016-12-27 03:59:58 +0000382 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
383 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000384 if (Result.isNull()) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000385 Info.Param = NTTP;
386 Info.FirstArg = Deduced[NTTP->getIndex()];
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000387 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000388 return Sema::TDK_Inconsistent;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000389 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000390
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000391 Deduced[NTTP->getIndex()] = Result;
Aaron Ballmanc351fba2017-12-04 20:27:34 +0000392 if (!S.getLangOpts().CPlusPlus17)
Richard Smithd92eddf2016-12-27 06:14:37 +0000393 return Sema::TDK_Success;
394
Richard Smith130cc442017-02-21 23:49:18 +0000395 if (NTTP->isExpandedParameterPack())
396 // FIXME: We may still need to deduce parts of the type here! But we
397 // don't have any way to find which slice of the type to use, and the
398 // type stored on the NTTP itself is nonsense. Perhaps the type of an
399 // expanded NTTP should be a pack expansion type?
400 return Sema::TDK_Success;
401
Richard Smith7bfcc052017-12-01 21:24:36 +0000402 // Get the type of the parameter for deduction. If it's a (dependent) array
403 // or function type, we will not have decayed it yet, so do that now.
404 QualType ParamType = S.Context.getAdjustedParameterType(NTTP->getType());
Richard Smith130cc442017-02-21 23:49:18 +0000405 if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
406 ParamType = Expansion->getPattern();
407
Richard Smithd92eddf2016-12-27 06:14:37 +0000408 // FIXME: It's not clear how deduction of a parameter of reference
409 // type from an argument (of non-reference type) should be performed.
410 // For now, we just remove reference types from both sides and let
411 // the final check for matching types sort out the mess.
412 return DeduceTemplateArgumentsByTypeMatch(
Richard Smith130cc442017-02-21 23:49:18 +0000413 S, TemplateParams, ParamType.getNonReferenceType(),
Richard Smithd92eddf2016-12-27 06:14:37 +0000414 ValueType.getNonReferenceType(), Info, Deduced, TDF_SkipNonDependent,
415 /*PartialOrdering=*/false,
416 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000417}
418
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000419/// Deduce the value of the given non-type template parameter
Richard Smith5d102892016-12-27 03:59:58 +0000420/// from the given integral constant.
421static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
422 Sema &S, TemplateParameterList *TemplateParams,
423 NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
424 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
425 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
426 return DeduceNonTypeTemplateArgument(
427 S, TemplateParams, NTTP,
428 DeducedTemplateArgument(S.Context, Value, ValueType,
429 DeducedFromArrayBound),
430 ValueType, Info, Deduced);
431}
432
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000433/// Deduce the value of the given non-type template parameter
Richard Smith38175a22016-09-28 22:08:38 +0000434/// from the given null pointer template argument type.
435static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
Richard Smith5f274382016-09-28 23:55:27 +0000436 Sema &S, TemplateParameterList *TemplateParams,
437 NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
Richard Smith38175a22016-09-28 22:08:38 +0000438 TemplateDeductionInfo &Info,
439 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
440 Expr *Value =
441 S.ImpCastExprToType(new (S.Context) CXXNullPtrLiteralExpr(
442 S.Context.NullPtrTy, NTTP->getLocation()),
443 NullPtrType, CK_NullToPointer)
444 .get();
Richard Smith5d102892016-12-27 03:59:58 +0000445 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
446 DeducedTemplateArgument(Value),
447 Value->getType(), Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +0000448}
449
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000450/// Deduce the value of the given non-type template parameter
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000451/// from the given type- or value-dependent expression.
452///
453/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000454static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
455 Sema &S, TemplateParameterList *TemplateParams,
456 NonTypeTemplateParmDecl *NTTP, Expr *Value, TemplateDeductionInfo &Info,
457 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith5d102892016-12-27 03:59:58 +0000458 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
459 DeducedTemplateArgument(Value),
460 Value->getType(), Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +0000461}
462
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000463/// Deduce the value of the given non-type template parameter
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000464/// from the given declaration.
465///
466/// \returns true if deduction succeeded, false otherwise.
Richard Smith5d102892016-12-27 03:59:58 +0000467static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
468 Sema &S, TemplateParameterList *TemplateParams,
469 NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
470 TemplateDeductionInfo &Info,
471 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000472 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Richard Smith593d6a12016-12-23 01:30:39 +0000473 TemplateArgument New(D, T);
Richard Smith5d102892016-12-27 03:59:58 +0000474 return DeduceNonTypeTemplateArgument(
475 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +0000476}
477
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000478static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000479DeduceTemplateArguments(Sema &S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000480 TemplateParameterList *TemplateParams,
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000481 TemplateName Param,
482 TemplateName Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000483 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +0000484 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000485 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
Douglas Gregoradee3e32009-11-11 23:06:43 +0000486 if (!ParamDecl) {
487 // The parameter type is dependent and is not a template template parameter,
488 // so there is nothing that we can deduce.
489 return Sema::TDK_Success;
490 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000491
Douglas Gregoradee3e32009-11-11 23:06:43 +0000492 if (TemplateTemplateParmDecl *TempParam
493 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
Richard Smith87d263e2016-12-25 08:05:23 +0000494 // If we're not deducing at this depth, there's nothing to deduce.
495 if (TempParam->getDepth() != Info.getDeducedDepth())
496 return Sema::TDK_Success;
497
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000498 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000499 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000500 Deduced[TempParam->getIndex()],
501 NewDeduced);
502 if (Result.isNull()) {
503 Info.Param = TempParam;
504 Info.FirstArg = Deduced[TempParam->getIndex()];
505 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000506 return Sema::TDK_Inconsistent;
Douglas Gregoradee3e32009-11-11 23:06:43 +0000507 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000508
Douglas Gregor7f8e7682010-12-22 23:09:49 +0000509 Deduced[TempParam->getIndex()] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000510 return Sema::TDK_Success;
Douglas Gregor181aa4a2009-06-12 18:26:56 +0000511 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000512
Douglas Gregoradee3e32009-11-11 23:06:43 +0000513 // Verify that the two template names are equivalent.
Chandler Carruthc1263112010-02-07 21:33:28 +0000514 if (S.Context.hasSameTemplateName(Param, Arg))
Douglas Gregoradee3e32009-11-11 23:06:43 +0000515 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000516
Douglas Gregoradee3e32009-11-11 23:06:43 +0000517 // Mismatch of non-dependent template parameter to argument.
518 Info.FirstArg = TemplateArgument(Param);
519 Info.SecondArg = TemplateArgument(Arg);
520 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +0000521}
522
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000523/// Deduce the template arguments by comparing the template parameter
Douglas Gregore81f3e72009-07-07 23:09:34 +0000524/// type (which is a template-id) with the template argument type.
525///
Chandler Carruthc1263112010-02-07 21:33:28 +0000526/// \param S the Sema
Douglas Gregore81f3e72009-07-07 23:09:34 +0000527///
528/// \param TemplateParams the template parameters that we are deducing
529///
530/// \param Param the parameter type
531///
532/// \param Arg the argument type
533///
534/// \param Info information about the template argument deduction itself
535///
536/// \param Deduced the deduced template arguments
537///
538/// \returns the result of template argument deduction so far. Note that a
539/// "success" result means that template argument deduction has not yet failed,
540/// but it may still fail, later, for other reasons.
541static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +0000542DeduceTemplateArguments(Sema &S,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000543 TemplateParameterList *TemplateParams,
544 const TemplateSpecializationType *Param,
545 QualType Arg,
John McCall19c1bfd2010-08-25 05:32:35 +0000546 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +0000547 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
John McCallb692a092009-10-22 20:10:53 +0000548 assert(Arg.isCanonical() && "Argument type must be canonical");
Mike Stump11289f42009-09-09 15:08:12 +0000549
Richard Smith13373182018-01-04 01:24:17 +0000550 // Treat an injected-class-name as its underlying template-id.
551 if (auto *Injected = dyn_cast<InjectedClassNameType>(Arg))
552 Arg = Injected->getInjectedSpecializationType();
553
Douglas Gregore81f3e72009-07-07 23:09:34 +0000554 // Check whether the template argument is a dependent template-id.
Mike Stump11289f42009-09-09 15:08:12 +0000555 if (const TemplateSpecializationType *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000556 = dyn_cast<TemplateSpecializationType>(Arg)) {
557 // Perform template argument deduction for the template name.
558 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000559 = DeduceTemplateArguments(S, TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000560 Param->getTemplateName(),
561 SpecArg->getTemplateName(),
562 Info, Deduced))
563 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000564
Mike Stump11289f42009-09-09 15:08:12 +0000565
Douglas Gregore81f3e72009-07-07 23:09:34 +0000566 // Perform template argument deduction on each template
Douglas Gregord80ea202010-12-22 18:55:49 +0000567 // argument. Ignore any missing/extra arguments, since they could be
568 // filled in by default arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000569 return DeduceTemplateArguments(S, TemplateParams,
570 Param->template_arguments(),
571 SpecArg->template_arguments(), Info, Deduced,
Erik Pilkington6a16ac02016-06-28 23:05:09 +0000572 /*NumberOfArgumentsMustMatch=*/false);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000573 }
Mike Stump11289f42009-09-09 15:08:12 +0000574
Douglas Gregore81f3e72009-07-07 23:09:34 +0000575 // If the argument type is a class template specialization, we
576 // perform template argument deduction using its template
577 // arguments.
578 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
Richard Smith44ecdbd2013-01-31 05:19:49 +0000579 if (!RecordArg) {
580 Info.FirstArg = TemplateArgument(QualType(Param, 0));
581 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000582 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000583 }
Mike Stump11289f42009-09-09 15:08:12 +0000584
585 ClassTemplateSpecializationDecl *SpecArg
Douglas Gregore81f3e72009-07-07 23:09:34 +0000586 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
Richard Smith44ecdbd2013-01-31 05:19:49 +0000587 if (!SpecArg) {
588 Info.FirstArg = TemplateArgument(QualType(Param, 0));
589 Info.SecondArg = TemplateArgument(Arg);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000590 return Sema::TDK_NonDeducedMismatch;
Richard Smith44ecdbd2013-01-31 05:19:49 +0000591 }
Mike Stump11289f42009-09-09 15:08:12 +0000592
Douglas Gregore81f3e72009-07-07 23:09:34 +0000593 // Perform template argument deduction for the template name.
594 if (Sema::TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +0000595 = DeduceTemplateArguments(S,
Douglas Gregoradee3e32009-11-11 23:06:43 +0000596 TemplateParams,
Douglas Gregore81f3e72009-07-07 23:09:34 +0000597 Param->getTemplateName(),
598 TemplateName(SpecArg->getSpecializedTemplate()),
599 Info, Deduced))
600 return Result;
Mike Stump11289f42009-09-09 15:08:12 +0000601
Douglas Gregor7baabef2010-12-22 18:17:10 +0000602 // Perform template argument deduction for the template arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +0000603 return DeduceTemplateArguments(S, TemplateParams, Param->template_arguments(),
604 SpecArg->getTemplateArgs().asArray(), Info,
605 Deduced, /*NumberOfArgumentsMustMatch=*/true);
Douglas Gregore81f3e72009-07-07 23:09:34 +0000606}
607
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000608/// Determines whether the given type is an opaque type that
John McCall08569062010-08-28 22:14:41 +0000609/// might be more qualified when instantiated.
610static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
611 switch (T->getTypeClass()) {
612 case Type::TypeOfExpr:
613 case Type::TypeOf:
614 case Type::DependentName:
615 case Type::Decltype:
616 case Type::UnresolvedUsing:
John McCall6c9dd522011-01-18 07:41:22 +0000617 case Type::TemplateTypeParm:
John McCall08569062010-08-28 22:14:41 +0000618 return true;
619
620 case Type::ConstantArray:
621 case Type::IncompleteArray:
622 case Type::VariableArray:
623 case Type::DependentSizedArray:
624 return IsPossiblyOpaquelyQualifiedType(
625 cast<ArrayType>(T)->getElementType());
626
627 default:
628 return false;
629 }
630}
631
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000632/// Helper function to build a TemplateParameter when we don't
Douglas Gregor5499af42011-01-05 23:12:31 +0000633/// know its type statically.
634static TemplateParameter makeTemplateParameter(Decl *D) {
635 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
636 return TemplateParameter(TTP);
Craig Topper4b482ee2013-07-08 04:24:47 +0000637 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
Douglas Gregor5499af42011-01-05 23:12:31 +0000638 return TemplateParameter(NTTP);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000639
Douglas Gregor5499af42011-01-05 23:12:31 +0000640 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
641}
642
Richard Smith4a8f3512018-07-19 19:00:37 +0000643/// If \p Param is an expanded parameter pack, get the number of expansions.
644static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
645 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
646 if (NTTP->isExpandedParameterPack())
647 return NTTP->getNumExpansionTypes();
648
649 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param))
650 if (TTP->isExpandedParameterPack())
651 return TTP->getNumExpansionTemplateParameters();
652
653 return None;
654}
655
Richard Smith0a80d572014-05-29 01:12:14 +0000656/// A pack that we're currently deducing.
657struct clang::DeducedPack {
Richard Smith0a80d572014-05-29 01:12:14 +0000658 // The index of the pack.
659 unsigned Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000660
Richard Smith0a80d572014-05-29 01:12:14 +0000661 // The old value of the pack before we started deducing it.
662 DeducedTemplateArgument Saved;
Richard Smith802c4b72012-08-23 06:16:52 +0000663
Richard Smith0a80d572014-05-29 01:12:14 +0000664 // A deferred value of this pack from an inner deduction, that couldn't be
665 // deduced because this deduction hadn't happened yet.
666 DeducedTemplateArgument DeferredDeduction;
667
668 // The new value of the pack.
669 SmallVector<DeducedTemplateArgument, 4> New;
670
671 // The outer deduction for this pack, if any.
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000672 DeducedPack *Outer = nullptr;
673
674 DeducedPack(unsigned Index) : Index(Index) {}
Richard Smith0a80d572014-05-29 01:12:14 +0000675};
676
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000677namespace {
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000678
Richard Smith0a80d572014-05-29 01:12:14 +0000679/// A scope in which we're performing pack deduction.
680class PackDeductionScope {
681public:
Richard Smith4a8f3512018-07-19 19:00:37 +0000682 /// Prepare to deduce the packs named within Pattern.
Richard Smith0a80d572014-05-29 01:12:14 +0000683 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
684 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
685 TemplateDeductionInfo &Info, TemplateArgument Pattern)
686 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
Richard Smith4a8f3512018-07-19 19:00:37 +0000687 unsigned NumNamedPacks = addPacks(Pattern);
688 finishConstruction(NumNamedPacks);
689 }
690
691 /// Prepare to directly deduce arguments of the parameter with index \p Index.
692 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
693 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
694 TemplateDeductionInfo &Info, unsigned Index)
695 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
696 addPack(Index);
697 finishConstruction(1);
698 }
699
700private:
701 void addPack(unsigned Index) {
702 // Save the deduced template argument for the parameter pack expanded
703 // by this pack expansion, then clear out the deduction.
704 DeducedPack Pack(Index);
705 Pack.Saved = Deduced[Index];
706 Deduced[Index] = TemplateArgument();
707
708 // FIXME: What if we encounter multiple packs with different numbers of
709 // pre-expanded expansions? (This should already have been diagnosed
710 // during substitution.)
711 if (Optional<unsigned> ExpandedPackExpansions =
712 getExpandedPackSize(TemplateParams->getParam(Index)))
713 FixedNumExpansions = ExpandedPackExpansions;
714
715 Packs.push_back(Pack);
716 }
717
718 unsigned addPacks(TemplateArgument Pattern) {
719 // Compute the set of template parameter indices that correspond to
720 // parameter packs expanded by the pack expansion.
721 llvm::SmallBitVector SawIndices(TemplateParams->size());
722
723 auto AddPack = [&](unsigned Index) {
724 if (SawIndices[Index])
725 return;
726 SawIndices[Index] = true;
727 addPack(Index);
728 };
729
730 // First look for unexpanded packs in the pattern.
731 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
732 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
733 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
734 unsigned Depth, Index;
735 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
736 if (Depth == Info.getDeducedDepth())
737 AddPack(Index);
738 }
739 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
740
741 unsigned NumNamedPacks = Packs.size();
742
743 // We can also have deduced template parameters that do not actually
744 // appear in the pattern, but can be deduced by it (the type of a non-type
745 // template parameter pack, in particular). These won't have prevented us
746 // from partially expanding the pack.
747 llvm::SmallBitVector Used(TemplateParams->size());
748 MarkUsedTemplateParameters(S.Context, Pattern, /*OnlyDeduced*/true,
749 Info.getDeducedDepth(), Used);
750 for (int Index = Used.find_first(); Index != -1;
751 Index = Used.find_next(Index))
752 if (TemplateParams->getParam(Index)->isParameterPack())
753 AddPack(Index);
754
755 return NumNamedPacks;
756 }
757
758 void finishConstruction(unsigned NumNamedPacks) {
Richard Smith130cc442017-02-21 23:49:18 +0000759 // Dig out the partially-substituted pack, if there is one.
760 const TemplateArgument *PartialPackArgs = nullptr;
761 unsigned NumPartialPackArgs = 0;
762 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
763 if (auto *Scope = S.CurrentInstantiationScope)
764 if (auto *Partial = Scope->getPartiallySubstitutedPack(
765 &PartialPackArgs, &NumPartialPackArgs))
766 PartialPackDepthIndex = getDepthAndIndex(Partial);
767
Richard Smith4a8f3512018-07-19 19:00:37 +0000768 // This pack expansion will have been partially or fully expanded if
769 // it only names explicitly-specified parameter packs (including the
770 // partially-substituted one, if any).
771 bool IsExpanded = true;
772 for (unsigned I = 0; I != NumNamedPacks; ++I) {
773 if (Packs[I].Index >= Info.getNumExplicitArgs()) {
774 IsExpanded = false;
775 IsPartiallyExpanded = false;
776 break;
Richard Smith0a80d572014-05-29 01:12:14 +0000777 }
Richard Smith4a8f3512018-07-19 19:00:37 +0000778 if (PartialPackDepthIndex ==
779 std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
780 IsPartiallyExpanded = true;
781 }
Richard Smith0a80d572014-05-29 01:12:14 +0000782 }
Richard Smith0a80d572014-05-29 01:12:14 +0000783
Richard Smith4a8f3512018-07-19 19:00:37 +0000784 // Skip over the pack elements that were expanded into separate arguments.
785 // If we partially expanded, this is the number of partial arguments.
786 if (IsPartiallyExpanded)
787 PackElements += NumPartialPackArgs;
788 else if (IsExpanded)
789 PackElements += *FixedNumExpansions;
790
Richard Smith0a80d572014-05-29 01:12:14 +0000791 for (auto &Pack : Packs) {
792 if (Info.PendingDeducedPacks.size() > Pack.Index)
793 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
794 else
795 Info.PendingDeducedPacks.resize(Pack.Index + 1);
796 Info.PendingDeducedPacks[Pack.Index] = &Pack;
797
Richard Smith130cc442017-02-21 23:49:18 +0000798 if (PartialPackDepthIndex ==
799 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
800 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
801 // We pre-populate the deduced value of the partially-substituted
802 // pack with the specified value. This is not entirely correct: the
803 // value is supposed to have been substituted, not deduced, but the
804 // cases where this is observable require an exact type match anyway.
805 //
806 // FIXME: If we could represent a "depth i, index j, pack elem k"
807 // parameter, we could substitute the partially-substituted pack
808 // everywhere and avoid this.
Richard Smith4a8f3512018-07-19 19:00:37 +0000809 if (!IsPartiallyExpanded)
Richard Smith130cc442017-02-21 23:49:18 +0000810 Deduced[Pack.Index] = Pack.New[PackElements];
Richard Smith0a80d572014-05-29 01:12:14 +0000811 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000812 }
813 }
Douglas Gregora8bd0d92011-01-10 17:35:05 +0000814
Richard Smith4a8f3512018-07-19 19:00:37 +0000815public:
Richard Smith0a80d572014-05-29 01:12:14 +0000816 ~PackDeductionScope() {
817 for (auto &Pack : Packs)
818 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
Douglas Gregorb94a6172011-01-10 17:53:52 +0000819 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000820
Richard Smithde0d34a2017-01-09 07:14:40 +0000821 /// Determine whether this pack has already been partially expanded into a
822 /// sequence of (prior) function parameters / template arguments.
Richard Smith130cc442017-02-21 23:49:18 +0000823 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
Richard Smithde0d34a2017-01-09 07:14:40 +0000824
Richard Smith4a8f3512018-07-19 19:00:37 +0000825 /// Determine whether this pack expansion scope has a known, fixed arity.
826 /// This happens if it involves a pack from an outer template that has
827 /// (notionally) already been expanded.
828 bool hasFixedArity() { return FixedNumExpansions.hasValue(); }
829
830 /// Determine whether the next element of the argument is still part of this
831 /// pack. This is the case unless the pack is already expanded to a fixed
832 /// length.
833 bool hasNextElement() {
834 return !FixedNumExpansions || *FixedNumExpansions > PackElements;
835 }
836
Richard Smith0a80d572014-05-29 01:12:14 +0000837 /// Move to deducing the next element in each pack that is being deduced.
838 void nextPackElement() {
839 // Capture the deduced template arguments for each parameter pack expanded
840 // by this pack expansion, add them to the list of arguments we've deduced
841 // for that pack, then clear out the deduced argument.
842 for (auto &Pack : Packs) {
843 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
Richard Smith539e8e32017-01-04 01:48:55 +0000844 if (!Pack.New.empty() || !DeducedArg.isNull()) {
845 while (Pack.New.size() < PackElements)
846 Pack.New.push_back(DeducedTemplateArgument());
Richard Smith130cc442017-02-21 23:49:18 +0000847 if (Pack.New.size() == PackElements)
848 Pack.New.push_back(DeducedArg);
849 else
850 Pack.New[PackElements] = DeducedArg;
851 DeducedArg = Pack.New.size() > PackElements + 1
852 ? Pack.New[PackElements + 1]
853 : DeducedTemplateArgument();
Richard Smith0a80d572014-05-29 01:12:14 +0000854 }
855 }
Richard Smith539e8e32017-01-04 01:48:55 +0000856 ++PackElements;
Richard Smith0a80d572014-05-29 01:12:14 +0000857 }
858
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000859 /// Finish template argument deduction for a set of argument packs,
Richard Smith0a80d572014-05-29 01:12:14 +0000860 /// producing the argument packs and checking for consistency with prior
861 /// deductions.
Richard Smith4a8f3512018-07-19 19:00:37 +0000862 Sema::TemplateDeductionResult
863 finish(bool TreatNoDeductionsAsNonDeduced = true) {
Richard Smith0a80d572014-05-29 01:12:14 +0000864 // Build argument packs for each of the parameter packs expanded by this
865 // pack expansion.
866 for (auto &Pack : Packs) {
867 // Put back the old value for this pack.
868 Deduced[Pack.Index] = Pack.Saved;
869
Richard Smith4a8f3512018-07-19 19:00:37 +0000870 // If we are deducing the size of this pack even if we didn't deduce any
871 // values for it, then make sure we build a pack of the right size.
872 // FIXME: Should we always deduce the size, even if the pack appears in
873 // a non-deduced context?
874 if (!TreatNoDeductionsAsNonDeduced)
875 Pack.New.resize(PackElements);
876
Richard Smith0a80d572014-05-29 01:12:14 +0000877 // Build or find a new value for this pack.
878 DeducedTemplateArgument NewPack;
Richard Smith539e8e32017-01-04 01:48:55 +0000879 if (PackElements && Pack.New.empty()) {
Richard Smith0a80d572014-05-29 01:12:14 +0000880 if (Pack.DeferredDeduction.isNull()) {
881 // We were not able to deduce anything for this parameter pack
882 // (because it only appeared in non-deduced contexts), so just
883 // restore the saved argument pack.
884 continue;
885 }
886
887 NewPack = Pack.DeferredDeduction;
888 Pack.DeferredDeduction = TemplateArgument();
889 } else if (Pack.New.empty()) {
890 // If we deduced an empty argument pack, create it now.
891 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
892 } else {
893 TemplateArgument *ArgumentPack =
894 new (S.Context) TemplateArgument[Pack.New.size()];
895 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
896 NewPack = DeducedTemplateArgument(
Benjamin Kramercce63472015-08-05 09:40:22 +0000897 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
Richard Smith7fa88bb2017-02-21 07:22:31 +0000898 // FIXME: This is wrong, it's possible that some pack elements are
899 // deduced from an array bound and others are not:
900 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
901 // g({1, 2, 3}, {{}, {}});
902 // ... should deduce T = {int, size_t (from array bound)}.
Richard Smith0a80d572014-05-29 01:12:14 +0000903 Pack.New[0].wasDeducedFromArrayBound());
904 }
905
906 // Pick where we're going to put the merged pack.
907 DeducedTemplateArgument *Loc;
908 if (Pack.Outer) {
909 if (Pack.Outer->DeferredDeduction.isNull()) {
910 // Defer checking this pack until we have a complete pack to compare
911 // it against.
912 Pack.Outer->DeferredDeduction = NewPack;
913 continue;
914 }
915 Loc = &Pack.Outer->DeferredDeduction;
916 } else {
917 Loc = &Deduced[Pack.Index];
918 }
919
920 // Check the new pack matches any previous value.
921 DeducedTemplateArgument OldPack = *Loc;
922 DeducedTemplateArgument Result =
923 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
924
925 // If we deferred a deduction of this pack, check that one now too.
926 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
927 OldPack = Result;
928 NewPack = Pack.DeferredDeduction;
929 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
930 }
931
Richard Smith4a8f3512018-07-19 19:00:37 +0000932 NamedDecl *Param = TemplateParams->getParam(Pack.Index);
Richard Smith0a80d572014-05-29 01:12:14 +0000933 if (Result.isNull()) {
Richard Smith4a8f3512018-07-19 19:00:37 +0000934 Info.Param = makeTemplateParameter(Param);
Richard Smith0a80d572014-05-29 01:12:14 +0000935 Info.FirstArg = OldPack;
936 Info.SecondArg = NewPack;
937 return Sema::TDK_Inconsistent;
938 }
939
Richard Smith4a8f3512018-07-19 19:00:37 +0000940 // If we have a pre-expanded pack and we didn't deduce enough elements
941 // for it, fail deduction.
942 if (Optional<unsigned> Expansions = getExpandedPackSize(Param)) {
943 if (*Expansions != PackElements) {
944 Info.Param = makeTemplateParameter(Param);
945 Info.FirstArg = Result;
946 return Sema::TDK_IncompletePack;
947 }
948 }
949
Richard Smith0a80d572014-05-29 01:12:14 +0000950 *Loc = Result;
951 }
952
953 return Sema::TDK_Success;
954 }
955
956private:
957 Sema &S;
958 TemplateParameterList *TemplateParams;
959 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
960 TemplateDeductionInfo &Info;
Richard Smith539e8e32017-01-04 01:48:55 +0000961 unsigned PackElements = 0;
Richard Smith130cc442017-02-21 23:49:18 +0000962 bool IsPartiallyExpanded = false;
Richard Smith4a8f3512018-07-19 19:00:37 +0000963 /// The number of expansions, if we have a fully-expanded pack in this scope.
964 Optional<unsigned> FixedNumExpansions;
Richard Smith0a80d572014-05-29 01:12:14 +0000965
966 SmallVector<DeducedPack, 2> Packs;
967};
Eugene Zelenko82eb70f2018-02-22 22:35:17 +0000968
Benjamin Kramerd5748c72015-03-23 12:31:05 +0000969} // namespace
Douglas Gregorb94a6172011-01-10 17:53:52 +0000970
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000971/// Deduce the template arguments by comparing the list of parameter
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000972/// types to the list of argument types, as in the parameter-type-lists of
973/// function types (C++ [temp.deduct.type]p10).
Douglas Gregor5499af42011-01-05 23:12:31 +0000974///
975/// \param S The semantic analysis object within which we are deducing
976///
977/// \param TemplateParams The template parameters that we are deducing
978///
979/// \param Params The list of parameter types
980///
981/// \param NumParams The number of types in \c Params
982///
983/// \param Args The list of argument types
984///
985/// \param NumArgs The number of types in \c Args
986///
987/// \param Info information about the template argument deduction itself
988///
989/// \param Deduced the deduced template arguments
990///
991/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
992/// how template argument deduction is performed.
993///
Douglas Gregorb837ea42011-01-11 17:34:58 +0000994/// \param PartialOrdering If true, we are performing template argument
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000995/// deduction for during partial ordering for a call
Douglas Gregorb837ea42011-01-11 17:34:58 +0000996/// (C++0x [temp.deduct.partial]).
997///
Douglas Gregor5499af42011-01-05 23:12:31 +0000998/// \returns the result of template argument deduction so far. Note that a
999/// "success" result means that template argument deduction has not yet failed,
1000/// but it may still fail, later, for other reasons.
1001static Sema::TemplateDeductionResult
1002DeduceTemplateArguments(Sema &S,
1003 TemplateParameterList *TemplateParams,
1004 const QualType *Params, unsigned NumParams,
1005 const QualType *Args, unsigned NumArgs,
1006 TemplateDeductionInfo &Info,
Craig Topperc1bbe8d2013-07-08 04:16:49 +00001007 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Douglas Gregorb837ea42011-01-11 17:34:58 +00001008 unsigned TDF,
Richard Smithed563c22015-02-20 04:45:22 +00001009 bool PartialOrdering = false) {
Douglas Gregor5499af42011-01-05 23:12:31 +00001010 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001011 // Similarly, if P has a form that contains (T), then each parameter type
1012 // Pi of the respective parameter-type- list of P is compared with the
1013 // corresponding parameter type Ai of the corresponding parameter-type-list
1014 // of A. [...]
Douglas Gregor5499af42011-01-05 23:12:31 +00001015 unsigned ArgIdx = 0, ParamIdx = 0;
1016 for (; ParamIdx != NumParams; ++ParamIdx) {
1017 // Check argument types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001018 const PackExpansionType *Expansion
Douglas Gregor5499af42011-01-05 23:12:31 +00001019 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
1020 if (!Expansion) {
1021 // Simple case: compare the parameter and argument types at this point.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001022
Douglas Gregor5499af42011-01-05 23:12:31 +00001023 // Make sure we have an argument.
1024 if (ArgIdx >= NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +00001025 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001026
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001027 if (isa<PackExpansionType>(Args[ArgIdx])) {
1028 // C++0x [temp.deduct.type]p22:
1029 // If the original function parameter associated with A is a function
1030 // parameter pack and the function parameter associated with P is not
1031 // a function parameter pack, then template argument deduction fails.
Richard Smith44ecdbd2013-01-31 05:19:49 +00001032 return Sema::TDK_MiscellaneousDeductionFailure;
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001033 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001034
Douglas Gregor5499af42011-01-05 23:12:31 +00001035 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001036 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1037 Params[ParamIdx], Args[ArgIdx],
1038 Info, Deduced, TDF,
Richard Smithed563c22015-02-20 04:45:22 +00001039 PartialOrdering))
Douglas Gregor5499af42011-01-05 23:12:31 +00001040 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001041
Douglas Gregor5499af42011-01-05 23:12:31 +00001042 ++ArgIdx;
1043 continue;
1044 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001045
Douglas Gregor5499af42011-01-05 23:12:31 +00001046 // C++0x [temp.deduct.type]p10:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001047 // If the parameter-declaration corresponding to Pi is a function
Douglas Gregor5499af42011-01-05 23:12:31 +00001048 // parameter pack, then the type of its declarator- id is compared with
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001049 // each remaining parameter type in the parameter-type-list of A. Each
Douglas Gregor5499af42011-01-05 23:12:31 +00001050 // comparison deduces template arguments for subsequent positions in the
1051 // template parameter packs expanded by the function parameter pack.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001052
Douglas Gregor5499af42011-01-05 23:12:31 +00001053 QualType Pattern = Expansion->getPattern();
Richard Smith0a80d572014-05-29 01:12:14 +00001054 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001055
Richard Smith4a8f3512018-07-19 19:00:37 +00001056 // A pack scope with fixed arity is not really a pack any more, so is not
1057 // a non-deduced context.
1058 if (ParamIdx + 1 == NumParams || PackScope.hasFixedArity()) {
1059 for (; ArgIdx < NumArgs && PackScope.hasNextElement(); ++ArgIdx) {
Richard Smithc379d1a2018-07-12 23:32:39 +00001060 // Deduce template arguments from the pattern.
1061 if (Sema::TemplateDeductionResult Result
1062 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
1063 Args[ArgIdx], Info, Deduced,
1064 TDF, PartialOrdering))
1065 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001066
Richard Smithc379d1a2018-07-12 23:32:39 +00001067 PackScope.nextPackElement();
1068 }
1069 } else {
1070 // C++0x [temp.deduct.type]p5:
1071 // The non-deduced contexts are:
1072 // - A function parameter pack that does not occur at the end of the
1073 // parameter-declaration-clause.
1074 //
1075 // FIXME: There is no wording to say what we should do in this case. We
1076 // choose to resolve this by applying the same rule that is applied for a
1077 // function call: that is, deduce all contained packs to their
1078 // explicitly-specified values (or to <> if there is no such value).
1079 //
1080 // This is seemingly-arbitrarily different from the case of a template-id
1081 // with a non-trailing pack-expansion in its arguments, which renders the
1082 // entire template-argument-list a non-deduced context.
1083
1084 // If the parameter type contains an explicitly-specified pack that we
1085 // could not expand, skip the number of parameters notionally created
1086 // by the expansion.
1087 Optional<unsigned> NumExpansions = Expansion->getNumExpansions();
1088 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
1089 for (unsigned I = 0; I != *NumExpansions && ArgIdx < NumArgs;
1090 ++I, ++ArgIdx)
1091 PackScope.nextPackElement();
1092 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001093 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001094
Douglas Gregor5499af42011-01-05 23:12:31 +00001095 // Build argument packs for each of the parameter packs expanded by this
1096 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00001097 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001098 return Result;
Douglas Gregor5499af42011-01-05 23:12:31 +00001099 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001100
Douglas Gregor5499af42011-01-05 23:12:31 +00001101 // Make sure we don't have any extra arguments.
1102 if (ArgIdx < NumArgs)
Richard Smith44ecdbd2013-01-31 05:19:49 +00001103 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001104
Douglas Gregor5499af42011-01-05 23:12:31 +00001105 return Sema::TDK_Success;
1106}
1107
Richard Smith34c32502018-07-11 21:07:04 +00001108/// Determine whether the parameter has qualifiers that the argument
1109/// lacks. Put another way, determine whether there is no way to add
1110/// a deduced set of qualifiers to the ParamType that would result in
1111/// its qualifiers matching those of the ArgType.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001112static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
1113 QualType ArgType) {
1114 Qualifiers ParamQs = ParamType.getQualifiers();
1115 Qualifiers ArgQs = ArgType.getQualifiers();
1116
1117 if (ParamQs == ArgQs)
1118 return false;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001119
Douglas Gregor1d684c22011-04-28 00:56:09 +00001120 // Mismatched (but not missing) Objective-C GC attributes.
Simon Pilgrim728134c2016-08-12 11:43:57 +00001121 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
Douglas Gregor1d684c22011-04-28 00:56:09 +00001122 ParamQs.hasObjCGCAttr())
1123 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001124
Douglas Gregor1d684c22011-04-28 00:56:09 +00001125 // Mismatched (but not missing) address spaces.
1126 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
1127 ParamQs.hasAddressSpace())
1128 return true;
1129
John McCall31168b02011-06-15 23:02:42 +00001130 // Mismatched (but not missing) Objective-C lifetime qualifiers.
1131 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
1132 ParamQs.hasObjCLifetime())
1133 return true;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001134
Richard Smith34c32502018-07-11 21:07:04 +00001135 // CVR qualifiers inconsistent or a superset.
1136 return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
Douglas Gregor1d684c22011-04-28 00:56:09 +00001137}
1138
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001139/// Compare types for equality with respect to possibly compatible
Douglas Gregor19a41f12013-04-17 08:45:07 +00001140/// function types (noreturn adjustment, implicit calling conventions). If any
1141/// of parameter and argument is not a function, just perform type comparison.
1142///
1143/// \param Param the template parameter type.
1144///
1145/// \param Arg the argument type.
1146bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
1147 CanQualType Arg) {
1148 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
1149 *ArgFunction = Arg->getAs<FunctionType>();
1150
1151 // Just compare if not functions.
1152 if (!ParamFunction || !ArgFunction)
1153 return Param == Arg;
1154
Richard Smith3c4f8d22016-10-16 17:54:23 +00001155 // Noreturn and noexcept adjustment.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001156 QualType AdjustedParam;
Richard Smith3c4f8d22016-10-16 17:54:23 +00001157 if (IsFunctionConversion(Param, Arg, AdjustedParam))
Douglas Gregor19a41f12013-04-17 08:45:07 +00001158 return Arg == Context.getCanonicalType(AdjustedParam);
1159
1160 // FIXME: Compatible calling conventions.
1161
1162 return Param == Arg;
1163}
1164
Richard Smith32918772017-02-14 00:25:28 +00001165/// Get the index of the first template parameter that was originally from the
1166/// innermost template-parameter-list. This is 0 except when we concatenate
1167/// the template parameter lists of a class template and a constructor template
1168/// when forming an implicit deduction guide.
1169static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD) {
Richard Smithbc491202017-02-17 20:05:37 +00001170 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1171 if (!Guide || !Guide->isImplicit())
Richard Smith32918772017-02-14 00:25:28 +00001172 return 0;
Richard Smithbc491202017-02-17 20:05:37 +00001173 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
Richard Smith32918772017-02-14 00:25:28 +00001174}
1175
1176/// Determine whether a type denotes a forwarding reference.
1177static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1178 // C++1z [temp.deduct.call]p3:
1179 // A forwarding reference is an rvalue reference to a cv-unqualified
1180 // template parameter that does not represent a template parameter of a
1181 // class template.
1182 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1183 if (ParamRef->getPointeeType().getQualifiers())
1184 return false;
1185 auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
1186 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1187 }
1188 return false;
1189}
1190
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001191/// Deduce the template arguments by comparing the parameter type and
Douglas Gregorcceb9752009-06-26 18:27:22 +00001192/// the argument type (C++ [temp.deduct.type]).
1193///
Chandler Carruthc1263112010-02-07 21:33:28 +00001194/// \param S the semantic analysis object within which we are deducing
Douglas Gregorcceb9752009-06-26 18:27:22 +00001195///
1196/// \param TemplateParams the template parameters that we are deducing
1197///
1198/// \param ParamIn the parameter type
1199///
1200/// \param ArgIn the argument type
1201///
1202/// \param Info information about the template argument deduction itself
1203///
1204/// \param Deduced the deduced template arguments
1205///
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001206/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
Mike Stump11289f42009-09-09 15:08:12 +00001207/// how template argument deduction is performed.
Douglas Gregorcceb9752009-06-26 18:27:22 +00001208///
Douglas Gregorb837ea42011-01-11 17:34:58 +00001209/// \param PartialOrdering Whether we're performing template argument deduction
1210/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1211///
Douglas Gregorcceb9752009-06-26 18:27:22 +00001212/// \returns the result of template argument deduction so far. Note that a
1213/// "success" result means that template argument deduction has not yet failed,
1214/// but it may still fail, later, for other reasons.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001215static Sema::TemplateDeductionResult
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001216DeduceTemplateArgumentsByTypeMatch(Sema &S,
1217 TemplateParameterList *TemplateParams,
1218 QualType ParamIn, QualType ArgIn,
1219 TemplateDeductionInfo &Info,
1220 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1221 unsigned TDF,
Richard Smith5f274382016-09-28 23:55:27 +00001222 bool PartialOrdering,
1223 bool DeducedFromArrayBound) {
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001224 // We only want to look at the canonical types, since typedefs and
1225 // sugar are not part of template argument deduction.
Chandler Carruthc1263112010-02-07 21:33:28 +00001226 QualType Param = S.Context.getCanonicalType(ParamIn);
1227 QualType Arg = S.Context.getCanonicalType(ArgIn);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001228
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001229 // If the argument type is a pack expansion, look at its pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001230 // This isn't explicitly called out
Douglas Gregor2fcb8632011-01-11 22:21:24 +00001231 if (const PackExpansionType *ArgExpansion
1232 = dyn_cast<PackExpansionType>(Arg))
1233 Arg = ArgExpansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001234
Douglas Gregorb837ea42011-01-11 17:34:58 +00001235 if (PartialOrdering) {
Richard Smithed563c22015-02-20 04:45:22 +00001236 // C++11 [temp.deduct.partial]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001237 // Before the partial ordering is done, certain transformations are
1238 // performed on the types used for partial ordering:
1239 // - If P is a reference type, P is replaced by the type referred to.
Douglas Gregorb837ea42011-01-11 17:34:58 +00001240 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1241 if (ParamRef)
1242 Param = ParamRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001243
Douglas Gregorb837ea42011-01-11 17:34:58 +00001244 // - If A is a reference type, A is replaced by the type referred to.
1245 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1246 if (ArgRef)
1247 Arg = ArgRef->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001248
Richard Smithed563c22015-02-20 04:45:22 +00001249 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1250 // C++11 [temp.deduct.partial]p9:
1251 // If, for a given type, deduction succeeds in both directions (i.e.,
1252 // the types are identical after the transformations above) and both
1253 // P and A were reference types [...]:
1254 // - if [one type] was an lvalue reference and [the other type] was
1255 // not, [the other type] is not considered to be at least as
1256 // specialized as [the first type]
1257 // - if [one type] is more cv-qualified than [the other type],
1258 // [the other type] is not considered to be at least as specialized
1259 // as [the first type]
1260 // Objective-C ARC adds:
1261 // - [one type] has non-trivial lifetime, [the other type] has
1262 // __unsafe_unretained lifetime, and the types are otherwise
1263 // identical
Douglas Gregorb837ea42011-01-11 17:34:58 +00001264 //
Richard Smithed563c22015-02-20 04:45:22 +00001265 // A is "considered to be at least as specialized" as P iff deduction
1266 // succeeds, so we model this as a deduction failure. Note that
1267 // [the first type] is P and [the other type] is A here; the standard
1268 // gets this backwards.
Douglas Gregor85894a82011-04-30 17:07:52 +00001269 Qualifiers ParamQuals = Param.getQualifiers();
1270 Qualifiers ArgQuals = Arg.getQualifiers();
Richard Smithed563c22015-02-20 04:45:22 +00001271 if ((ParamRef->isLValueReferenceType() &&
1272 !ArgRef->isLValueReferenceType()) ||
1273 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1274 (ParamQuals.hasNonTrivialObjCLifetime() &&
1275 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1276 ParamQuals.withoutObjCLifetime() ==
1277 ArgQuals.withoutObjCLifetime())) {
1278 Info.FirstArg = TemplateArgument(ParamIn);
1279 Info.SecondArg = TemplateArgument(ArgIn);
1280 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor6beabee2014-01-02 19:42:02 +00001281 }
Douglas Gregorb837ea42011-01-11 17:34:58 +00001282 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001283
Richard Smithed563c22015-02-20 04:45:22 +00001284 // C++11 [temp.deduct.partial]p7:
Douglas Gregorb837ea42011-01-11 17:34:58 +00001285 // Remove any top-level cv-qualifiers:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001286 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001287 // version of P.
1288 Param = Param.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001289 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
Douglas Gregorb837ea42011-01-11 17:34:58 +00001290 // version of A.
1291 Arg = Arg.getUnqualifiedType();
1292 } else {
1293 // C++0x [temp.deduct.call]p4 bullet 1:
1294 // - If the original P is a reference type, the deduced A (i.e., the type
1295 // referred to by the reference) can be more cv-qualified than the
1296 // transformed A.
1297 if (TDF & TDF_ParamWithReferenceType) {
1298 Qualifiers Quals;
1299 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1300 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
John McCall6c9dd522011-01-18 07:41:22 +00001301 Arg.getCVRQualifiers());
Douglas Gregorb837ea42011-01-11 17:34:58 +00001302 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1303 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001304
Douglas Gregor85f240c2011-01-25 17:19:08 +00001305 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1306 // C++0x [temp.deduct.type]p10:
1307 // If P and A are function types that originated from deduction when
1308 // taking the address of a function template (14.8.2.2) or when deducing
1309 // template arguments from a function declaration (14.8.2.6) and Pi and
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001310 // Ai are parameters of the top-level parameter-type-list of P and A,
Richard Smith32918772017-02-14 00:25:28 +00001311 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1312 // is an lvalue reference, in
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001313 // which case the type of Pi is changed to be the template parameter
Douglas Gregor85f240c2011-01-25 17:19:08 +00001314 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1315 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001316 // deduced as X&. - end note ]
Douglas Gregor85f240c2011-01-25 17:19:08 +00001317 TDF &= ~TDF_TopLevelParameterTypeList;
Richard Smith32918772017-02-14 00:25:28 +00001318 if (isForwardingReference(Param, 0) && Arg->isLValueReferenceType())
1319 Param = Param->getPointeeType();
Douglas Gregor85f240c2011-01-25 17:19:08 +00001320 }
Douglas Gregorcceb9752009-06-26 18:27:22 +00001321 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001322
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001323 // C++ [temp.deduct.type]p9:
Mike Stump11289f42009-09-09 15:08:12 +00001324 // A template type argument T, a template template argument TT or a
1325 // template non-type argument i can be deduced if P and A have one of
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001326 // the following forms:
1327 //
1328 // T
1329 // cv-list T
Mike Stump11289f42009-09-09 15:08:12 +00001330 if (const TemplateTypeParmType *TemplateTypeParm
John McCall9dd450b2009-09-21 23:43:11 +00001331 = Param->getAs<TemplateTypeParmType>()) {
Richard Smith87d263e2016-12-25 08:05:23 +00001332 // Just skip any attempts to deduce from a placeholder type or a parameter
1333 // at a different depth.
1334 if (Arg->isPlaceholderType() ||
1335 Info.getDeducedDepth() != TemplateTypeParm->getDepth())
Douglas Gregor4ea5dec2011-09-22 15:57:07 +00001336 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001337
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001338 unsigned Index = TemplateTypeParm->getIndex();
Douglas Gregord6605db2009-07-22 21:30:48 +00001339 bool RecanonicalizeArg = false;
Mike Stump11289f42009-09-09 15:08:12 +00001340
Douglas Gregor60454822009-07-22 20:02:25 +00001341 // If the argument type is an array type, move the qualifiers up to the
1342 // top level, so they can be matched with the qualifiers on the parameter.
Douglas Gregord6605db2009-07-22 21:30:48 +00001343 if (isa<ArrayType>(Arg)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001344 Qualifiers Quals;
Chandler Carruthc1263112010-02-07 21:33:28 +00001345 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
John McCall8ccfcb52009-09-24 19:53:00 +00001346 if (Quals) {
Chandler Carruthc1263112010-02-07 21:33:28 +00001347 Arg = S.Context.getQualifiedType(Arg, Quals);
Douglas Gregord6605db2009-07-22 21:30:48 +00001348 RecanonicalizeArg = true;
1349 }
1350 }
Mike Stump11289f42009-09-09 15:08:12 +00001351
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001352 // The argument type can not be less qualified than the parameter
1353 // type.
Douglas Gregor1d684c22011-04-28 00:56:09 +00001354 if (!(TDF & TDF_IgnoreQualifiers) &&
1355 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001356 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
John McCall42d7d192010-08-05 09:05:08 +00001357 Info.FirstArg = TemplateArgument(Param);
John McCall0ad16662009-10-29 08:12:44 +00001358 Info.SecondArg = TemplateArgument(Arg);
John McCall42d7d192010-08-05 09:05:08 +00001359 return Sema::TDK_Underqualified;
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001360 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001361
Lei Liu413f3c52018-05-03 01:43:23 +00001362 // Do not match a function type with a cv-qualified type.
1363 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
1364 if (Arg->isFunctionType() && Param.hasQualifiers()) {
1365 return Sema::TDK_NonDeducedMismatch;
1366 }
1367
Richard Smith87d263e2016-12-25 08:05:23 +00001368 assert(TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&
1369 "saw template type parameter with wrong depth");
Chandler Carruthc1263112010-02-07 21:33:28 +00001370 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
John McCall8ccfcb52009-09-24 19:53:00 +00001371 QualType DeducedType = Arg;
John McCall717d9b02010-12-10 11:01:00 +00001372
Douglas Gregor1d684c22011-04-28 00:56:09 +00001373 // Remove any qualifiers on the parameter from the deduced type.
1374 // We checked the qualifiers for consistency above.
1375 Qualifiers DeducedQs = DeducedType.getQualifiers();
1376 Qualifiers ParamQs = Param.getQualifiers();
1377 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1378 if (ParamQs.hasObjCGCAttr())
1379 DeducedQs.removeObjCGCAttr();
1380 if (ParamQs.hasAddressSpace())
1381 DeducedQs.removeAddressSpace();
John McCall31168b02011-06-15 23:02:42 +00001382 if (ParamQs.hasObjCLifetime())
1383 DeducedQs.removeObjCLifetime();
Simon Pilgrim728134c2016-08-12 11:43:57 +00001384
Douglas Gregore46db902011-06-17 22:11:49 +00001385 // Objective-C ARC:
Douglas Gregora4f2b432011-07-26 14:53:44 +00001386 // If template deduction would produce a lifetime qualifier on a type
1387 // that is not a lifetime type, template argument deduction fails.
1388 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1389 !DeducedType->isDependentType()) {
1390 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1391 Info.FirstArg = TemplateArgument(Param);
1392 Info.SecondArg = TemplateArgument(Arg);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001393 return Sema::TDK_Underqualified;
Douglas Gregora4f2b432011-07-26 14:53:44 +00001394 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001395
Douglas Gregora4f2b432011-07-26 14:53:44 +00001396 // Objective-C ARC:
Douglas Gregore46db902011-06-17 22:11:49 +00001397 // If template deduction would produce an argument type with lifetime type
1398 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001399 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregore46db902011-06-17 22:11:49 +00001400 DeducedType->isObjCLifetimeType() &&
1401 !DeducedQs.hasObjCLifetime())
1402 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001403
Douglas Gregor1d684c22011-04-28 00:56:09 +00001404 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1405 DeducedQs);
Simon Pilgrim728134c2016-08-12 11:43:57 +00001406
Douglas Gregord6605db2009-07-22 21:30:48 +00001407 if (RecanonicalizeArg)
Chandler Carruthc1263112010-02-07 21:33:28 +00001408 DeducedType = S.Context.getCanonicalType(DeducedType);
Mike Stump11289f42009-09-09 15:08:12 +00001409
Richard Smith5f274382016-09-28 23:55:27 +00001410 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001411 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001412 Deduced[Index],
1413 NewDeduced);
1414 if (Result.isNull()) {
1415 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1416 Info.FirstArg = Deduced[Index];
1417 Info.SecondArg = NewDeduced;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001418 return Sema::TDK_Inconsistent;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001419 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001420
Douglas Gregor7f8e7682010-12-22 23:09:49 +00001421 Deduced[Index] = Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001422 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001423 }
1424
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001425 // Set up the template argument deduction information for a failure.
John McCall0ad16662009-10-29 08:12:44 +00001426 Info.FirstArg = TemplateArgument(ParamIn);
1427 Info.SecondArg = TemplateArgument(ArgIn);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001428
Douglas Gregorfb322d82011-01-14 05:11:40 +00001429 // If the parameter is an already-substituted template parameter
1430 // pack, do nothing: we don't know which of its arguments to look
1431 // at, so we have to wait until all of the parameter packs in this
1432 // expansion have arguments.
1433 if (isa<SubstTemplateTypeParmPackType>(Param))
1434 return Sema::TDK_Success;
1435
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001436 // Check the cv-qualifiers on the parameter and argument types.
Douglas Gregor19a41f12013-04-17 08:45:07 +00001437 CanQualType CanParam = S.Context.getCanonicalType(Param);
1438 CanQualType CanArg = S.Context.getCanonicalType(Arg);
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001439 if (!(TDF & TDF_IgnoreQualifiers)) {
1440 if (TDF & TDF_ParamWithReferenceType) {
Douglas Gregor1d684c22011-04-28 00:56:09 +00001441 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001442 return Sema::TDK_NonDeducedMismatch;
Richard Smithb884ed12018-07-11 23:19:41 +00001443 } else if (TDF & TDF_ArgWithReferenceType) {
1444 // C++ [temp.deduct.conv]p4:
1445 // If the original A is a reference type, A can be more cv-qualified
1446 // than the deduced A
1447 if (!Arg.getQualifiers().compatiblyIncludes(Param.getQualifiers()))
1448 return Sema::TDK_NonDeducedMismatch;
1449
1450 // Strip out all extra qualifiers from the argument to figure out the
1451 // type we're converting to, prior to the qualification conversion.
1452 Qualifiers Quals;
1453 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
1454 Arg = S.Context.getQualifiedType(Arg, Param.getQualifiers());
John McCall08569062010-08-28 22:14:41 +00001455 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001456 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
Mike Stump11289f42009-09-09 15:08:12 +00001457 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001458 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001459
Douglas Gregor194ea692012-03-11 03:29:50 +00001460 // If the parameter type is not dependent, there is nothing to deduce.
1461 if (!Param->isDependentType()) {
Douglas Gregor19a41f12013-04-17 08:45:07 +00001462 if (!(TDF & TDF_SkipNonDependent)) {
Richard Smithcd198152017-06-07 21:46:22 +00001463 bool NonDeduced =
1464 (TDF & TDF_AllowCompatibleFunctionType)
1465 ? !S.isSameOrCompatibleFunctionType(CanParam, CanArg)
1466 : Param != Arg;
Douglas Gregor19a41f12013-04-17 08:45:07 +00001467 if (NonDeduced) {
1468 return Sema::TDK_NonDeducedMismatch;
1469 }
1470 }
Douglas Gregor194ea692012-03-11 03:29:50 +00001471 return Sema::TDK_Success;
1472 }
Douglas Gregor19a41f12013-04-17 08:45:07 +00001473 } else if (!Param->isDependentType()) {
1474 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1475 ArgUnqualType = CanArg.getUnqualifiedType();
Richard Smithcd198152017-06-07 21:46:22 +00001476 bool Success =
1477 (TDF & TDF_AllowCompatibleFunctionType)
1478 ? S.isSameOrCompatibleFunctionType(ParamUnqualType, ArgUnqualType)
1479 : ParamUnqualType == ArgUnqualType;
Douglas Gregor19a41f12013-04-17 08:45:07 +00001480 if (Success)
1481 return Sema::TDK_Success;
Douglas Gregorcf0b47d2009-06-26 23:10:12 +00001482 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001483
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001484 switch (Param->getTypeClass()) {
Douglas Gregor39c02722011-06-15 16:02:29 +00001485 // Non-canonical types cannot appear here.
1486#define NON_CANONICAL_TYPE(Class, Base) \
1487 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1488#define TYPE(Class, Base)
1489#include "clang/AST/TypeNodes.def"
Simon Pilgrim728134c2016-08-12 11:43:57 +00001490
Douglas Gregor39c02722011-06-15 16:02:29 +00001491 case Type::TemplateTypeParm:
1492 case Type::SubstTemplateTypeParmPack:
1493 llvm_unreachable("Type nodes handled above");
Douglas Gregor194ea692012-03-11 03:29:50 +00001494
1495 // These types cannot be dependent, so simply check whether the types are
1496 // the same.
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001497 case Type::Builtin:
Douglas Gregor39c02722011-06-15 16:02:29 +00001498 case Type::VariableArray:
1499 case Type::Vector:
1500 case Type::FunctionNoProto:
1501 case Type::Record:
1502 case Type::Enum:
1503 case Type::ObjCObject:
1504 case Type::ObjCInterface:
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00001505 case Type::ObjCObjectPointer:
Douglas Gregor194ea692012-03-11 03:29:50 +00001506 if (TDF & TDF_SkipNonDependent)
1507 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001508
Douglas Gregor194ea692012-03-11 03:29:50 +00001509 if (TDF & TDF_IgnoreQualifiers) {
1510 Param = Param.getUnqualifiedType();
1511 Arg = Arg.getUnqualifiedType();
1512 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001513
Douglas Gregor194ea692012-03-11 03:29:50 +00001514 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001515
1516 // _Complex T [placeholder extension]
Douglas Gregor39c02722011-06-15 16:02:29 +00001517 case Type::Complex:
1518 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
Simon Pilgrim728134c2016-08-12 11:43:57 +00001519 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1520 cast<ComplexType>(Param)->getElementType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001521 ComplexArg->getElementType(),
1522 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001523
1524 return Sema::TDK_NonDeducedMismatch;
Eli Friedman0dfb8892011-10-06 23:00:33 +00001525
1526 // _Atomic T [extension]
1527 case Type::Atomic:
1528 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001529 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Eli Friedman0dfb8892011-10-06 23:00:33 +00001530 cast<AtomicType>(Param)->getValueType(),
1531 AtomicArg->getValueType(),
1532 Info, Deduced, TDF);
1533
1534 return Sema::TDK_NonDeducedMismatch;
1535
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001536 // T *
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001537 case Type::Pointer: {
John McCallbb4ea812010-05-13 07:48:05 +00001538 QualType PointeeType;
1539 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1540 PointeeType = PointerArg->getPointeeType();
1541 } else if (const ObjCObjectPointerType *PointerArg
1542 = Arg->getAs<ObjCObjectPointerType>()) {
1543 PointeeType = PointerArg->getPointeeType();
1544 } else {
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001545 return Sema::TDK_NonDeducedMismatch;
John McCallbb4ea812010-05-13 07:48:05 +00001546 }
Mike Stump11289f42009-09-09 15:08:12 +00001547
Douglas Gregorfc516c92009-06-26 23:27:24 +00001548 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001549 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1550 cast<PointerType>(Param)->getPointeeType(),
John McCallbb4ea812010-05-13 07:48:05 +00001551 PointeeType,
Douglas Gregorfc516c92009-06-26 23:27:24 +00001552 Info, Deduced, SubTDF);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001553 }
Mike Stump11289f42009-09-09 15:08:12 +00001554
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001555 // T &
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001556 case Type::LValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001557 const LValueReferenceType *ReferenceArg =
1558 Arg->getAs<LValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001559 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001560 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001561
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001562 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001563 cast<LValueReferenceType>(Param)->getPointeeType(),
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001564 ReferenceArg->getPointeeType(), Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001565 }
Douglas Gregor55ca8f62009-06-04 00:03:07 +00001566
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001567 // T && [C++0x]
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001568 case Type::RValueReference: {
Nico Weberc153d242014-07-28 00:02:09 +00001569 const RValueReferenceType *ReferenceArg =
1570 Arg->getAs<RValueReferenceType>();
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001571 if (!ReferenceArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001572 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001573
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001574 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1575 cast<RValueReferenceType>(Param)->getPointeeType(),
1576 ReferenceArg->getPointeeType(),
1577 Info, Deduced, 0);
Douglas Gregor5cdac0a2009-06-04 00:21:18 +00001578 }
Mike Stump11289f42009-09-09 15:08:12 +00001579
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001580 // T [] (implied, but not stated explicitly)
Anders Carlsson35533d12009-06-04 04:11:30 +00001581 case Type::IncompleteArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001582 const IncompleteArrayType *IncompleteArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001583 S.Context.getAsIncompleteArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001584 if (!IncompleteArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001585 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001586
John McCallf7332682010-08-19 00:20:19 +00001587 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001588 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1589 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1590 IncompleteArrayArg->getElementType(),
1591 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001592 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001593
1594 // T [integer-constant]
Anders Carlsson35533d12009-06-04 04:11:30 +00001595 case Type::ConstantArray: {
Mike Stump11289f42009-09-09 15:08:12 +00001596 const ConstantArrayType *ConstantArrayArg =
Chandler Carruthc1263112010-02-07 21:33:28 +00001597 S.Context.getAsConstantArrayType(Arg);
Anders Carlsson35533d12009-06-04 04:11:30 +00001598 if (!ConstantArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001599 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001600
1601 const ConstantArrayType *ConstantArrayParm =
Chandler Carruthc1263112010-02-07 21:33:28 +00001602 S.Context.getAsConstantArrayType(Param);
Anders Carlsson35533d12009-06-04 04:11:30 +00001603 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001604 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001605
John McCallf7332682010-08-19 00:20:19 +00001606 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001607 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1608 ConstantArrayParm->getElementType(),
1609 ConstantArrayArg->getElementType(),
1610 Info, Deduced, SubTDF);
Anders Carlsson35533d12009-06-04 04:11:30 +00001611 }
1612
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001613 // type [i]
1614 case Type::DependentSizedArray: {
Chandler Carruthc1263112010-02-07 21:33:28 +00001615 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001616 if (!ArrayArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001617 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001618
John McCallf7332682010-08-19 00:20:19 +00001619 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1620
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001621 // Check the element type of the arrays
1622 const DependentSizedArrayType *DependentArrayParm
Chandler Carruthc1263112010-02-07 21:33:28 +00001623 = S.Context.getAsDependentSizedArrayType(Param);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001624 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001625 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1626 DependentArrayParm->getElementType(),
1627 ArrayArg->getElementType(),
1628 Info, Deduced, SubTDF))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001629 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001630
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001631 // Determine the array bound is something we can deduce.
Mike Stump11289f42009-09-09 15:08:12 +00001632 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00001633 = getDeducedParameterFromExpr(Info, DependentArrayParm->getSizeExpr());
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001634 if (!NTTP)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001635 return Sema::TDK_Success;
Mike Stump11289f42009-09-09 15:08:12 +00001636
1637 // We can perform template argument deduction for the given non-type
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001638 // template parameter.
Richard Smith87d263e2016-12-25 08:05:23 +00001639 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1640 "saw non-type template parameter with wrong depth");
Mike Stump11289f42009-09-09 15:08:12 +00001641 if (const ConstantArrayType *ConstantArrayArg
Anders Carlsson3a106e02009-06-16 22:44:31 +00001642 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1643 llvm::APSInt Size(ConstantArrayArg->getSize());
Richard Smith5f274382016-09-28 23:55:27 +00001644 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
Douglas Gregor0a29a052010-03-26 05:50:28 +00001645 S.Context.getSizeType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00001646 /*ArrayBound=*/true,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001647 Info, Deduced);
Anders Carlsson3a106e02009-06-16 22:44:31 +00001648 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001649 if (const DependentSizedArrayType *DependentArrayArg
1650 = dyn_cast<DependentSizedArrayType>(ArrayArg))
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001651 if (DependentArrayArg->getSizeExpr())
Richard Smith5f274382016-09-28 23:55:27 +00001652 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Douglas Gregor7a49ead2010-12-22 23:15:38 +00001653 DependentArrayArg->getSizeExpr(),
1654 Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001655
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001656 // Incomplete type does not match a dependently-sized array type
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001657 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00001658 }
Mike Stump11289f42009-09-09 15:08:12 +00001659
1660 // type(*)(T)
1661 // T(*)()
1662 // T(*)(T)
Anders Carlsson2128ec72009-06-08 15:19:08 +00001663 case Type::FunctionProto: {
Douglas Gregor85f240c2011-01-25 17:19:08 +00001664 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
Mike Stump11289f42009-09-09 15:08:12 +00001665 const FunctionProtoType *FunctionProtoArg =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001666 dyn_cast<FunctionProtoType>(Arg);
1667 if (!FunctionProtoArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001668 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001669
1670 const FunctionProtoType *FunctionProtoParam =
Anders Carlsson2128ec72009-06-08 15:19:08 +00001671 cast<FunctionProtoType>(Param);
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001672
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001673 if (FunctionProtoParam->getTypeQuals()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001674 != FunctionProtoArg->getTypeQuals() ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001675 FunctionProtoParam->getRefQualifier()
Douglas Gregor54e462a2011-01-26 16:50:54 +00001676 != FunctionProtoArg->getRefQualifier() ||
1677 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001678 return Sema::TDK_NonDeducedMismatch;
Anders Carlsson096e6ee2009-06-08 19:22:23 +00001679
Anders Carlsson2128ec72009-06-08 15:19:08 +00001680 // Check return types.
Richard Smithcd198152017-06-07 21:46:22 +00001681 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
1682 S, TemplateParams, FunctionProtoParam->getReturnType(),
1683 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001684 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001685
Richard Smithcd198152017-06-07 21:46:22 +00001686 // Check parameter types.
1687 if (auto Result = DeduceTemplateArguments(
1688 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1689 FunctionProtoParam->getNumParams(),
1690 FunctionProtoArg->param_type_begin(),
1691 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF))
1692 return Result;
1693
1694 if (TDF & TDF_AllowCompatibleFunctionType)
1695 return Sema::TDK_Success;
1696
1697 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
1698 // deducing through the noexcept-specifier if it's part of the canonical
1699 // type. libstdc++ relies on this.
1700 Expr *NoexceptExpr = FunctionProtoParam->getNoexceptExpr();
1701 if (NonTypeTemplateParmDecl *NTTP =
1702 NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr)
1703 : nullptr) {
1704 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1705 "saw non-type template parameter with wrong depth");
1706
1707 llvm::APSInt Noexcept(1);
Richard Smitheaf11ad2018-05-03 03:58:32 +00001708 switch (FunctionProtoArg->canThrow()) {
Richard Smithcd198152017-06-07 21:46:22 +00001709 case CT_Cannot:
1710 Noexcept = 1;
1711 LLVM_FALLTHROUGH;
1712
1713 case CT_Can:
1714 // We give E in noexcept(E) the "deduced from array bound" treatment.
1715 // FIXME: Should we?
1716 return DeduceNonTypeTemplateArgument(
1717 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
1718 /*ArrayBound*/true, Info, Deduced);
1719
1720 case CT_Dependent:
1721 if (Expr *ArgNoexceptExpr = FunctionProtoArg->getNoexceptExpr())
1722 return DeduceNonTypeTemplateArgument(
1723 S, TemplateParams, NTTP, ArgNoexceptExpr, Info, Deduced);
1724 // Can't deduce anything from throw(T...).
1725 break;
1726 }
1727 }
1728 // FIXME: Detect non-deduced exception specification mismatches?
Richard Smith746e35e2018-07-12 18:49:13 +00001729 //
1730 // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
1731 // top-level differences in noexcept-specifications.
Richard Smithcd198152017-06-07 21:46:22 +00001732
1733 return Sema::TDK_Success;
Anders Carlsson2128ec72009-06-08 15:19:08 +00001734 }
Mike Stump11289f42009-09-09 15:08:12 +00001735
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00001736 case Type::InjectedClassName:
John McCalle78aac42010-03-10 03:28:59 +00001737 // Treat a template's injected-class-name as if the template
1738 // specialization type had been used.
John McCall2408e322010-04-27 00:57:59 +00001739 Param = cast<InjectedClassNameType>(Param)
1740 ->getInjectedSpecializationType();
John McCalle78aac42010-03-10 03:28:59 +00001741 assert(isa<TemplateSpecializationType>(Param) &&
1742 "injected class name is not a template specialization type");
Richard Smithcd198152017-06-07 21:46:22 +00001743 LLVM_FALLTHROUGH;
John McCalle78aac42010-03-10 03:28:59 +00001744
Douglas Gregor705c9002009-06-26 20:57:09 +00001745 // template-name<T> (where template-name refers to a class template)
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001746 // template-name<i>
Douglas Gregoradee3e32009-11-11 23:06:43 +00001747 // TT<T>
1748 // TT<i>
1749 // TT<>
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001750 case Type::TemplateSpecialization: {
Richard Smith9b296e32016-04-25 19:09:05 +00001751 const TemplateSpecializationType *SpecParam =
1752 cast<TemplateSpecializationType>(Param);
Mike Stump11289f42009-09-09 15:08:12 +00001753
Richard Smith9b296e32016-04-25 19:09:05 +00001754 // When Arg cannot be a derived class, we can just try to deduce template
1755 // arguments from the template-id.
1756 const RecordType *RecordT = Arg->getAs<RecordType>();
1757 if (!(TDF & TDF_DerivedClass) || !RecordT)
1758 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1759 Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001760
Richard Smith9b296e32016-04-25 19:09:05 +00001761 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1762 Deduced.end());
Chandler Carruthc1263112010-02-07 21:33:28 +00001763
Richard Smith9b296e32016-04-25 19:09:05 +00001764 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1765 S, TemplateParams, SpecParam, Arg, Info, Deduced);
Mike Stump11289f42009-09-09 15:08:12 +00001766
Richard Smith9b296e32016-04-25 19:09:05 +00001767 if (Result == Sema::TDK_Success)
1768 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001769
Richard Smith9b296e32016-04-25 19:09:05 +00001770 // We cannot inspect base classes as part of deduction when the type
1771 // is incomplete, so either instantiate any templates necessary to
1772 // complete the type, or skip over it if it cannot be completed.
1773 if (!S.isCompleteType(Info.getLocation(), Arg))
1774 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001775
Richard Smith9b296e32016-04-25 19:09:05 +00001776 // C++14 [temp.deduct.call] p4b3:
1777 // If P is a class and P has the form simple-template-id, then the
1778 // transformed A can be a derived class of the deduced A. Likewise if
1779 // P is a pointer to a class of the form simple-template-id, the
1780 // transformed A can be a pointer to a derived class pointed to by the
1781 // deduced A.
1782 //
1783 // These alternatives are considered only if type deduction would
1784 // otherwise fail. If they yield more than one possible deduced A, the
1785 // type deduction fails.
Mike Stump11289f42009-09-09 15:08:12 +00001786
Faisal Vali683b0742016-05-19 02:28:21 +00001787 // Reset the incorrectly deduced argument from above.
1788 Deduced = DeducedOrig;
1789
1790 // Use data recursion to crawl through the list of base classes.
1791 // Visited contains the set of nodes we have already visited, while
1792 // ToVisit is our stack of records that we still need to visit.
1793 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1794 SmallVector<const RecordType *, 8> ToVisit;
1795 ToVisit.push_back(RecordT);
Richard Smith9b296e32016-04-25 19:09:05 +00001796 bool Successful = false;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001797 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
Faisal Vali683b0742016-05-19 02:28:21 +00001798 while (!ToVisit.empty()) {
1799 // Retrieve the next class in the inheritance hierarchy.
1800 const RecordType *NextT = ToVisit.pop_back_val();
Richard Smith9b296e32016-04-25 19:09:05 +00001801
Faisal Vali683b0742016-05-19 02:28:21 +00001802 // If we have already seen this type, skip it.
1803 if (!Visited.insert(NextT).second)
1804 continue;
Richard Smith9b296e32016-04-25 19:09:05 +00001805
Faisal Vali683b0742016-05-19 02:28:21 +00001806 // If this is a base class, try to perform template argument
1807 // deduction from it.
1808 if (NextT != RecordT) {
1809 TemplateDeductionInfo BaseInfo(Info.getLocation());
1810 Sema::TemplateDeductionResult BaseResult =
1811 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1812 QualType(NextT, 0), BaseInfo, Deduced);
1813
1814 // If template argument deduction for this base was successful,
1815 // note that we had some success. Otherwise, ignore any deductions
1816 // from this base class.
1817 if (BaseResult == Sema::TDK_Success) {
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001818 // If we've already seen some success, then deduction fails due to
1819 // an ambiguity (temp.deduct.call p5).
1820 if (Successful)
1821 return Sema::TDK_MiscellaneousDeductionFailure;
1822
Faisal Vali683b0742016-05-19 02:28:21 +00001823 Successful = true;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001824 std::swap(SuccessfulDeduced, Deduced);
1825
Faisal Vali683b0742016-05-19 02:28:21 +00001826 Info.Param = BaseInfo.Param;
1827 Info.FirstArg = BaseInfo.FirstArg;
1828 Info.SecondArg = BaseInfo.SecondArg;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001829 }
1830
1831 Deduced = DeducedOrig;
Douglas Gregore81f3e72009-07-07 23:09:34 +00001832 }
Mike Stump11289f42009-09-09 15:08:12 +00001833
Faisal Vali683b0742016-05-19 02:28:21 +00001834 // Visit base classes
1835 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1836 for (const auto &Base : Next->bases()) {
1837 assert(Base.getType()->isRecordType() &&
1838 "Base class that isn't a record?");
1839 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1840 }
1841 }
Mike Stump11289f42009-09-09 15:08:12 +00001842
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001843 if (Successful) {
1844 std::swap(SuccessfulDeduced, Deduced);
Richard Smith9b296e32016-04-25 19:09:05 +00001845 return Sema::TDK_Success;
Erik Pilkington6a16ac02016-06-28 23:05:09 +00001846 }
Richard Smith9b296e32016-04-25 19:09:05 +00001847
Douglas Gregore81f3e72009-07-07 23:09:34 +00001848 return Result;
Douglas Gregor4fbe3e32009-06-09 16:35:58 +00001849 }
1850
Douglas Gregor637d9982009-06-10 23:47:09 +00001851 // T type::*
1852 // T T::*
1853 // T (type::*)()
1854 // type (T::*)()
1855 // type (type::*)(T)
1856 // type (T::*)(T)
1857 // T (type::*)(T)
1858 // T (T::*)()
1859 // T (T::*)(T)
1860 case Type::MemberPointer: {
1861 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1862 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1863 if (!MemPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001864 return Sema::TDK_NonDeducedMismatch;
Douglas Gregor637d9982009-06-10 23:47:09 +00001865
David Majnemera381cda2015-11-30 20:34:28 +00001866 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1867 if (ParamPointeeType->isFunctionType())
1868 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1869 /*IsCtorOrDtor=*/false, Info.getLocation());
1870 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1871 if (ArgPointeeType->isFunctionType())
1872 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1873 /*IsCtorOrDtor=*/false, Info.getLocation());
1874
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001875 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001876 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
David Majnemera381cda2015-11-30 20:34:28 +00001877 ParamPointeeType,
1878 ArgPointeeType,
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001879 Info, Deduced,
1880 TDF & TDF_IgnoreQualifiers))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001881 return Result;
1882
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001883 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1884 QualType(MemPtrParam->getClass(), 0),
1885 QualType(MemPtrArg->getClass(), 0),
Simon Pilgrim728134c2016-08-12 11:43:57 +00001886 Info, Deduced,
Douglas Gregor194ea692012-03-11 03:29:50 +00001887 TDF & TDF_IgnoreQualifiers);
Douglas Gregor637d9982009-06-10 23:47:09 +00001888 }
1889
Anders Carlsson15f1dd12009-06-12 22:56:54 +00001890 // (clang extension)
1891 //
Mike Stump11289f42009-09-09 15:08:12 +00001892 // type(^)(T)
1893 // T(^)()
1894 // T(^)(T)
Anders Carlssona767eee2009-06-12 16:23:10 +00001895 case Type::BlockPointer: {
1896 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1897 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
Mike Stump11289f42009-09-09 15:08:12 +00001898
Anders Carlssona767eee2009-06-12 16:23:10 +00001899 if (!BlockPtrArg)
Douglas Gregor181aa4a2009-06-12 18:26:56 +00001900 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00001901
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001902 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1903 BlockPtrParam->getPointeeType(),
1904 BlockPtrArg->getPointeeType(),
1905 Info, Deduced, 0);
Anders Carlssona767eee2009-06-12 16:23:10 +00001906 }
1907
Douglas Gregor39c02722011-06-15 16:02:29 +00001908 // (clang extension)
1909 //
1910 // T __attribute__(((ext_vector_type(<integral constant>))))
1911 case Type::ExtVector: {
1912 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1913 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1914 // Make sure that the vectors have the same number of elements.
1915 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1916 return Sema::TDK_NonDeducedMismatch;
Simon Pilgrim728134c2016-08-12 11:43:57 +00001917
Douglas Gregor39c02722011-06-15 16:02:29 +00001918 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001919 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1920 VectorParam->getElementType(),
1921 VectorArg->getElementType(),
1922 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001923 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001924
1925 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00001926 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1927 // We can't check the number of elements, since the argument has a
1928 // dependent number of elements. This can only occur during partial
1929 // ordering.
1930
1931 // Perform deduction on the element types.
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001932 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1933 VectorParam->getElementType(),
1934 VectorArg->getElementType(),
1935 Info, Deduced, TDF);
Douglas Gregor39c02722011-06-15 16:02:29 +00001936 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001937
Douglas Gregor39c02722011-06-15 16:02:29 +00001938 return Sema::TDK_NonDeducedMismatch;
1939 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00001940
Erich Keanef702b022018-07-13 19:46:04 +00001941 case Type::DependentVector: {
1942 const auto *VectorParam = cast<DependentVectorType>(Param);
1943
1944 if (const auto *VectorArg = dyn_cast<VectorType>(Arg)) {
1945 // Perform deduction on the element types.
1946 if (Sema::TemplateDeductionResult Result =
1947 DeduceTemplateArgumentsByTypeMatch(
1948 S, TemplateParams, VectorParam->getElementType(),
1949 VectorArg->getElementType(), Info, Deduced, TDF))
1950 return Result;
1951
1952 // Perform deduction on the vector size, if we can.
1953 NonTypeTemplateParmDecl *NTTP =
1954 getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
1955 if (!NTTP)
1956 return Sema::TDK_Success;
1957
1958 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1959 ArgSize = VectorArg->getNumElements();
1960 // Note that we use the "array bound" rules here; just like in that
1961 // case, we don't have any particular type for the vector size, but
1962 // we can provide one if necessary.
1963 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
1964 S.Context.UnsignedIntTy, true,
1965 Info, Deduced);
1966 }
1967
1968 if (const auto *VectorArg = dyn_cast<DependentVectorType>(Arg)) {
1969 // Perform deduction on the element types.
1970 if (Sema::TemplateDeductionResult Result =
1971 DeduceTemplateArgumentsByTypeMatch(
1972 S, TemplateParams, VectorParam->getElementType(),
1973 VectorArg->getElementType(), Info, Deduced, TDF))
1974 return Result;
1975
1976 // Perform deduction on the vector size, if we can.
1977 NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
1978 Info, VectorParam->getSizeExpr());
1979 if (!NTTP)
1980 return Sema::TDK_Success;
1981
1982 return DeduceNonTypeTemplateArgument(
1983 S, TemplateParams, NTTP, VectorArg->getSizeExpr(), Info, Deduced);
1984 }
1985
1986 return Sema::TDK_NonDeducedMismatch;
1987 }
1988
Douglas Gregor39c02722011-06-15 16:02:29 +00001989 // (clang extension)
1990 //
1991 // T __attribute__(((ext_vector_type(N))))
1992 case Type::DependentSizedExtVector: {
1993 const DependentSizedExtVectorType *VectorParam
1994 = cast<DependentSizedExtVectorType>(Param);
1995
1996 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1997 // Perform deduction on the element types.
1998 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00001999 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
2000 VectorParam->getElementType(),
2001 VectorArg->getElementType(),
2002 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00002003 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002004
Douglas Gregor39c02722011-06-15 16:02:29 +00002005 // Perform deduction on the vector size, if we can.
2006 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00002007 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00002008 if (!NTTP)
2009 return Sema::TDK_Success;
2010
2011 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2012 ArgSize = VectorArg->getNumElements();
Richard Smith87d263e2016-12-25 08:05:23 +00002013 // Note that we use the "array bound" rules here; just like in that
2014 // case, we don't have any particular type for the vector size, but
2015 // we can provide one if necessary.
Richard Smith5f274382016-09-28 23:55:27 +00002016 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
Richard Smith87d263e2016-12-25 08:05:23 +00002017 S.Context.IntTy, true, Info,
Richard Smith593d6a12016-12-23 01:30:39 +00002018 Deduced);
Douglas Gregor39c02722011-06-15 16:02:29 +00002019 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002020
2021 if (const DependentSizedExtVectorType *VectorArg
Douglas Gregor39c02722011-06-15 16:02:29 +00002022 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
2023 // Perform deduction on the element types.
2024 if (Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00002025 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
2026 VectorParam->getElementType(),
2027 VectorArg->getElementType(),
2028 Info, Deduced, TDF))
Douglas Gregor39c02722011-06-15 16:02:29 +00002029 return Result;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002030
Douglas Gregor39c02722011-06-15 16:02:29 +00002031 // Perform deduction on the vector size, if we can.
2032 NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00002033 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
Douglas Gregor39c02722011-06-15 16:02:29 +00002034 if (!NTTP)
2035 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00002036
Richard Smith5f274382016-09-28 23:55:27 +00002037 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2038 VectorArg->getSizeExpr(),
Douglas Gregor39c02722011-06-15 16:02:29 +00002039 Info, Deduced);
2040 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002041
Douglas Gregor39c02722011-06-15 16:02:29 +00002042 return Sema::TDK_NonDeducedMismatch;
2043 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00002044
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002045 // (clang extension)
2046 //
2047 // T __attribute__(((address_space(N))))
2048 case Type::DependentAddressSpace: {
2049 const DependentAddressSpaceType *AddressSpaceParam =
2050 cast<DependentAddressSpaceType>(Param);
2051
2052 if (const DependentAddressSpaceType *AddressSpaceArg =
2053 dyn_cast<DependentAddressSpaceType>(Arg)) {
2054 // Perform deduction on the pointer type.
2055 if (Sema::TemplateDeductionResult Result =
2056 DeduceTemplateArgumentsByTypeMatch(
2057 S, TemplateParams, AddressSpaceParam->getPointeeType(),
2058 AddressSpaceArg->getPointeeType(), Info, Deduced, TDF))
2059 return Result;
2060
2061 // Perform deduction on the address space, if we can.
2062 NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
2063 Info, AddressSpaceParam->getAddrSpaceExpr());
2064 if (!NTTP)
2065 return Sema::TDK_Success;
2066
2067 return DeduceNonTypeTemplateArgument(
2068 S, TemplateParams, NTTP, AddressSpaceArg->getAddrSpaceExpr(), Info,
2069 Deduced);
2070 }
2071
Alexander Richardson6d989432017-10-15 18:48:14 +00002072 if (isTargetAddressSpace(Arg.getAddressSpace())) {
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002073 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
2074 false);
Alexander Richardson6d989432017-10-15 18:48:14 +00002075 ArgAddressSpace = toTargetAddressSpace(Arg.getAddressSpace());
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002076
2077 // Perform deduction on the pointer types.
2078 if (Sema::TemplateDeductionResult Result =
2079 DeduceTemplateArgumentsByTypeMatch(
2080 S, TemplateParams, AddressSpaceParam->getPointeeType(),
2081 S.Context.removeAddrSpaceQualType(Arg), Info, Deduced, TDF))
2082 return Result;
2083
2084 // Perform deduction on the address space, if we can.
2085 NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
2086 Info, AddressSpaceParam->getAddrSpaceExpr());
2087 if (!NTTP)
2088 return Sema::TDK_Success;
2089
2090 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2091 ArgAddressSpace, S.Context.IntTy,
2092 true, Info, Deduced);
2093 }
2094
2095 return Sema::TDK_NonDeducedMismatch;
2096 }
2097
Douglas Gregor637d9982009-06-10 23:47:09 +00002098 case Type::TypeOfExpr:
2099 case Type::TypeOf:
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00002100 case Type::DependentName:
Douglas Gregor39c02722011-06-15 16:02:29 +00002101 case Type::UnresolvedUsing:
2102 case Type::Decltype:
2103 case Type::UnaryTransform:
2104 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00002105 case Type::DeducedTemplateSpecialization:
Douglas Gregor39c02722011-06-15 16:02:29 +00002106 case Type::DependentTemplateSpecialization:
2107 case Type::PackExpansion:
Xiuli Pan9c14e282016-01-09 12:53:17 +00002108 case Type::Pipe:
Douglas Gregor637d9982009-06-10 23:47:09 +00002109 // No template argument deduction for these types
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002110 return Sema::TDK_Success;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002111 }
2112
David Blaikiee4d798f2012-01-20 21:50:17 +00002113 llvm_unreachable("Invalid Type Class!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002114}
2115
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002116static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00002117DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002118 TemplateParameterList *TemplateParams,
2119 const TemplateArgument &Param,
Douglas Gregor2fcb8632011-01-11 22:21:24 +00002120 TemplateArgument Arg,
John McCall19c1bfd2010-08-25 05:32:35 +00002121 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00002122 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Douglas Gregor2fcb8632011-01-11 22:21:24 +00002123 // If the template argument is a pack expansion, perform template argument
2124 // deduction against the pattern of that expansion. This only occurs during
2125 // partial ordering.
2126 if (Arg.isPackExpansion())
2127 Arg = Arg.getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002128
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002129 switch (Param.getKind()) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002130 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00002131 llvm_unreachable("Null template argument in parameter list");
Mike Stump11289f42009-09-09 15:08:12 +00002132
2133 case TemplateArgument::Type:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002134 if (Arg.getKind() == TemplateArgument::Type)
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00002135 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
2136 Param.getAsType(),
2137 Arg.getAsType(),
2138 Info, Deduced, 0);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002139 Info.FirstArg = Param;
2140 Info.SecondArg = Arg;
2141 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002142
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002143 case TemplateArgument::Template:
Douglas Gregoradee3e32009-11-11 23:06:43 +00002144 if (Arg.getKind() == TemplateArgument::Template)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002145 return DeduceTemplateArguments(S, TemplateParams,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002146 Param.getAsTemplate(),
Douglas Gregoradee3e32009-11-11 23:06:43 +00002147 Arg.getAsTemplate(), Info, Deduced);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002148 Info.FirstArg = Param;
2149 Info.SecondArg = Arg;
2150 return Sema::TDK_NonDeducedMismatch;
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002151
2152 case TemplateArgument::TemplateExpansion:
2153 llvm_unreachable("caller should handle pack expansions");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002154
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002155 case TemplateArgument::Declaration:
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002156 if (Arg.getKind() == TemplateArgument::Declaration &&
David Blaikie0f62c8d2014-10-16 04:21:25 +00002157 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
Eli Friedmanb826a002012-09-26 02:36:12 +00002158 return Sema::TDK_Success;
2159
2160 Info.FirstArg = Param;
2161 Info.SecondArg = Arg;
2162 return Sema::TDK_NonDeducedMismatch;
2163
2164 case TemplateArgument::NullPtr:
2165 if (Arg.getKind() == TemplateArgument::NullPtr &&
2166 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002167 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002168
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002169 Info.FirstArg = Param;
2170 Info.SecondArg = Arg;
2171 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00002172
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002173 case TemplateArgument::Integral:
2174 if (Arg.getKind() == TemplateArgument::Integral) {
Benjamin Kramer6003ad52012-06-07 15:09:51 +00002175 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002176 return Sema::TDK_Success;
2177
2178 Info.FirstArg = Param;
2179 Info.SecondArg = Arg;
2180 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002181 }
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002182
2183 if (Arg.getKind() == TemplateArgument::Expression) {
2184 Info.FirstArg = Param;
2185 Info.SecondArg = Arg;
2186 return Sema::TDK_NonDeducedMismatch;
2187 }
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002188
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002189 Info.FirstArg = Param;
2190 Info.SecondArg = Arg;
2191 return Sema::TDK_NonDeducedMismatch;
Mike Stump11289f42009-09-09 15:08:12 +00002192
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00002193 case TemplateArgument::Expression:
Mike Stump11289f42009-09-09 15:08:12 +00002194 if (NonTypeTemplateParmDecl *NTTP
Richard Smith87d263e2016-12-25 08:05:23 +00002195 = getDeducedParameterFromExpr(Info, Param.getAsExpr())) {
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002196 if (Arg.getKind() == TemplateArgument::Integral)
Richard Smith5f274382016-09-28 23:55:27 +00002197 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
Benjamin Kramer6003ad52012-06-07 15:09:51 +00002198 Arg.getAsIntegral(),
Douglas Gregor0a29a052010-03-26 05:50:28 +00002199 Arg.getIntegralType(),
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002200 /*ArrayBound=*/false,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002201 Info, Deduced);
Richard Smith38175a22016-09-28 22:08:38 +00002202 if (Arg.getKind() == TemplateArgument::NullPtr)
Richard Smith5f274382016-09-28 23:55:27 +00002203 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
2204 Arg.getNullPtrType(),
Richard Smith38175a22016-09-28 22:08:38 +00002205 Info, Deduced);
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002206 if (Arg.getKind() == TemplateArgument::Expression)
Richard Smith5f274382016-09-28 23:55:27 +00002207 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2208 Arg.getAsExpr(), Info, Deduced);
Douglas Gregor2bb756a2009-11-13 23:45:44 +00002209 if (Arg.getKind() == TemplateArgument::Declaration)
Richard Smith5f274382016-09-28 23:55:27 +00002210 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2211 Arg.getAsDecl(),
2212 Arg.getParamTypeForDecl(),
Douglas Gregor2bb756a2009-11-13 23:45:44 +00002213 Info, Deduced);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002214
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002215 Info.FirstArg = Param;
2216 Info.SecondArg = Arg;
2217 return Sema::TDK_NonDeducedMismatch;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002218 }
Mike Stump11289f42009-09-09 15:08:12 +00002219
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002220 // Can't deduce anything, but that's okay.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002221 return Sema::TDK_Success;
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00002222
Anders Carlssonbc343912009-06-15 17:04:53 +00002223 case TemplateArgument::Pack:
Douglas Gregor7baabef2010-12-22 18:17:10 +00002224 llvm_unreachable("Argument packs should be expanded by the caller!");
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002225 }
Mike Stump11289f42009-09-09 15:08:12 +00002226
David Blaikiee4d798f2012-01-20 21:50:17 +00002227 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002228}
2229
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002230/// Determine whether there is a template argument to be used for
Douglas Gregor7baabef2010-12-22 18:17:10 +00002231/// deduction.
2232///
2233/// This routine "expands" argument packs in-place, overriding its input
2234/// parameters so that \c Args[ArgIdx] will be the available template argument.
2235///
2236/// \returns true if there is another template argument (which will be at
2237/// \c Args[ArgIdx]), false otherwise.
Richard Smith0bda5b52016-12-23 23:46:56 +00002238static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
2239 unsigned &ArgIdx) {
2240 if (ArgIdx == Args.size())
Douglas Gregor7baabef2010-12-22 18:17:10 +00002241 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002242
Douglas Gregor7baabef2010-12-22 18:17:10 +00002243 const TemplateArgument &Arg = Args[ArgIdx];
2244 if (Arg.getKind() != TemplateArgument::Pack)
2245 return true;
2246
Richard Smith0bda5b52016-12-23 23:46:56 +00002247 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
2248 Args = Arg.pack_elements();
Douglas Gregor7baabef2010-12-22 18:17:10 +00002249 ArgIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00002250 return ArgIdx < Args.size();
Douglas Gregor7baabef2010-12-22 18:17:10 +00002251}
2252
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002253/// Determine whether the given set of template arguments has a pack
Douglas Gregord0ad2942010-12-23 01:24:45 +00002254/// expansion that is not the last template argument.
Richard Smith0bda5b52016-12-23 23:46:56 +00002255static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
2256 bool FoundPackExpansion = false;
2257 for (const auto &A : Args) {
2258 if (FoundPackExpansion)
Douglas Gregord0ad2942010-12-23 01:24:45 +00002259 return true;
Richard Smith0bda5b52016-12-23 23:46:56 +00002260
2261 if (A.getKind() == TemplateArgument::Pack)
2262 return hasPackExpansionBeforeEnd(A.pack_elements());
2263
Richard Smith4a8f3512018-07-19 19:00:37 +00002264 // FIXME: If this is a fixed-arity pack expansion from an outer level of
2265 // templates, it should not be treated as a pack expansion.
Richard Smith0bda5b52016-12-23 23:46:56 +00002266 if (A.isPackExpansion())
2267 FoundPackExpansion = true;
Douglas Gregord0ad2942010-12-23 01:24:45 +00002268 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002269
Douglas Gregord0ad2942010-12-23 01:24:45 +00002270 return false;
2271}
2272
Douglas Gregor7baabef2010-12-22 18:17:10 +00002273static Sema::TemplateDeductionResult
Erik Pilkington6a16ac02016-06-28 23:05:09 +00002274DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
Richard Smith0bda5b52016-12-23 23:46:56 +00002275 ArrayRef<TemplateArgument> Params,
2276 ArrayRef<TemplateArgument> Args,
Douglas Gregor7baabef2010-12-22 18:17:10 +00002277 TemplateDeductionInfo &Info,
Erik Pilkington6a16ac02016-06-28 23:05:09 +00002278 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2279 bool NumberOfArgumentsMustMatch) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002280 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002281 // If the template argument list of P contains a pack expansion that is not
2282 // the last template argument, the entire template argument list is a
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002283 // non-deduced context.
Richard Smith0bda5b52016-12-23 23:46:56 +00002284 if (hasPackExpansionBeforeEnd(Params))
Douglas Gregord0ad2942010-12-23 01:24:45 +00002285 return Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002286
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002287 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002288 // If P has a form that contains <T> or <i>, then each argument Pi of the
2289 // respective template argument list P is compared with the corresponding
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002290 // argument Ai of the corresponding template argument list of A.
Douglas Gregor7baabef2010-12-22 18:17:10 +00002291 unsigned ArgIdx = 0, ParamIdx = 0;
Richard Smith0bda5b52016-12-23 23:46:56 +00002292 for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) {
Douglas Gregor7baabef2010-12-22 18:17:10 +00002293 if (!Params[ParamIdx].isPackExpansion()) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002294 // The simple case: deduce template arguments by matching Pi and Ai.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002295
Douglas Gregor7baabef2010-12-22 18:17:10 +00002296 // Check whether we have enough arguments.
Richard Smith0bda5b52016-12-23 23:46:56 +00002297 if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
Richard Smithec7176e2017-01-05 02:31:32 +00002298 return NumberOfArgumentsMustMatch
2299 ? Sema::TDK_MiscellaneousDeductionFailure
2300 : Sema::TDK_Success;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002301
Richard Smith26b86ea2016-12-31 21:41:23 +00002302 // C++1z [temp.deduct.type]p9:
2303 // During partial ordering, if Ai was originally a pack expansion [and]
2304 // Pi is not a pack expansion, template argument deduction fails.
2305 if (Args[ArgIdx].isPackExpansion())
Richard Smith44ecdbd2013-01-31 05:19:49 +00002306 return Sema::TDK_MiscellaneousDeductionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002307
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002308 // Perform deduction for this Pi/Ai pair.
Douglas Gregor7baabef2010-12-22 18:17:10 +00002309 if (Sema::TemplateDeductionResult Result
Douglas Gregor2fcb8632011-01-11 22:21:24 +00002310 = DeduceTemplateArguments(S, TemplateParams,
2311 Params[ParamIdx], Args[ArgIdx],
2312 Info, Deduced))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002313 return Result;
2314
Douglas Gregor7baabef2010-12-22 18:17:10 +00002315 // Move to the next argument.
2316 ++ArgIdx;
2317 continue;
2318 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002319
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002320 // The parameter is a pack expansion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002321
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002322 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002323 // If Pi is a pack expansion, then the pattern of Pi is compared with
2324 // each remaining argument in the template argument list of A. Each
2325 // comparison deduces template arguments for subsequent positions in the
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002326 // template parameter packs expanded by Pi.
2327 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002328
Richard Smith0a80d572014-05-29 01:12:14 +00002329 // Prepare to deduce the packs within the pattern.
2330 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002331
2332 // Keep track of the deduced template arguments for each parameter pack
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002333 // expanded by this pack expansion (the outer index) and for each
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002334 // template argument (the inner SmallVectors).
Richard Smith4a8f3512018-07-19 19:00:37 +00002335 for (; hasTemplateArgumentForDeduction(Args, ArgIdx) &&
2336 PackScope.hasNextElement();
2337 ++ArgIdx) {
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002338 // Deduce template arguments from the pattern.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002339 if (Sema::TemplateDeductionResult Result
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002340 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
2341 Info, Deduced))
2342 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002343
Richard Smith0a80d572014-05-29 01:12:14 +00002344 PackScope.nextPackElement();
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002345 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002346
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002347 // Build argument packs for each of the parameter packs expanded by this
2348 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00002349 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002350 return Result;
Douglas Gregor7baabef2010-12-22 18:17:10 +00002351 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002352
Douglas Gregor7baabef2010-12-22 18:17:10 +00002353 return Sema::TDK_Success;
2354}
2355
Mike Stump11289f42009-09-09 15:08:12 +00002356static Sema::TemplateDeductionResult
Chandler Carruthc1263112010-02-07 21:33:28 +00002357DeduceTemplateArguments(Sema &S,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002358 TemplateParameterList *TemplateParams,
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002359 const TemplateArgumentList &ParamList,
2360 const TemplateArgumentList &ArgList,
John McCall19c1bfd2010-08-25 05:32:35 +00002361 TemplateDeductionInfo &Info,
Craig Topper79653572013-07-08 04:13:06 +00002362 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
Richard Smith0bda5b52016-12-23 23:46:56 +00002363 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
Richard Smith26b86ea2016-12-31 21:41:23 +00002364 ArgList.asArray(), Info, Deduced,
2365 /*NumberOfArgumentsMustMatch*/false);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002366}
2367
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002368/// Determine whether two template arguments are the same.
Mike Stump11289f42009-09-09 15:08:12 +00002369static bool isSameTemplateArg(ASTContext &Context,
Richard Smith0e617ec2016-12-27 07:56:27 +00002370 TemplateArgument X,
2371 const TemplateArgument &Y,
2372 bool PackExpansionMatchesPack = false) {
2373 // If we're checking deduced arguments (X) against original arguments (Y),
2374 // we will have flattened packs to non-expansions in X.
2375 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
2376 X = X.getPackExpansionPattern();
2377
Douglas Gregor705c9002009-06-26 20:57:09 +00002378 if (X.getKind() != Y.getKind())
2379 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002380
Douglas Gregor705c9002009-06-26 20:57:09 +00002381 switch (X.getKind()) {
2382 case TemplateArgument::Null:
David Blaikie83d382b2011-09-23 05:06:16 +00002383 llvm_unreachable("Comparing NULL template argument");
Mike Stump11289f42009-09-09 15:08:12 +00002384
Douglas Gregor705c9002009-06-26 20:57:09 +00002385 case TemplateArgument::Type:
2386 return Context.getCanonicalType(X.getAsType()) ==
2387 Context.getCanonicalType(Y.getAsType());
Mike Stump11289f42009-09-09 15:08:12 +00002388
Douglas Gregor705c9002009-06-26 20:57:09 +00002389 case TemplateArgument::Declaration:
David Blaikie0f62c8d2014-10-16 04:21:25 +00002390 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
Eli Friedmanb826a002012-09-26 02:36:12 +00002391
2392 case TemplateArgument::NullPtr:
2393 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
Mike Stump11289f42009-09-09 15:08:12 +00002394
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002395 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002396 case TemplateArgument::TemplateExpansion:
2397 return Context.getCanonicalTemplateName(
2398 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2399 Context.getCanonicalTemplateName(
2400 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002401
Douglas Gregor705c9002009-06-26 20:57:09 +00002402 case TemplateArgument::Integral:
Richard Smith993f2032016-12-25 20:21:12 +00002403 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
Mike Stump11289f42009-09-09 15:08:12 +00002404
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002405 case TemplateArgument::Expression: {
2406 llvm::FoldingSetNodeID XID, YID;
2407 X.getAsExpr()->Profile(XID, Context, true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002408 Y.getAsExpr()->Profile(YID, Context, true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00002409 return XID == YID;
2410 }
Mike Stump11289f42009-09-09 15:08:12 +00002411
Douglas Gregor705c9002009-06-26 20:57:09 +00002412 case TemplateArgument::Pack:
2413 if (X.pack_size() != Y.pack_size())
2414 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002415
2416 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2417 XPEnd = X.pack_end(),
Douglas Gregor705c9002009-06-26 20:57:09 +00002418 YP = Y.pack_begin();
Mike Stump11289f42009-09-09 15:08:12 +00002419 XP != XPEnd; ++XP, ++YP)
Richard Smith0e617ec2016-12-27 07:56:27 +00002420 if (!isSameTemplateArg(Context, *XP, *YP, PackExpansionMatchesPack))
Douglas Gregor705c9002009-06-26 20:57:09 +00002421 return false;
2422
2423 return true;
2424 }
2425
David Blaikiee4d798f2012-01-20 21:50:17 +00002426 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregor705c9002009-06-26 20:57:09 +00002427}
2428
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002429/// Allocate a TemplateArgumentLoc where all locations have
Douglas Gregorca4686d2011-01-04 23:35:54 +00002430/// been initialized to the given location.
2431///
James Dennett634962f2012-06-14 21:40:34 +00002432/// \param Arg The template argument we are producing template argument
Douglas Gregorca4686d2011-01-04 23:35:54 +00002433/// location information for.
2434///
2435/// \param NTTPType For a declaration template argument, the type of
2436/// the non-type template parameter that corresponds to this template
Richard Smith93417902016-12-23 02:00:24 +00002437/// argument. Can be null if no type sugar is available to add to the
2438/// type from the template argument.
Douglas Gregorca4686d2011-01-04 23:35:54 +00002439///
2440/// \param Loc The source location to use for the resulting template
2441/// argument.
Richard Smith7873de02016-08-11 22:25:46 +00002442TemplateArgumentLoc
2443Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2444 QualType NTTPType, SourceLocation Loc) {
Douglas Gregorca4686d2011-01-04 23:35:54 +00002445 switch (Arg.getKind()) {
2446 case TemplateArgument::Null:
2447 llvm_unreachable("Can't get a NULL template argument here");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002448
Douglas Gregorca4686d2011-01-04 23:35:54 +00002449 case TemplateArgument::Type:
Richard Smith7873de02016-08-11 22:25:46 +00002450 return TemplateArgumentLoc(
2451 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002452
Douglas Gregorca4686d2011-01-04 23:35:54 +00002453 case TemplateArgument::Declaration: {
Richard Smith93417902016-12-23 02:00:24 +00002454 if (NTTPType.isNull())
2455 NTTPType = Arg.getParamTypeForDecl();
Richard Smith7873de02016-08-11 22:25:46 +00002456 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2457 .getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002458 return TemplateArgumentLoc(TemplateArgument(E), E);
2459 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002460
Eli Friedmanb826a002012-09-26 02:36:12 +00002461 case TemplateArgument::NullPtr: {
Richard Smith93417902016-12-23 02:00:24 +00002462 if (NTTPType.isNull())
2463 NTTPType = Arg.getNullPtrType();
Richard Smith7873de02016-08-11 22:25:46 +00002464 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2465 .getAs<Expr>();
Eli Friedmanb826a002012-09-26 02:36:12 +00002466 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2467 E);
2468 }
2469
Douglas Gregorca4686d2011-01-04 23:35:54 +00002470 case TemplateArgument::Integral: {
Richard Smith7873de02016-08-11 22:25:46 +00002471 Expr *E =
2472 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002473 return TemplateArgumentLoc(TemplateArgument(E), E);
2474 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002475
Douglas Gregor9d802122011-03-02 17:09:35 +00002476 case TemplateArgument::Template:
2477 case TemplateArgument::TemplateExpansion: {
2478 NestedNameSpecifierLocBuilder Builder;
2479 TemplateName Template = Arg.getAsTemplate();
2480 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002481 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
Nico Weberc153d242014-07-28 00:02:09 +00002482 else if (QualifiedTemplateName *QTN =
2483 Template.getAsQualifiedTemplateName())
Richard Smith7873de02016-08-11 22:25:46 +00002484 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
Simon Pilgrim728134c2016-08-12 11:43:57 +00002485
Douglas Gregor9d802122011-03-02 17:09:35 +00002486 if (Arg.getKind() == TemplateArgument::Template)
Richard Smith7873de02016-08-11 22:25:46 +00002487 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002488 Loc);
Richard Smith7873de02016-08-11 22:25:46 +00002489
2490 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
Douglas Gregor9d802122011-03-02 17:09:35 +00002491 Loc, Loc);
2492 }
Douglas Gregore4ff4b52011-01-05 18:58:31 +00002493
Douglas Gregorca4686d2011-01-04 23:35:54 +00002494 case TemplateArgument::Expression:
2495 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002496
Douglas Gregorca4686d2011-01-04 23:35:54 +00002497 case TemplateArgument::Pack:
2498 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2499 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002500
David Blaikiee4d798f2012-01-20 21:50:17 +00002501 llvm_unreachable("Invalid TemplateArgument Kind!");
Douglas Gregorca4686d2011-01-04 23:35:54 +00002502}
2503
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002504/// Convert the given deduced template argument and add it to the set of
Douglas Gregorca4686d2011-01-04 23:35:54 +00002505/// fully-converted template arguments.
Craig Topper79653572013-07-08 04:13:06 +00002506static bool
2507ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2508 DeducedTemplateArgument Arg,
2509 NamedDecl *Template,
Craig Topper79653572013-07-08 04:13:06 +00002510 TemplateDeductionInfo &Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002511 bool IsDeduced,
Craig Topper79653572013-07-08 04:13:06 +00002512 SmallVectorImpl<TemplateArgument> &Output) {
Richard Smith37acb792016-02-03 20:15:01 +00002513 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2514 unsigned ArgumentPackIndex) {
2515 // Convert the deduced template argument into a template
2516 // argument that we can check, almost as if the user had written
2517 // the template argument explicitly.
2518 TemplateArgumentLoc ArgLoc =
Richard Smith93417902016-12-23 02:00:24 +00002519 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
Richard Smith37acb792016-02-03 20:15:01 +00002520
2521 // Check the template argument, converting it as necessary.
2522 return S.CheckTemplateArgument(
2523 Param, ArgLoc, Template, Template->getLocation(),
2524 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
Richard Smith87d263e2016-12-25 08:05:23 +00002525 IsDeduced
Richard Smith37acb792016-02-03 20:15:01 +00002526 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2527 : Sema::CTAK_Deduced)
2528 : Sema::CTAK_Specified);
2529 };
2530
Douglas Gregorca4686d2011-01-04 23:35:54 +00002531 if (Arg.getKind() == TemplateArgument::Pack) {
2532 // This is a template argument pack, so check each of its arguments against
2533 // the template parameter.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002534 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
Aaron Ballman2a89e852014-07-15 21:32:31 +00002535 for (const auto &P : Arg.pack_elements()) {
Douglas Gregor51bc5712011-01-05 20:52:18 +00002536 // When converting the deduced template argument, append it to the
2537 // general output list. We need to do this so that the template argument
2538 // checking logic has all of the prior template arguments available.
Aaron Ballman2a89e852014-07-15 21:32:31 +00002539 DeducedTemplateArgument InnerArg(P);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002540 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
Richard Smith37acb792016-02-03 20:15:01 +00002541 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2542 "deduced nested pack");
Richard Smith539e8e32017-01-04 01:48:55 +00002543 if (P.isNull()) {
2544 // We deduced arguments for some elements of this pack, but not for
2545 // all of them. This happens if we get a conditionally-non-deduced
2546 // context in a pack expansion (such as an overload set in one of the
2547 // arguments).
2548 S.Diag(Param->getLocation(),
2549 diag::err_template_arg_deduced_incomplete_pack)
2550 << Arg << Param;
2551 return true;
2552 }
Richard Smith37acb792016-02-03 20:15:01 +00002553 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
Douglas Gregorca4686d2011-01-04 23:35:54 +00002554 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002555
Douglas Gregor51bc5712011-01-05 20:52:18 +00002556 // Move the converted template argument into our argument pack.
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002557 PackedArgsBuilder.push_back(Output.pop_back_val());
Douglas Gregorca4686d2011-01-04 23:35:54 +00002558 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002559
Richard Smithdf18ee92016-02-03 20:40:30 +00002560 // If the pack is empty, we still need to substitute into the parameter
Richard Smith93417902016-12-23 02:00:24 +00002561 // itself, in case that substitution fails.
2562 if (PackedArgsBuilder.empty()) {
Richard Smithdf18ee92016-02-03 20:40:30 +00002563 LocalInstantiationScope Scope(S);
Richard Smithe8247752016-12-22 07:24:39 +00002564 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
Richard Smith93417902016-12-23 02:00:24 +00002565 MultiLevelTemplateArgumentList Args(TemplateArgs);
2566
2567 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2568 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2569 NTTP, Output,
2570 Template->getSourceRange());
Simon Pilgrim6f3e1ea2016-12-26 18:11:49 +00002571 if (Inst.isInvalid() ||
Richard Smith93417902016-12-23 02:00:24 +00002572 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2573 NTTP->getDeclName()).isNull())
2574 return true;
2575 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2576 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2577 TTP, Output,
2578 Template->getSourceRange());
2579 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2580 return true;
2581 }
2582 // For type parameters, no substitution is ever required.
Richard Smithdf18ee92016-02-03 20:40:30 +00002583 }
Richard Smith37acb792016-02-03 20:15:01 +00002584
Douglas Gregorca4686d2011-01-04 23:35:54 +00002585 // Create the resulting argument pack.
Benjamin Kramercce63472015-08-05 09:40:22 +00002586 Output.push_back(
2587 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
Douglas Gregorca4686d2011-01-04 23:35:54 +00002588 return false;
2589 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002590
Richard Smith37acb792016-02-03 20:15:01 +00002591 return ConvertArg(Arg, 0);
Douglas Gregorca4686d2011-01-04 23:35:54 +00002592}
2593
Richard Smith1f5be4d2016-12-21 01:10:31 +00002594// FIXME: This should not be a template, but
2595// ClassTemplatePartialSpecializationDecl sadly does not derive from
2596// TemplateDecl.
2597template<typename TemplateDeclT>
2598static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00002599 Sema &S, TemplateDeclT *Template, bool IsDeduced,
Richard Smith1f5be4d2016-12-21 01:10:31 +00002600 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2601 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2602 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
Richard Smithf0393bf2017-02-16 04:22:56 +00002603 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002604 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2605
2606 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2607 NamedDecl *Param = TemplateParams->getParam(I);
2608
Richard Smith4a8f3512018-07-19 19:00:37 +00002609 // C++0x [temp.arg.explicit]p3:
2610 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2611 // be deduced to an empty sequence of template arguments.
2612 // FIXME: Where did the word "trailing" come from?
2613 if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
2614 if (auto Result = PackDeductionScope(S, TemplateParams, Deduced, Info, I)
2615 .finish(/*TreatNoDeductionsAsNonDeduced*/false))
2616 return Result;
2617 }
2618
Richard Smith1f5be4d2016-12-21 01:10:31 +00002619 if (!Deduced[I].isNull()) {
2620 if (I < NumAlreadyConverted) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002621 // We may have had explicitly-specified template arguments for a
2622 // template parameter pack (that may or may not have been extended
2623 // via additional deduced arguments).
Richard Smith9c0c9862017-01-05 20:27:28 +00002624 if (Param->isParameterPack() && CurrentInstantiationScope &&
2625 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2626 // Forget the partially-substituted pack; its substitution is now
2627 // complete.
2628 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2629 // We still need to check the argument in case it was extended by
2630 // deduction.
2631 } else {
2632 // We have already fully type-checked and converted this
2633 // argument, because it was explicitly-specified. Just record the
2634 // presence of this argument.
2635 Builder.push_back(Deduced[I]);
2636 continue;
Richard Smith1f5be4d2016-12-21 01:10:31 +00002637 }
Richard Smith1f5be4d2016-12-21 01:10:31 +00002638 }
2639
Richard Smith9c0c9862017-01-05 20:27:28 +00002640 // We may have deduced this argument, so it still needs to be
Richard Smith1f5be4d2016-12-21 01:10:31 +00002641 // checked and converted.
2642 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
Richard Smith87d263e2016-12-25 08:05:23 +00002643 IsDeduced, Builder)) {
Richard Smith1f5be4d2016-12-21 01:10:31 +00002644 Info.Param = makeTemplateParameter(Param);
2645 // FIXME: These template arguments are temporary. Free them!
2646 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2647 return Sema::TDK_SubstitutionFailure;
2648 }
2649
2650 continue;
2651 }
2652
Richard Smith1f5be4d2016-12-21 01:10:31 +00002653 // Substitute into the default template argument, if available.
2654 bool HasDefaultArg = false;
2655 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2656 if (!TD) {
Richard Smithf8ba3fd2017-06-02 22:53:06 +00002657 assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
2658 isa<VarTemplatePartialSpecializationDecl>(Template));
Richard Smith1f5be4d2016-12-21 01:10:31 +00002659 return Sema::TDK_Incomplete;
2660 }
2661
2662 TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2663 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2664 HasDefaultArg);
2665
2666 // If there was no default argument, deduction is incomplete.
2667 if (DefArg.getArgument().isNull()) {
2668 Info.Param = makeTemplateParameter(
2669 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2670 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
Richard Smithf0393bf2017-02-16 04:22:56 +00002671 if (PartialOverloading) break;
2672
Richard Smith1f5be4d2016-12-21 01:10:31 +00002673 return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2674 : Sema::TDK_Incomplete;
2675 }
2676
2677 // Check whether we can actually use the default argument.
2678 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2679 TD->getSourceRange().getEnd(), 0, Builder,
2680 Sema::CTAK_Specified)) {
2681 Info.Param = makeTemplateParameter(
2682 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2683 // FIXME: These template arguments are temporary. Free them!
2684 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2685 return Sema::TDK_SubstitutionFailure;
2686 }
2687
2688 // If we get here, we successfully used the default template argument.
2689 }
2690
2691 return Sema::TDK_Success;
2692}
2693
Benjamin Kramer357c9e12017-02-11 12:21:17 +00002694static DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
Richard Smith0da6dc42016-12-24 16:40:51 +00002695 if (auto *DC = dyn_cast<DeclContext>(D))
2696 return DC;
2697 return D->getDeclContext();
2698}
2699
2700template<typename T> struct IsPartialSpecialization {
2701 static constexpr bool value = false;
2702};
2703template<>
2704struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
2705 static constexpr bool value = true;
2706};
2707template<>
2708struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
2709 static constexpr bool value = true;
2710};
2711
2712/// Complete template argument deduction for a partial specialization.
2713template <typename T>
2714static typename std::enable_if<IsPartialSpecialization<T>::value,
2715 Sema::TemplateDeductionResult>::type
2716FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00002717 Sema &S, T *Partial, bool IsPartialOrdering,
2718 const TemplateArgumentList &TemplateArgs,
Richard Smith0da6dc42016-12-24 16:40:51 +00002719 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2720 TemplateDeductionInfo &Info) {
Eli Friedman77dcc722012-02-08 03:07:05 +00002721 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002722 EnterExpressionEvaluationContext Unevaluated(
2723 S, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor684268d2010-04-29 06:21:43 +00002724 Sema::SFINAETrap Trap(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002725
Richard Smith0da6dc42016-12-24 16:40:51 +00002726 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
Douglas Gregor684268d2010-04-29 06:21:43 +00002727
2728 // C++ [temp.deduct.type]p2:
2729 // [...] or if any template argument remains neither deduced nor
2730 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002731 SmallVector<TemplateArgument, 4> Builder;
Richard Smith87d263e2016-12-25 08:05:23 +00002732 if (auto Result = ConvertDeducedTemplateArguments(
2733 S, Partial, IsPartialOrdering, Deduced, Info, Builder))
Richard Smith1f5be4d2016-12-21 01:10:31 +00002734 return Result;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002735
Douglas Gregor684268d2010-04-29 06:21:43 +00002736 // Form the template argument list from the deduced template arguments.
2737 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00002738 = TemplateArgumentList::CreateCopy(S.Context, Builder);
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002739
Douglas Gregor684268d2010-04-29 06:21:43 +00002740 Info.reset(DeducedArgumentList);
2741
2742 // Substitute the deduced template arguments into the template
2743 // arguments of the class template partial specialization, and
2744 // verify that the instantiated template arguments are both valid
2745 // and are equivalent to the template arguments originally provided
2746 // to the class template.
John McCall19c1bfd2010-08-25 05:32:35 +00002747 LocalInstantiationScope InstScope(S);
Richard Smith0da6dc42016-12-24 16:40:51 +00002748 auto *Template = Partial->getSpecializedTemplate();
2749 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2750 Partial->getTemplateArgsAsWritten();
2751 const TemplateArgumentLoc *PartialTemplateArgs =
2752 PartialTemplArgInfo->getTemplateArgs();
Douglas Gregor684268d2010-04-29 06:21:43 +00002753
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002754 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2755 PartialTemplArgInfo->RAngleLoc);
Douglas Gregor684268d2010-04-29 06:21:43 +00002756
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002757 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002758 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2759 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2760 if (ParamIdx >= Partial->getTemplateParameters()->size())
2761 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2762
Richard Smith0da6dc42016-12-24 16:40:51 +00002763 Decl *Param = const_cast<NamedDecl *>(
2764 Partial->getTemplateParameters()->getParam(ParamIdx));
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002765 Info.Param = makeTemplateParameter(Param);
2766 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2767 return Sema::TDK_SubstitutionFailure;
Douglas Gregor684268d2010-04-29 06:21:43 +00002768 }
2769
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002770 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
Richard Smith0da6dc42016-12-24 16:40:51 +00002771 if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2772 false, ConvertedInstArgs))
Douglas Gregor684268d2010-04-29 06:21:43 +00002773 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002774
Richard Smith0da6dc42016-12-24 16:40:51 +00002775 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
Douglas Gregorca4686d2011-01-04 23:35:54 +00002776 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002777 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
Douglas Gregor684268d2010-04-29 06:21:43 +00002778 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
Douglas Gregor66990032011-01-05 00:13:17 +00002779 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
Douglas Gregor684268d2010-04-29 06:21:43 +00002780 Info.FirstArg = TemplateArgs[I];
2781 Info.SecondArg = InstArg;
2782 return Sema::TDK_NonDeducedMismatch;
2783 }
2784 }
2785
2786 if (Trap.hasErrorOccurred())
2787 return Sema::TDK_SubstitutionFailure;
2788
2789 return Sema::TDK_Success;
2790}
2791
Richard Smith0e617ec2016-12-27 07:56:27 +00002792/// Complete template argument deduction for a class or variable template,
2793/// when partial ordering against a partial specialization.
2794// FIXME: Factor out duplication with partial specialization version above.
Benjamin Kramer357c9e12017-02-11 12:21:17 +00002795static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
Richard Smith0e617ec2016-12-27 07:56:27 +00002796 Sema &S, TemplateDecl *Template, bool PartialOrdering,
2797 const TemplateArgumentList &TemplateArgs,
2798 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2799 TemplateDeductionInfo &Info) {
2800 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002801 EnterExpressionEvaluationContext Unevaluated(
2802 S, Sema::ExpressionEvaluationContext::Unevaluated);
Richard Smith0e617ec2016-12-27 07:56:27 +00002803 Sema::SFINAETrap Trap(S);
2804
2805 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
2806
2807 // C++ [temp.deduct.type]p2:
2808 // [...] or if any template argument remains neither deduced nor
2809 // explicitly specified, template argument deduction fails.
2810 SmallVector<TemplateArgument, 4> Builder;
2811 if (auto Result = ConvertDeducedTemplateArguments(
2812 S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder))
2813 return Result;
2814
2815 // Check that we produced the correct argument list.
2816 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2817 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2818 TemplateArgument InstArg = Builder[I];
2819 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
2820 /*PackExpansionMatchesPack*/true)) {
2821 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2822 Info.FirstArg = TemplateArgs[I];
2823 Info.SecondArg = InstArg;
2824 return Sema::TDK_NonDeducedMismatch;
2825 }
2826 }
2827
2828 if (Trap.hasErrorOccurred())
2829 return Sema::TDK_SubstitutionFailure;
2830
2831 return Sema::TDK_Success;
2832}
2833
2834
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002835/// Perform template argument deduction to determine whether
Larisse Voufo833b05a2013-08-06 07:33:00 +00002836/// the given template arguments match the given class template
Douglas Gregor170bc422009-06-12 22:31:52 +00002837/// partial specialization per C++ [temp.class.spec.match].
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002838Sema::TemplateDeductionResult
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002839Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002840 const TemplateArgumentList &TemplateArgs,
2841 TemplateDeductionInfo &Info) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00002842 if (Partial->isInvalidDecl())
2843 return TDK_Invalid;
2844
Douglas Gregor170bc422009-06-12 22:31:52 +00002845 // C++ [temp.class.spec.match]p2:
2846 // A partial specialization matches a given actual template
2847 // argument list if the template arguments of the partial
2848 // specialization can be deduced from the actual template argument
2849 // list (14.8.2).
Eli Friedman77dcc722012-02-08 03:07:05 +00002850
2851 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002852 EnterExpressionEvaluationContext Unevaluated(
2853 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregore1416332009-06-14 08:02:22 +00002854 SFINAETrap Trap(*this);
Eli Friedman77dcc722012-02-08 03:07:05 +00002855
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002856 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002857 Deduced.resize(Partial->getTemplateParameters()->size());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002858 if (TemplateDeductionResult Result
Chandler Carruthc1263112010-02-07 21:33:28 +00002859 = ::DeduceTemplateArguments(*this,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002860 Partial->getTemplateParameters(),
Mike Stump11289f42009-09-09 15:08:12 +00002861 Partial->getTemplateArgs(),
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002862 TemplateArgs, Info, Deduced))
2863 return Result;
Douglas Gregor637d9982009-06-10 23:47:09 +00002864
Richard Smith80934652012-07-16 01:09:10 +00002865 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002866 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2867 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002868 if (Inst.isInvalid())
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002869 return TDK_InstantiationDepth;
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002870
Douglas Gregore1416332009-06-14 08:02:22 +00002871 if (Trap.hasErrorOccurred())
Douglas Gregor684268d2010-04-29 06:21:43 +00002872 return Sema::TDK_SubstitutionFailure;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002873
Richard Smith87d263e2016-12-25 08:05:23 +00002874 return ::FinishTemplateArgumentDeduction(
2875 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Douglas Gregor55ca8f62009-06-04 00:03:07 +00002876}
Douglas Gregor91772d12009-06-13 00:26:55 +00002877
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002878/// Perform template argument deduction to determine whether
Larisse Voufo39a1e502013-08-06 01:03:05 +00002879/// the given template arguments match the given variable template
2880/// partial specialization per C++ [temp.class.spec.match].
Larisse Voufo39a1e502013-08-06 01:03:05 +00002881Sema::TemplateDeductionResult
2882Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2883 const TemplateArgumentList &TemplateArgs,
2884 TemplateDeductionInfo &Info) {
2885 if (Partial->isInvalidDecl())
2886 return TDK_Invalid;
2887
2888 // C++ [temp.class.spec.match]p2:
2889 // A partial specialization matches a given actual template
2890 // argument list if the template arguments of the partial
2891 // specialization can be deduced from the actual template argument
2892 // list (14.8.2).
2893
2894 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002895 EnterExpressionEvaluationContext Unevaluated(
2896 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002897 SFINAETrap Trap(*this);
2898
2899 SmallVector<DeducedTemplateArgument, 4> Deduced;
2900 Deduced.resize(Partial->getTemplateParameters()->size());
2901 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2902 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2903 TemplateArgs, Info, Deduced))
2904 return Result;
2905
2906 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Nick Lewycky56412332014-01-11 02:37:12 +00002907 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2908 Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002909 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00002910 return TDK_InstantiationDepth;
2911
2912 if (Trap.hasErrorOccurred())
2913 return Sema::TDK_SubstitutionFailure;
2914
Richard Smith87d263e2016-12-25 08:05:23 +00002915 return ::FinishTemplateArgumentDeduction(
2916 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002917}
2918
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002919/// Determine whether the given type T is a simple-template-id type.
Douglas Gregorfc516c92009-06-26 23:27:24 +00002920static bool isSimpleTemplateIdType(QualType T) {
Mike Stump11289f42009-09-09 15:08:12 +00002921 if (const TemplateSpecializationType *Spec
John McCall9dd450b2009-09-21 23:43:11 +00002922 = T->getAs<TemplateSpecializationType>())
Craig Topperc3ec1492014-05-26 06:22:03 +00002923 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002924
Richard Smith1363e8f2017-09-07 07:22:36 +00002925 // C++17 [temp.local]p2:
2926 // the injected-class-name [...] is equivalent to the template-name followed
2927 // by the template-arguments of the class template specialization or partial
2928 // specialization enclosed in <>
2929 // ... which means it's equivalent to a simple-template-id.
2930 //
2931 // This only arises during class template argument deduction for a copy
2932 // deduction candidate, where it permits slicing.
2933 if (T->getAs<InjectedClassNameType>())
2934 return true;
2935
Douglas Gregorfc516c92009-06-26 23:27:24 +00002936 return false;
2937}
Douglas Gregor9b146582009-07-08 20:55:45 +00002938
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002939/// Substitute the explicitly-provided template arguments into the
Douglas Gregor9b146582009-07-08 20:55:45 +00002940/// given function template according to C++ [temp.arg.explicit].
2941///
2942/// \param FunctionTemplate the function template into which the explicit
2943/// template arguments will be substituted.
2944///
James Dennett634962f2012-06-14 21:40:34 +00002945/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor9b146582009-07-08 20:55:45 +00002946/// arguments.
2947///
Mike Stump11289f42009-09-09 15:08:12 +00002948/// \param Deduced the deduced template arguments, which will be populated
Douglas Gregor9b146582009-07-08 20:55:45 +00002949/// with the converted and checked explicit template arguments.
2950///
Mike Stump11289f42009-09-09 15:08:12 +00002951/// \param ParamTypes will be populated with the instantiated function
Douglas Gregor9b146582009-07-08 20:55:45 +00002952/// parameters.
2953///
2954/// \param FunctionType if non-NULL, the result type of the function template
2955/// will also be instantiated and the pointed-to value will be updated with
2956/// the instantiated function type.
2957///
2958/// \param Info if substitution fails for any reason, this object will be
2959/// populated with more information about the failure.
2960///
2961/// \returns TDK_Success if substitution was successful, or some failure
2962/// condition.
2963Sema::TemplateDeductionResult
2964Sema::SubstituteExplicitTemplateArguments(
2965 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor739b107a2011-03-03 02:41:12 +00002966 TemplateArgumentListInfo &ExplicitTemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002967 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2968 SmallVectorImpl<QualType> &ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00002969 QualType *FunctionType,
2970 TemplateDeductionInfo &Info) {
2971 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2972 TemplateParameterList *TemplateParams
2973 = FunctionTemplate->getTemplateParameters();
2974
John McCall6b51f282009-11-23 01:53:49 +00002975 if (ExplicitTemplateArgs.size() == 0) {
Douglas Gregor9b146582009-07-08 20:55:45 +00002976 // No arguments to substitute; just copy over the parameter types and
2977 // fill in the function type.
David Majnemer59f77922016-06-24 04:05:48 +00002978 for (auto P : Function->parameters())
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002979 ParamTypes.push_back(P->getType());
Mike Stump11289f42009-09-09 15:08:12 +00002980
Douglas Gregor9b146582009-07-08 20:55:45 +00002981 if (FunctionType)
2982 *FunctionType = Function->getType();
2983 return TDK_Success;
2984 }
Mike Stump11289f42009-09-09 15:08:12 +00002985
Eli Friedman77dcc722012-02-08 03:07:05 +00002986 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00002987 EnterExpressionEvaluationContext Unevaluated(
2988 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00002989 SFINAETrap Trap(*this);
2990
Douglas Gregor9b146582009-07-08 20:55:45 +00002991 // C++ [temp.arg.explicit]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002992 // Template arguments that are present shall be specified in the
2993 // declaration order of their corresponding template-parameters. The
Douglas Gregor9b146582009-07-08 20:55:45 +00002994 // template argument list shall not specify more template-arguments than
Mike Stump11289f42009-09-09 15:08:12 +00002995 // there are corresponding template-parameters.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002996 SmallVector<TemplateArgument, 4> Builder;
Mike Stump11289f42009-09-09 15:08:12 +00002997
2998 // Enter a new template instantiation context where we check the
Douglas Gregor9b146582009-07-08 20:55:45 +00002999 // explicitly-specified template arguments against this function template,
3000 // and then substitute them into the function parameter types.
Richard Smithde0d34a2017-01-09 07:14:40 +00003001 SmallVector<TemplateArgument, 4> DeducedArgs;
Richard Smith696e3122017-02-23 01:43:54 +00003002 InstantiatingTemplate Inst(
3003 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3004 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003005 if (Inst.isInvalid())
Douglas Gregor9b146582009-07-08 20:55:45 +00003006 return TDK_InstantiationDepth;
Mike Stump11289f42009-09-09 15:08:12 +00003007
Richard Smith11255ec2017-01-18 19:19:22 +00003008 if (CheckTemplateArgumentList(FunctionTemplate, SourceLocation(),
3009 ExplicitTemplateArgs, true, Builder, false) ||
3010 Trap.hasErrorOccurred()) {
Douglas Gregor1ccc8412010-11-07 23:05:16 +00003011 unsigned Index = Builder.size();
Douglas Gregor62c281a2010-05-09 01:26:06 +00003012 if (Index >= TemplateParams->size())
Richard Smith4a8f3512018-07-19 19:00:37 +00003013 return TDK_SubstitutionFailure;
Douglas Gregor62c281a2010-05-09 01:26:06 +00003014 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
Douglas Gregor9b146582009-07-08 20:55:45 +00003015 return TDK_InvalidExplicitArguments;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00003016 }
Mike Stump11289f42009-09-09 15:08:12 +00003017
Douglas Gregor9b146582009-07-08 20:55:45 +00003018 // Form the template argument list from the explicitly-specified
3019 // template arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003020 TemplateArgumentList *ExplicitArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00003021 = TemplateArgumentList::CreateCopy(Context, Builder);
Richard Smith4a8f3512018-07-19 19:00:37 +00003022 Info.setExplicitArgs(ExplicitArgumentList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003023
John McCall036855a2010-10-12 19:40:14 +00003024 // Template argument deduction and the final substitution should be
3025 // done in the context of the templated declaration. Explicit
3026 // argument substitution, on the other hand, needs to happen in the
3027 // calling context.
3028 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3029
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003030 // If we deduced template arguments for a template parameter pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003031 // note that the template argument pack is partially substituted and record
3032 // the explicit template arguments. They'll be used as part of deduction
3033 // for this template parameter pack.
Richard Smith4a8f3512018-07-19 19:00:37 +00003034 unsigned PartiallySubstitutedPackIndex = -1u;
3035 if (!Builder.empty()) {
3036 const TemplateArgument &Arg = Builder.back();
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003037 if (Arg.getKind() == TemplateArgument::Pack) {
Richard Smith4a8f3512018-07-19 19:00:37 +00003038 auto *Param = TemplateParams->getParam(Builder.size() - 1);
3039 // If this is a fully-saturated fixed-size pack, it should be
3040 // fully-substituted, not partially-substituted.
3041 Optional<unsigned> Expansions = getExpandedPackSize(Param);
3042 if (!Expansions || Arg.pack_size() < *Expansions) {
3043 PartiallySubstitutedPackIndex = Builder.size() - 1;
3044 CurrentInstantiationScope->SetPartiallySubstitutedPack(
3045 Param, Arg.pack_begin(), Arg.pack_size());
3046 }
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003047 }
3048 }
3049
Richard Smith5e580292012-02-10 09:58:53 +00003050 const FunctionProtoType *Proto
3051 = Function->getType()->getAs<FunctionProtoType>();
3052 assert(Proto && "Function template does not have a prototype?");
3053
Richard Smith70b13042015-01-09 01:19:56 +00003054 // Isolate our substituted parameters from our caller.
3055 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
3056
John McCallc8e321d2016-03-01 02:09:25 +00003057 ExtParameterInfoBuilder ExtParamInfos;
3058
Douglas Gregor9b146582009-07-08 20:55:45 +00003059 // Instantiate the types of each of the function parameters given the
Richard Smith5e580292012-02-10 09:58:53 +00003060 // explicitly-specified template arguments. If the function has a trailing
3061 // return type, substitute it after the arguments to ensure we substitute
3062 // in lexical order.
Douglas Gregor3024f072012-04-16 07:05:22 +00003063 if (Proto->hasTrailingReturn()) {
David Majnemer59f77922016-06-24 04:05:48 +00003064 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00003065 Proto->getExtParameterInfosOrNull(),
Douglas Gregor3024f072012-04-16 07:05:22 +00003066 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00003067 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Douglas Gregor3024f072012-04-16 07:05:22 +00003068 return TDK_SubstitutionFailure;
3069 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003070
Richard Smith5e580292012-02-10 09:58:53 +00003071 // Instantiate the return type.
Douglas Gregor3024f072012-04-16 07:05:22 +00003072 QualType ResultType;
3073 {
3074 // C++11 [expr.prim.general]p3:
Simon Pilgrim728134c2016-08-12 11:43:57 +00003075 // If a declaration declares a member function or member function
3076 // template of a class X, the expression this is a prvalue of type
Douglas Gregor3024f072012-04-16 07:05:22 +00003077 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
Simon Pilgrim728134c2016-08-12 11:43:57 +00003078 // and the end of the function-definition, member-declarator, or
Douglas Gregor3024f072012-04-16 07:05:22 +00003079 // declarator.
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003080 Qualifiers ThisTypeQuals;
Craig Topperc3ec1492014-05-26 06:22:03 +00003081 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00003082 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3083 ThisContext = Method->getParent();
3084 ThisTypeQuals = Method->getTypeQualifiers();
3085 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003086
Douglas Gregor3024f072012-04-16 07:05:22 +00003087 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003088 getLangOpts().CPlusPlus11);
Alp Toker314cc812014-01-25 16:55:45 +00003089
3090 ResultType =
3091 SubstType(Proto->getReturnType(),
3092 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
3093 Function->getTypeSpecStartLoc(), Function->getDeclName());
Douglas Gregor3024f072012-04-16 07:05:22 +00003094 if (ResultType.isNull() || Trap.hasErrorOccurred())
3095 return TDK_SubstitutionFailure;
3096 }
John McCallc8e321d2016-03-01 02:09:25 +00003097
Richard Smith5e580292012-02-10 09:58:53 +00003098 // Instantiate the types of each of the function parameters given the
3099 // explicitly-specified template arguments if we didn't do so earlier.
3100 if (!Proto->hasTrailingReturn() &&
David Majnemer59f77922016-06-24 04:05:48 +00003101 SubstParmTypes(Function->getLocation(), Function->parameters(),
John McCallc8e321d2016-03-01 02:09:25 +00003102 Proto->getExtParameterInfosOrNull(),
Richard Smith5e580292012-02-10 09:58:53 +00003103 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
John McCallc8e321d2016-03-01 02:09:25 +00003104 ParamTypes, /*params*/ nullptr, ExtParamInfos))
Richard Smith5e580292012-02-10 09:58:53 +00003105 return TDK_SubstitutionFailure;
3106
Douglas Gregor9b146582009-07-08 20:55:45 +00003107 if (FunctionType) {
John McCallc8e321d2016-03-01 02:09:25 +00003108 auto EPI = Proto->getExtProtoInfo();
3109 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
Richard Smithcd198152017-06-07 21:46:22 +00003110
3111 // In C++1z onwards, exception specifications are part of the function type,
3112 // so substitution into the type must also substitute into the exception
3113 // specification.
3114 SmallVector<QualType, 4> ExceptionStorage;
Aaron Ballmanc351fba2017-12-04 20:27:34 +00003115 if (getLangOpts().CPlusPlus17 &&
Richard Smithcd198152017-06-07 21:46:22 +00003116 SubstExceptionSpec(
3117 Function->getLocation(), EPI.ExceptionSpec, ExceptionStorage,
3118 MultiLevelTemplateArgumentList(*ExplicitArgumentList)))
3119 return TDK_SubstitutionFailure;
3120
Jordan Rose5c382722013-03-08 21:51:21 +00003121 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00003122 Function->getLocation(),
Eli Friedmand8725a92010-08-05 02:54:05 +00003123 Function->getDeclName(),
John McCallc8e321d2016-03-01 02:09:25 +00003124 EPI);
Douglas Gregor9b146582009-07-08 20:55:45 +00003125 if (FunctionType->isNull() || Trap.hasErrorOccurred())
3126 return TDK_SubstitutionFailure;
3127 }
Mike Stump11289f42009-09-09 15:08:12 +00003128
Douglas Gregor9b146582009-07-08 20:55:45 +00003129 // C++ [temp.arg.explicit]p2:
Mike Stump11289f42009-09-09 15:08:12 +00003130 // Trailing template arguments that can be deduced (14.8.2) may be
3131 // omitted from the list of explicit template-arguments. If all of the
Douglas Gregor9b146582009-07-08 20:55:45 +00003132 // template arguments can be deduced, they may all be omitted; in this
3133 // case, the empty template argument list <> itself may also be omitted.
3134 //
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003135 // Take all of the explicitly-specified arguments and put them into
Richard Smith4a8f3512018-07-19 19:00:37 +00003136 // the set of deduced template arguments. The partially-substituted
3137 // parameter pack, however, will be set to NULL since the deduction
3138 // mechanism handles the partially-substituted argument pack directly.
Douglas Gregor9b146582009-07-08 20:55:45 +00003139 Deduced.reserve(TemplateParams->size());
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003140 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
3141 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
Richard Smith4a8f3512018-07-19 19:00:37 +00003142 if (I == PartiallySubstitutedPackIndex)
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003143 Deduced.push_back(DeducedTemplateArgument());
3144 else
3145 Deduced.push_back(Arg);
3146 }
Mike Stump11289f42009-09-09 15:08:12 +00003147
Douglas Gregor9b146582009-07-08 20:55:45 +00003148 return TDK_Success;
3149}
3150
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003151/// Check whether the deduced argument type for a call to a function
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003152/// template matches the actual argument type per C++ [temp.deduct.call]p4.
Richard Smithb1efc9b2017-08-30 00:44:08 +00003153static Sema::TemplateDeductionResult
3154CheckOriginalCallArgDeduction(Sema &S, TemplateDeductionInfo &Info,
3155 Sema::OriginalCallArg OriginalArg,
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003156 QualType DeducedA) {
3157 ASTContext &Context = S.Context;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003158
Richard Smithb1efc9b2017-08-30 00:44:08 +00003159 auto Failed = [&]() -> Sema::TemplateDeductionResult {
3160 Info.FirstArg = TemplateArgument(DeducedA);
3161 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3162 Info.CallArgIndex = OriginalArg.ArgIdx;
3163 return OriginalArg.DecomposedParam ? Sema::TDK_DeducedMismatchNested
3164 : Sema::TDK_DeducedMismatch;
3165 };
3166
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003167 QualType A = OriginalArg.OriginalArgType;
3168 QualType OriginalParamType = OriginalArg.OriginalParamType;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003169
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003170 // Check for type equality (top-level cv-qualifiers are ignored).
3171 if (Context.hasSameUnqualifiedType(A, DeducedA))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003172 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003173
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003174 // Strip off references on the argument types; they aren't needed for
3175 // the following checks.
3176 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
3177 DeducedA = DeducedARef->getPointeeType();
3178 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3179 A = ARef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003180
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003181 // C++ [temp.deduct.call]p4:
3182 // [...] However, there are three cases that allow a difference:
Simon Pilgrim728134c2016-08-12 11:43:57 +00003183 // - If the original P is a reference type, the deduced A (i.e., the
3184 // type referred to by the reference) can be more cv-qualified than
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003185 // the transformed A.
3186 if (const ReferenceType *OriginalParamRef
3187 = OriginalParamType->getAs<ReferenceType>()) {
3188 // We don't want to keep the reference around any more.
3189 OriginalParamType = OriginalParamRef->getPointeeType();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003190
Richard Smith1be59c52016-10-22 01:32:19 +00003191 // FIXME: Resolve core issue (no number yet): if the original P is a
3192 // reference type and the transformed A is function type "noexcept F",
3193 // the deduced A can be F.
3194 QualType Tmp;
3195 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003196 return Sema::TDK_Success;
Richard Smith1be59c52016-10-22 01:32:19 +00003197
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003198 Qualifiers AQuals = A.getQualifiers();
3199 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
Douglas Gregora906ad22012-07-18 00:14:59 +00003200
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003201 // Under Objective-C++ ARC, the deduced type may have implicitly
3202 // been given strong or (when dealing with a const reference)
3203 // unsafe_unretained lifetime. If so, update the original
3204 // qualifiers to include this lifetime.
Douglas Gregora906ad22012-07-18 00:14:59 +00003205 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregorc9f019a2013-11-08 02:04:24 +00003206 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
3207 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
3208 (DeducedAQuals.hasConst() &&
3209 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
3210 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
Douglas Gregora906ad22012-07-18 00:14:59 +00003211 }
3212
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003213 if (AQuals == DeducedAQuals) {
3214 // Qualifiers match; there's nothing to do.
3215 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
Richard Smithb1efc9b2017-08-30 00:44:08 +00003216 return Failed();
Simon Pilgrim728134c2016-08-12 11:43:57 +00003217 } else {
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003218 // Qualifiers are compatible, so have the argument type adopt the
3219 // deduced argument type's qualifiers as if we had performed the
3220 // qualification conversion.
3221 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3222 }
3223 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003224
3225 // - The transformed A can be another pointer or pointer to member
Richard Smith3c4f8d22016-10-16 17:54:23 +00003226 // type that can be converted to the deduced A via a function pointer
3227 // conversion and/or a qualification conversion.
Chandler Carruth53e61b02011-06-18 01:19:03 +00003228 //
Richard Smith1be59c52016-10-22 01:32:19 +00003229 // Also allow conversions which merely strip __attribute__((noreturn)) from
3230 // function types (recursively).
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003231 bool ObjCLifetimeConversion = false;
Chandler Carruth53e61b02011-06-18 01:19:03 +00003232 QualType ResultTy;
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003233 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
Chandler Carruth53e61b02011-06-18 01:19:03 +00003234 (S.IsQualificationConversion(A, DeducedA, false,
3235 ObjCLifetimeConversion) ||
Richard Smith3c4f8d22016-10-16 17:54:23 +00003236 S.IsFunctionConversion(A, DeducedA, ResultTy)))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003237 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003238
Simon Pilgrim728134c2016-08-12 11:43:57 +00003239 // - If P is a class and P has the form simple-template-id, then the
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003240 // transformed A can be a derived class of the deduced A. [...]
Simon Pilgrim728134c2016-08-12 11:43:57 +00003241 // [...] Likewise, if P is a pointer to a class of the form
3242 // simple-template-id, the transformed A can be a pointer to a
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003243 // derived class pointed to by the deduced A.
3244 if (const PointerType *OriginalParamPtr
3245 = OriginalParamType->getAs<PointerType>()) {
3246 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3247 if (const PointerType *APtr = A->getAs<PointerType>()) {
3248 if (A->getPointeeType()->isRecordType()) {
3249 OriginalParamType = OriginalParamPtr->getPointeeType();
3250 DeducedA = DeducedAPtr->getPointeeType();
3251 A = APtr->getPointeeType();
3252 }
3253 }
3254 }
3255 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003256
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003257 if (Context.hasSameUnqualifiedType(A, DeducedA))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003258 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003259
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003260 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
Richard Smith148bc6a2018-02-20 23:47:12 +00003261 S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
Richard Smithb1efc9b2017-08-30 00:44:08 +00003262 return Sema::TDK_Success;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003263
Richard Smithb1efc9b2017-08-30 00:44:08 +00003264 return Failed();
Douglas Gregor2ead4c42011-06-17 05:18:17 +00003265}
3266
Richard Smithc92d2062017-01-05 23:02:44 +00003267/// Find the pack index for a particular parameter index in an instantiation of
3268/// a function template with specific arguments.
3269///
3270/// \return The pack index for whichever pack produced this parameter, or -1
3271/// if this was not produced by a parameter. Intended to be used as the
3272/// ArgumentPackSubstitutionIndex for further substitutions.
3273// FIXME: We should track this in OriginalCallArgs so we don't need to
3274// reconstruct it here.
3275static unsigned getPackIndexForParam(Sema &S,
3276 FunctionTemplateDecl *FunctionTemplate,
3277 const MultiLevelTemplateArgumentList &Args,
3278 unsigned ParamIdx) {
3279 unsigned Idx = 0;
3280 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3281 if (PD->isParameterPack()) {
3282 unsigned NumExpansions =
3283 S.getNumArgumentsInExpansion(PD->getType(), Args).getValueOr(1);
3284 if (Idx + NumExpansions > ParamIdx)
3285 return ParamIdx - Idx;
3286 Idx += NumExpansions;
3287 } else {
3288 if (Idx == ParamIdx)
3289 return -1; // Not a pack expansion
3290 ++Idx;
3291 }
3292 }
3293
3294 llvm_unreachable("parameter index would not be produced from template");
3295}
3296
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003297/// Finish template argument deduction for a function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00003298/// checking the deduced template arguments for completeness and forming
3299/// the function template specialization.
Douglas Gregore65aacb2011-06-16 16:50:48 +00003300///
3301/// \param OriginalCallArgs If non-NULL, the original call arguments against
3302/// which the deduced argument types should be compared.
Richard Smith6eedfe72017-01-09 08:01:21 +00003303Sema::TemplateDeductionResult Sema::FinishTemplateArgumentDeduction(
3304 FunctionTemplateDecl *FunctionTemplate,
3305 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3306 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3307 TemplateDeductionInfo &Info,
3308 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3309 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
Eli Friedman77dcc722012-02-08 03:07:05 +00003310 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00003311 EnterExpressionEvaluationContext Unevaluated(
3312 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00003313 SFINAETrap Trap(*this);
3314
Douglas Gregor9b146582009-07-08 20:55:45 +00003315 // Enter a new template instantiation context while we instantiate the
3316 // actual function declaration.
Richard Smith80934652012-07-16 01:09:10 +00003317 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
Richard Smith696e3122017-02-23 01:43:54 +00003318 InstantiatingTemplate Inst(
3319 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3320 CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003321 if (Inst.isInvalid())
Mike Stump11289f42009-09-09 15:08:12 +00003322 return TDK_InstantiationDepth;
3323
John McCalle23b8712010-04-29 01:18:58 +00003324 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
John McCall80e58cd2010-04-29 00:35:03 +00003325
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003326 // C++ [temp.deduct.type]p2:
3327 // [...] or if any template argument remains neither deduced nor
3328 // explicitly specified, template argument deduction fails.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003329 SmallVector<TemplateArgument, 4> Builder;
Richard Smith1f5be4d2016-12-21 01:10:31 +00003330 if (auto Result = ConvertDeducedTemplateArguments(
Richard Smith87d263e2016-12-25 08:05:23 +00003331 *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder,
Richard Smith1f5be4d2016-12-21 01:10:31 +00003332 CurrentInstantiationScope, NumExplicitlySpecified,
3333 PartialOverloading))
3334 return Result;
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003335
Richard Smith6eedfe72017-01-09 08:01:21 +00003336 // C++ [temp.deduct.call]p10: [DR1391]
3337 // If deduction succeeds for all parameters that contain
3338 // template-parameters that participate in template argument deduction,
3339 // and all template arguments are explicitly specified, deduced, or
3340 // obtained from default template arguments, remaining parameters are then
3341 // compared with the corresponding arguments. For each remaining parameter
3342 // P with a type that was non-dependent before substitution of any
3343 // explicitly-specified template arguments, if the corresponding argument
3344 // A cannot be implicitly converted to P, deduction fails.
3345 if (CheckNonDependent())
3346 return TDK_NonDependentConversionFailure;
3347
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003348 // Form the template argument list from the deduced template arguments.
3349 TemplateArgumentList *DeducedArgumentList
David Majnemer8b622692016-07-03 21:17:51 +00003350 = TemplateArgumentList::CreateCopy(Context, Builder);
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00003351 Info.reset(DeducedArgumentList);
3352
Mike Stump11289f42009-09-09 15:08:12 +00003353 // Substitute the deduced template arguments into the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00003354 // declaration to produce the function template specialization.
Douglas Gregor16142372010-04-28 04:52:24 +00003355 DeclContext *Owner = FunctionTemplate->getDeclContext();
3356 if (FunctionTemplate->getFriendObjectKind())
3357 Owner = FunctionTemplate->getLexicalDeclContext();
Richard Smithc92d2062017-01-05 23:02:44 +00003358 MultiLevelTemplateArgumentList SubstArgs(*DeducedArgumentList);
Douglas Gregor9b146582009-07-08 20:55:45 +00003359 Specialization = cast_or_null<FunctionDecl>(
Richard Smithc92d2062017-01-05 23:02:44 +00003360 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, SubstArgs));
Douglas Gregorebcfbb52011-10-12 20:35:48 +00003361 if (!Specialization || Specialization->isInvalidDecl())
Douglas Gregor9b146582009-07-08 20:55:45 +00003362 return TDK_SubstitutionFailure;
Mike Stump11289f42009-09-09 15:08:12 +00003363
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003364 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
Douglas Gregor31fae892009-09-15 18:26:13 +00003365 FunctionTemplate->getCanonicalDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003366
Mike Stump11289f42009-09-09 15:08:12 +00003367 // If the template argument list is owned by the function template
Douglas Gregor9b146582009-07-08 20:55:45 +00003368 // specialization, release it.
Douglas Gregord09efd42010-05-08 20:07:26 +00003369 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
3370 !Trap.hasErrorOccurred())
Douglas Gregor9b146582009-07-08 20:55:45 +00003371 Info.take();
Mike Stump11289f42009-09-09 15:08:12 +00003372
Douglas Gregorebcfbb52011-10-12 20:35:48 +00003373 // There may have been an error that did not prevent us from constructing a
3374 // declaration. Mark the declaration invalid and return with a substitution
3375 // failure.
3376 if (Trap.hasErrorOccurred()) {
3377 Specialization->setInvalidDecl(true);
3378 return TDK_SubstitutionFailure;
3379 }
3380
Douglas Gregore65aacb2011-06-16 16:50:48 +00003381 if (OriginalCallArgs) {
3382 // C++ [temp.deduct.call]p4:
3383 // In general, the deduction process attempts to find template argument
Simon Pilgrim728134c2016-08-12 11:43:57 +00003384 // values that will make the deduced A identical to A (after the type A
Douglas Gregore65aacb2011-06-16 16:50:48 +00003385 // is transformed as described above). [...]
Richard Smithc92d2062017-01-05 23:02:44 +00003386 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
Douglas Gregore65aacb2011-06-16 16:50:48 +00003387 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
3388 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
Simon Pilgrim728134c2016-08-12 11:43:57 +00003389
Richard Smithc92d2062017-01-05 23:02:44 +00003390 auto ParamIdx = OriginalArg.ArgIdx;
Douglas Gregore65aacb2011-06-16 16:50:48 +00003391 if (ParamIdx >= Specialization->getNumParams())
Richard Smithc92d2062017-01-05 23:02:44 +00003392 // FIXME: This presumably means a pack ended up smaller than we
3393 // expected while deducing. Should this not result in deduction
3394 // failure? Can it even happen?
Douglas Gregore65aacb2011-06-16 16:50:48 +00003395 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003396
Richard Smithc92d2062017-01-05 23:02:44 +00003397 QualType DeducedA;
3398 if (!OriginalArg.DecomposedParam) {
3399 // P is one of the function parameters, just look up its substituted
3400 // type.
3401 DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
3402 } else {
3403 // P is a decomposed element of a parameter corresponding to a
3404 // braced-init-list argument. Substitute back into P to find the
3405 // deduced A.
3406 QualType &CacheEntry =
3407 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
3408 if (CacheEntry.isNull()) {
3409 ArgumentPackSubstitutionIndexRAII PackIndex(
3410 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
3411 ParamIdx));
3412 CacheEntry =
3413 SubstType(OriginalArg.OriginalParamType, SubstArgs,
3414 Specialization->getTypeSpecStartLoc(),
3415 Specialization->getDeclName());
3416 }
3417 DeducedA = CacheEntry;
3418 }
3419
Richard Smithb1efc9b2017-08-30 00:44:08 +00003420 if (auto TDK =
3421 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA))
3422 return TDK;
Douglas Gregore65aacb2011-06-16 16:50:48 +00003423 }
3424 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003425
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003426 // If we suppressed any diagnostics while performing template argument
3427 // deduction, and if we haven't already instantiated this declaration,
3428 // keep track of these diagnostics. They'll be emitted if this specialization
3429 // is actually used.
3430 if (Info.diag_begin() != Info.diag_end()) {
Craig Topper79be4cd2013-07-05 04:33:53 +00003431 SuppressedDiagnosticsMap::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003432 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
3433 if (Pos == SuppressedDiagnostics.end())
3434 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
3435 .append(Info.diag_begin(), Info.diag_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003436 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003437
Mike Stump11289f42009-09-09 15:08:12 +00003438 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00003439}
3440
John McCall8d08b9b2010-08-27 09:08:28 +00003441/// Gets the type of a function for template-argument-deducton
3442/// purposes when it's considered as part of an overload set.
Richard Smith2a7d4812013-05-04 07:00:32 +00003443static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
John McCallc1f69982010-02-02 02:21:27 +00003444 FunctionDecl *Fn) {
Richard Smith2a7d4812013-05-04 07:00:32 +00003445 // We may need to deduce the return type of the function now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003446 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
Alp Toker314cc812014-01-25 16:55:45 +00003447 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00003448 return {};
Richard Smith2a7d4812013-05-04 07:00:32 +00003449
John McCallc1f69982010-02-02 02:21:27 +00003450 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
John McCall8d08b9b2010-08-27 09:08:28 +00003451 if (Method->isInstance()) {
3452 // An instance method that's referenced in a form that doesn't
3453 // look like a member pointer is just invalid.
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00003454 if (!R.HasFormOfMemberPointer)
3455 return {};
John McCall8d08b9b2010-08-27 09:08:28 +00003456
Richard Smith2a7d4812013-05-04 07:00:32 +00003457 return S.Context.getMemberPointerType(Fn->getType(),
3458 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00003459 }
3460
3461 if (!R.IsAddressOfOperand) return Fn->getType();
Richard Smith2a7d4812013-05-04 07:00:32 +00003462 return S.Context.getPointerType(Fn->getType());
John McCallc1f69982010-02-02 02:21:27 +00003463}
3464
3465/// Apply the deduction rules for overload sets.
3466///
3467/// \return the null type if this argument should be treated as an
3468/// undeduced context
3469static QualType
3470ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003471 Expr *Arg, QualType ParamType,
3472 bool ParamWasReference) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003473
John McCall8d08b9b2010-08-27 09:08:28 +00003474 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
John McCallc1f69982010-02-02 02:21:27 +00003475
John McCall8d08b9b2010-08-27 09:08:28 +00003476 OverloadExpr *Ovl = R.Expression;
John McCallc1f69982010-02-02 02:21:27 +00003477
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003478 // C++0x [temp.deduct.call]p4
3479 unsigned TDF = 0;
3480 if (ParamWasReference)
3481 TDF |= TDF_ParamWithReferenceType;
3482 if (R.IsAddressOfOperand)
3483 TDF |= TDF_IgnoreQualifiers;
3484
John McCallc1f69982010-02-02 02:21:27 +00003485 // C++0x [temp.deduct.call]p6:
3486 // When P is a function type, pointer to function type, or pointer
3487 // to member function type:
3488
3489 if (!ParamType->isFunctionType() &&
3490 !ParamType->isFunctionPointerType() &&
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003491 !ParamType->isMemberFunctionPointerType()) {
3492 if (Ovl->hasExplicitTemplateArgs()) {
3493 // But we can still look for an explicit specialization.
3494 if (FunctionDecl *ExplicitSpec
3495 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
Richard Smith2a7d4812013-05-04 07:00:32 +00003496 return GetTypeOfFunction(S, R, ExplicitSpec);
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003497 }
John McCallc1f69982010-02-02 02:21:27 +00003498
George Burgess IVcc2f3552016-03-19 21:51:45 +00003499 DeclAccessPair DAP;
3500 if (FunctionDecl *Viable =
3501 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3502 return GetTypeOfFunction(S, R, Viable);
3503
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00003504 return {};
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003505 }
Simon Pilgrim728134c2016-08-12 11:43:57 +00003506
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003507 // Gather the explicit template arguments, if any.
3508 TemplateArgumentListInfo ExplicitTemplateArgs;
3509 if (Ovl->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003510 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
John McCallc1f69982010-02-02 02:21:27 +00003511 QualType Match;
John McCall1acbbb52010-02-02 06:20:04 +00003512 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3513 E = Ovl->decls_end(); I != E; ++I) {
John McCallc1f69982010-02-02 02:21:27 +00003514 NamedDecl *D = (*I)->getUnderlyingDecl();
3515
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003516 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3517 // - If the argument is an overload set containing one or more
3518 // function templates, the parameter is treated as a
3519 // non-deduced context.
3520 if (!Ovl->hasExplicitTemplateArgs())
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00003521 return {};
Simon Pilgrim728134c2016-08-12 11:43:57 +00003522
3523 // Otherwise, see if we can resolve a function type
Craig Topperc3ec1492014-05-26 06:22:03 +00003524 FunctionDecl *Specialization = nullptr;
Craig Toppere6706e42012-09-19 02:26:47 +00003525 TemplateDeductionInfo Info(Ovl->getNameLoc());
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003526 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3527 Specialization, Info))
3528 continue;
Simon Pilgrim728134c2016-08-12 11:43:57 +00003529
Douglas Gregor8409ccd2012-03-12 21:09:16 +00003530 D = Specialization;
3531 }
John McCallc1f69982010-02-02 02:21:27 +00003532
3533 FunctionDecl *Fn = cast<FunctionDecl>(D);
Richard Smith2a7d4812013-05-04 07:00:32 +00003534 QualType ArgType = GetTypeOfFunction(S, R, Fn);
John McCall8d08b9b2010-08-27 09:08:28 +00003535 if (ArgType.isNull()) continue;
John McCallc1f69982010-02-02 02:21:27 +00003536
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003537 // Function-to-pointer conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003538 if (!ParamWasReference && ParamType->isPointerType() &&
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003539 ArgType->isFunctionType())
3540 ArgType = S.Context.getPointerType(ArgType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003541
John McCallc1f69982010-02-02 02:21:27 +00003542 // - If the argument is an overload set (not containing function
3543 // templates), trial argument deduction is attempted using each
3544 // of the members of the set. If deduction succeeds for only one
3545 // of the overload set members, that member is used as the
3546 // argument value for the deduction. If deduction succeeds for
3547 // more than one member of the overload set the parameter is
3548 // treated as a non-deduced context.
3549
3550 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3551 // Type deduction is done independently for each P/A pair, and
3552 // the deduced template argument values are then combined.
3553 // So we do not reject deductions which were made elsewhere.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003554 SmallVector<DeducedTemplateArgument, 8>
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003555 Deduced(TemplateParams->size());
Craig Toppere6706e42012-09-19 02:26:47 +00003556 TemplateDeductionInfo Info(Ovl->getNameLoc());
John McCallc1f69982010-02-02 02:21:27 +00003557 Sema::TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00003558 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3559 ArgType, Info, Deduced, TDF);
John McCallc1f69982010-02-02 02:21:27 +00003560 if (Result) continue;
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00003561 if (!Match.isNull())
3562 return {};
John McCallc1f69982010-02-02 02:21:27 +00003563 Match = ArgType;
3564 }
3565
3566 return Match;
3567}
3568
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003569/// Perform the adjustments to the parameter and argument types
Douglas Gregor7825bf32011-01-06 22:09:01 +00003570/// described in C++ [temp.deduct.call].
3571///
3572/// \returns true if the caller should not attempt to perform any template
Richard Smith8c6eeb92013-01-31 04:03:12 +00003573/// argument deduction based on this P/A pair because the argument is an
3574/// overloaded function set that could not be resolved.
Richard Smith32918772017-02-14 00:25:28 +00003575static bool AdjustFunctionParmAndArgTypesForDeduction(
3576 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3577 QualType &ParamType, QualType &ArgType, Expr *Arg, unsigned &TDF) {
Douglas Gregor7825bf32011-01-06 22:09:01 +00003578 // C++0x [temp.deduct.call]p3:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003579 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
Douglas Gregor7825bf32011-01-06 22:09:01 +00003580 // are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003581 if (ParamType.hasQualifiers())
3582 ParamType = ParamType.getUnqualifiedType();
Nathan Sidwell96090022015-01-16 15:20:14 +00003583
3584 // [...] If P is a reference type, the type referred to by P is
3585 // used for type deduction.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003586 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
Nathan Sidwell96090022015-01-16 15:20:14 +00003587 if (ParamRefType)
3588 ParamType = ParamRefType->getPointeeType();
Richard Smith30482bc2011-02-20 03:19:35 +00003589
Nathan Sidwell96090022015-01-16 15:20:14 +00003590 // Overload sets usually make this parameter an undeduced context,
3591 // but there are sometimes special circumstances. Typically
3592 // involving a template-id-expr.
Douglas Gregor7825bf32011-01-06 22:09:01 +00003593 if (ArgType == S.Context.OverloadTy) {
3594 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3595 Arg, ParamType,
Craig Topperc3ec1492014-05-26 06:22:03 +00003596 ParamRefType != nullptr);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003597 if (ArgType.isNull())
3598 return true;
3599 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003600
Douglas Gregor7825bf32011-01-06 22:09:01 +00003601 if (ParamRefType) {
Nathan Sidwell96090022015-01-16 15:20:14 +00003602 // If the argument has incomplete array type, try to complete its type.
Richard Smithdb0ac552015-12-18 22:40:25 +00003603 if (ArgType->isIncompleteArrayType()) {
3604 S.completeExprArrayBound(Arg);
Nathan Sidwell96090022015-01-16 15:20:14 +00003605 ArgType = Arg->getType();
Richard Smithdb0ac552015-12-18 22:40:25 +00003606 }
Nathan Sidwell96090022015-01-16 15:20:14 +00003607
Richard Smith32918772017-02-14 00:25:28 +00003608 // C++1z [temp.deduct.call]p3:
3609 // If P is a forwarding reference and the argument is an lvalue, the type
3610 // "lvalue reference to A" is used in place of A for type deduction.
3611 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
Douglas Gregor7825bf32011-01-06 22:09:01 +00003612 Arg->isLValue())
3613 ArgType = S.Context.getLValueReferenceType(ArgType);
3614 } else {
3615 // C++ [temp.deduct.call]p2:
3616 // If P is not a reference type:
3617 // - If A is an array type, the pointer type produced by the
3618 // array-to-pointer standard conversion (4.2) is used in place of
3619 // A for type deduction; otherwise,
3620 if (ArgType->isArrayType())
3621 ArgType = S.Context.getArrayDecayedType(ArgType);
3622 // - If A is a function type, the pointer type produced by the
3623 // function-to-pointer standard conversion (4.3) is used in place
3624 // of A for type deduction; otherwise,
3625 else if (ArgType->isFunctionType())
3626 ArgType = S.Context.getPointerType(ArgType);
3627 else {
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003628 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
Douglas Gregor7825bf32011-01-06 22:09:01 +00003629 // type are ignored for type deduction.
Douglas Gregor17846882011-04-27 23:34:22 +00003630 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003631 }
3632 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003633
Douglas Gregor7825bf32011-01-06 22:09:01 +00003634 // C++0x [temp.deduct.call]p4:
3635 // In general, the deduction process attempts to find template argument
3636 // values that will make the deduced A identical to A (after the type A
3637 // is transformed as described above). [...]
3638 TDF = TDF_SkipNonDependent;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003639
Douglas Gregor7825bf32011-01-06 22:09:01 +00003640 // - If the original P is a reference type, the deduced A (i.e., the
3641 // type referred to by the reference) can be more cv-qualified than
3642 // the transformed A.
3643 if (ParamRefType)
3644 TDF |= TDF_ParamWithReferenceType;
3645 // - The transformed A can be another pointer or pointer to member
3646 // type that can be converted to the deduced A via a qualification
3647 // conversion (4.4).
3648 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3649 ArgType->isObjCObjectPointerType())
3650 TDF |= TDF_IgnoreQualifiers;
3651 // - If P is a class and P has the form simple-template-id, then the
3652 // transformed A can be a derived class of the deduced A. Likewise,
3653 // if P is a pointer to a class of the form simple-template-id, the
3654 // transformed A can be a pointer to a derived class pointed to by
3655 // the deduced A.
3656 if (isSimpleTemplateIdType(ParamType) ||
3657 (isa<PointerType>(ParamType) &&
3658 isSimpleTemplateIdType(
3659 ParamType->getAs<PointerType>()->getPointeeType())))
3660 TDF |= TDF_DerivedClass;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003661
Douglas Gregor7825bf32011-01-06 22:09:01 +00003662 return false;
3663}
3664
Richard Smithf0393bf2017-02-16 04:22:56 +00003665static bool
3666hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3667 QualType T);
Douglas Gregore65aacb2011-06-16 16:50:48 +00003668
Richard Smith707eab62017-01-05 04:08:31 +00003669static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003670 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3671 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
Richard Smith707eab62017-01-05 04:08:31 +00003672 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3673 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
Richard Smithc92d2062017-01-05 23:02:44 +00003674 bool DecomposedParam, unsigned ArgIdx, unsigned TDF);
Hubert Tong3280b332015-06-25 00:25:49 +00003675
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003676/// Attempt template argument deduction from an initializer list
Hubert Tong3280b332015-06-25 00:25:49 +00003677/// deemed to be an argument in a function call.
Richard Smith707eab62017-01-05 04:08:31 +00003678static Sema::TemplateDeductionResult DeduceFromInitializerList(
3679 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
3680 InitListExpr *ILE, TemplateDeductionInfo &Info,
3681 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00003682 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
3683 unsigned TDF) {
Richard Smitha7d5ec92017-01-04 19:47:19 +00003684 // C++ [temp.deduct.call]p1: (CWG 1591)
3685 // If removing references and cv-qualifiers from P gives
3686 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
3687 // a non-empty initializer list, then deduction is performed instead for
3688 // each element of the initializer list, taking P0 as a function template
3689 // parameter type and the initializer element as its argument
3690 //
Richard Smith707eab62017-01-05 04:08:31 +00003691 // We've already removed references and cv-qualifiers here.
Richard Smith9c5534c2017-01-05 04:16:30 +00003692 if (!ILE->getNumInits())
3693 return Sema::TDK_Success;
3694
Richard Smitha7d5ec92017-01-04 19:47:19 +00003695 QualType ElTy;
3696 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
3697 if (ArrTy)
3698 ElTy = ArrTy->getElementType();
3699 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
3700 // Otherwise, an initializer list argument causes the parameter to be
3701 // considered a non-deduced context
3702 return Sema::TDK_Success;
Hubert Tong3280b332015-06-25 00:25:49 +00003703 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003704
Faisal Valif6dfdb32015-12-10 05:36:39 +00003705 // Deduction only needs to be done for dependent types.
3706 if (ElTy->isDependentType()) {
3707 for (Expr *E : ILE->inits()) {
Richard Smith707eab62017-01-05 04:08:31 +00003708 if (auto Result = DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003709 S, TemplateParams, 0, ElTy, E, Info, Deduced, OriginalCallArgs, true,
Richard Smithc92d2062017-01-05 23:02:44 +00003710 ArgIdx, TDF))
Richard Smitha7d5ec92017-01-04 19:47:19 +00003711 return Result;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003712 }
3713 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003714
3715 // in the P0[N] case, if N is a non-type template parameter, N is deduced
3716 // from the length of the initializer list.
Richard Smitha7d5ec92017-01-04 19:47:19 +00003717 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003718 // Determine the array bound is something we can deduce.
3719 if (NonTypeTemplateParmDecl *NTTP =
Richard Smitha7d5ec92017-01-04 19:47:19 +00003720 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
Faisal Valif6dfdb32015-12-10 05:36:39 +00003721 // We can perform template argument deduction for the given non-type
3722 // template parameter.
Richard Smith7fa88bb2017-02-21 07:22:31 +00003723 // C++ [temp.deduct.type]p13:
3724 // The type of N in the type T[N] is std::size_t.
3725 QualType T = S.Context.getSizeType();
3726 llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
Richard Smitha7d5ec92017-01-04 19:47:19 +00003727 if (auto Result = DeduceNonTypeTemplateArgument(
Richard Smith7fa88bb2017-02-21 07:22:31 +00003728 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
Richard Smitha7d5ec92017-01-04 19:47:19 +00003729 /*ArrayBound=*/true, Info, Deduced))
3730 return Result;
Faisal Valif6dfdb32015-12-10 05:36:39 +00003731 }
3732 }
Richard Smitha7d5ec92017-01-04 19:47:19 +00003733
3734 return Sema::TDK_Success;
Hubert Tong3280b332015-06-25 00:25:49 +00003735}
3736
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003737/// Perform template argument deduction per [temp.deduct.call] for a
Richard Smith707eab62017-01-05 04:08:31 +00003738/// single parameter / argument pair.
3739static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003740 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3741 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
Richard Smith707eab62017-01-05 04:08:31 +00003742 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3743 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
Richard Smithc92d2062017-01-05 23:02:44 +00003744 bool DecomposedParam, unsigned ArgIdx, unsigned TDF) {
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003745 QualType ArgType = Arg->getType();
Richard Smith707eab62017-01-05 04:08:31 +00003746 QualType OrigParamType = ParamType;
3747
3748 // If P is a reference type [...]
3749 // If P is a cv-qualified type [...]
Richard Smith32918772017-02-14 00:25:28 +00003750 if (AdjustFunctionParmAndArgTypesForDeduction(
3751 S, TemplateParams, FirstInnerIndex, ParamType, ArgType, Arg, TDF))
Richard Smith363ae812017-01-04 22:03:59 +00003752 return Sema::TDK_Success;
3753
Richard Smith707eab62017-01-05 04:08:31 +00003754 // If [...] the argument is a non-empty initializer list [...]
3755 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg))
3756 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
Richard Smithc92d2062017-01-05 23:02:44 +00003757 Deduced, OriginalCallArgs, ArgIdx, TDF);
Richard Smith707eab62017-01-05 04:08:31 +00003758
3759 // [...] the deduction process attempts to find template argument values
3760 // that will make the deduced A identical to A
3761 //
3762 // Keep track of the argument type and corresponding parameter index,
3763 // so we can check for compatibility between the deduced A and A.
Richard Smithc92d2062017-01-05 23:02:44 +00003764 OriginalCallArgs.push_back(
3765 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
Sebastian Redl19181662012-03-15 21:40:51 +00003766 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
Douglas Gregor0e60cd72012-04-04 05:10:53 +00003767 ArgType, Info, Deduced, TDF);
Sebastian Redl19181662012-03-15 21:40:51 +00003768}
3769
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003770/// Perform template argument deduction from a function call
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003771/// (C++ [temp.deduct.call]).
3772///
3773/// \param FunctionTemplate the function template for which we are performing
3774/// template argument deduction.
3775///
James Dennett18348b62012-06-22 08:52:37 +00003776/// \param ExplicitTemplateArgs the explicit template arguments provided
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003777/// for this call.
Douglas Gregor89026b52009-06-30 23:57:56 +00003778///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003779/// \param Args the function call arguments
3780///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003781/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00003782/// this will be set to the function template specialization produced by
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003783/// template argument deduction.
3784///
3785/// \param Info the argument will be updated to provide additional information
3786/// about template argument deduction.
3787///
Richard Smith6eedfe72017-01-09 08:01:21 +00003788/// \param CheckNonDependent A callback to invoke to check conversions for
3789/// non-dependent parameters, between deduction and substitution, per DR1391.
3790/// If this returns true, substitution will be skipped and we return
3791/// TDK_NonDependentConversionFailure. The callback is passed the parameter
3792/// types (after substituting explicit template arguments).
3793///
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003794/// \returns the result of template argument deduction.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00003795Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3796 FunctionTemplateDecl *FunctionTemplate,
3797 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003798 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
Richard Smith6eedfe72017-01-09 08:01:21 +00003799 bool PartialOverloading,
3800 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00003801 if (FunctionTemplate->isInvalidDecl())
3802 return TDK_Invalid;
3803
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003804 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003805 unsigned NumParams = Function->getNumParams();
Douglas Gregor89026b52009-06-30 23:57:56 +00003806
Richard Smith32918772017-02-14 00:25:28 +00003807 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
3808
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003809 // C++ [temp.deduct.call]p1:
3810 // Template argument deduction is done by comparing each function template
3811 // parameter type (call it P) with the type of the corresponding argument
3812 // of the call (call it A) as described below.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003813 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003814 return TDK_TooFewArguments;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003815 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
Mike Stump11289f42009-09-09 15:08:12 +00003816 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00003817 = Function->getType()->getAs<FunctionProtoType>();
Douglas Gregor7825bf32011-01-06 22:09:01 +00003818 if (Proto->isTemplateVariadic())
3819 /* Do nothing */;
Richard Smithde0d34a2017-01-09 07:14:40 +00003820 else if (!Proto->isVariadic())
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003821 return TDK_TooManyArguments;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003822 }
Mike Stump11289f42009-09-09 15:08:12 +00003823
Douglas Gregor89026b52009-06-30 23:57:56 +00003824 // The types of the parameters from which we will perform template argument
3825 // deduction.
John McCall19c1bfd2010-08-25 05:32:35 +00003826 LocalInstantiationScope InstScope(*this);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003827 TemplateParameterList *TemplateParams
3828 = FunctionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003829 SmallVector<DeducedTemplateArgument, 4> Deduced;
Richard Smith6eedfe72017-01-09 08:01:21 +00003830 SmallVector<QualType, 8> ParamTypes;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003831 unsigned NumExplicitlySpecified = 0;
John McCall6b51f282009-11-23 01:53:49 +00003832 if (ExplicitTemplateArgs) {
Douglas Gregor9b146582009-07-08 20:55:45 +00003833 TemplateDeductionResult Result =
3834 SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00003835 *ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00003836 Deduced,
3837 ParamTypes,
Craig Topperc3ec1492014-05-26 06:22:03 +00003838 nullptr,
Douglas Gregor9b146582009-07-08 20:55:45 +00003839 Info);
3840 if (Result)
3841 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003842
3843 NumExplicitlySpecified = Deduced.size();
Douglas Gregor89026b52009-06-30 23:57:56 +00003844 } else {
3845 // Just fill in the parameter types from the function declaration.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003846 for (unsigned I = 0; I != NumParams; ++I)
Douglas Gregor89026b52009-06-30 23:57:56 +00003847 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3848 }
Mike Stump11289f42009-09-09 15:08:12 +00003849
Richard Smith6eedfe72017-01-09 08:01:21 +00003850 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
Richard Smitha7d5ec92017-01-04 19:47:19 +00003851
3852 // Deduce an argument of type ParamType from an expression with index ArgIdx.
3853 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx) {
Richard Smith707eab62017-01-05 04:08:31 +00003854 // C++ [demp.deduct.call]p1: (DR1391)
3855 // Template argument deduction is done by comparing each function template
3856 // parameter that contains template-parameters that participate in
3857 // template argument deduction ...
Richard Smithf0393bf2017-02-16 04:22:56 +00003858 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
Richard Smitha7d5ec92017-01-04 19:47:19 +00003859 return Sema::TDK_Success;
3860
Richard Smith707eab62017-01-05 04:08:31 +00003861 // ... with the type of the corresponding argument
3862 return DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00003863 *this, TemplateParams, FirstInnerIndex, ParamType, Args[ArgIdx], Info, Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00003864 OriginalCallArgs, /*Decomposed*/false, ArgIdx, /*TDF*/ 0);
Richard Smitha7d5ec92017-01-04 19:47:19 +00003865 };
3866
Douglas Gregor89026b52009-06-30 23:57:56 +00003867 // Deduce template arguments from the function parameters.
Mike Stump11289f42009-09-09 15:08:12 +00003868 Deduced.resize(TemplateParams->size());
Richard Smith6eedfe72017-01-09 08:01:21 +00003869 SmallVector<QualType, 8> ParamTypesForArgChecking;
Richard Smitha7d5ec92017-01-04 19:47:19 +00003870 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00003871 ParamIdx != NumParamTypes; ++ParamIdx) {
Richard Smitha7d5ec92017-01-04 19:47:19 +00003872 QualType ParamType = ParamTypes[ParamIdx];
Simon Pilgrim728134c2016-08-12 11:43:57 +00003873
Richard Smitha7d5ec92017-01-04 19:47:19 +00003874 const PackExpansionType *ParamExpansion =
3875 dyn_cast<PackExpansionType>(ParamType);
Douglas Gregor7825bf32011-01-06 22:09:01 +00003876 if (!ParamExpansion) {
3877 // Simple case: matching a function parameter to a function argument.
Richard Smithde0d34a2017-01-09 07:14:40 +00003878 if (ArgIdx >= Args.size())
Douglas Gregor7825bf32011-01-06 22:09:01 +00003879 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003880
Richard Smith6eedfe72017-01-09 08:01:21 +00003881 ParamTypesForArgChecking.push_back(ParamType);
Richard Smitha7d5ec92017-01-04 19:47:19 +00003882 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++))
Douglas Gregor7825bf32011-01-06 22:09:01 +00003883 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00003884
Douglas Gregor7825bf32011-01-06 22:09:01 +00003885 continue;
Douglas Gregor66d2c8e2010-08-30 21:04:23 +00003886 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003887
Richard Smithde0d34a2017-01-09 07:14:40 +00003888 QualType ParamPattern = ParamExpansion->getPattern();
3889 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3890 ParamPattern);
3891
Douglas Gregor7825bf32011-01-06 22:09:01 +00003892 // C++0x [temp.deduct.call]p1:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003893 // For a function parameter pack that occurs at the end of the
3894 // parameter-declaration-list, the type A of each remaining argument of
3895 // the call is compared with the type P of the declarator-id of the
3896 // function parameter pack. Each comparison deduces template arguments
3897 // for subsequent positions in the template parameter packs expanded by
Richard Smithde0d34a2017-01-09 07:14:40 +00003898 // the function parameter pack. When a function parameter pack appears
3899 // in a non-deduced context [not at the end of the list], the type of
3900 // that parameter pack is never deduced.
3901 //
3902 // FIXME: The above rule allows the size of the parameter pack to change
3903 // after we skip it (in the non-deduced case). That makes no sense, so
3904 // we instead notionally deduce the pack against N arguments, where N is
3905 // the length of the explicitly-specified pack if it's expanded by the
3906 // parameter pack and 0 otherwise, and we treat each deduction as a
3907 // non-deduced context.
Richard Smith4a8f3512018-07-19 19:00:37 +00003908 if (ParamIdx + 1 == NumParamTypes || PackScope.hasFixedArity()) {
3909 for (; ArgIdx < Args.size() && PackScope.hasNextElement();
3910 PackScope.nextPackElement(), ++ArgIdx) {
Richard Smith6eedfe72017-01-09 08:01:21 +00003911 ParamTypesForArgChecking.push_back(ParamPattern);
Richard Smithde0d34a2017-01-09 07:14:40 +00003912 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx))
3913 return Result;
Richard Smith6eedfe72017-01-09 08:01:21 +00003914 }
Richard Smithde0d34a2017-01-09 07:14:40 +00003915 } else {
3916 // If the parameter type contains an explicitly-specified pack that we
3917 // could not expand, skip the number of parameters notionally created
3918 // by the expansion.
3919 Optional<unsigned> NumExpansions = ParamExpansion->getNumExpansions();
Richard Smith6eedfe72017-01-09 08:01:21 +00003920 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
Richard Smithde0d34a2017-01-09 07:14:40 +00003921 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
Richard Smith6eedfe72017-01-09 08:01:21 +00003922 ++I, ++ArgIdx) {
3923 ParamTypesForArgChecking.push_back(ParamPattern);
Richard Smithde0d34a2017-01-09 07:14:40 +00003924 // FIXME: Should we add OriginalCallArgs for these? What if the
3925 // corresponding argument is a list?
3926 PackScope.nextPackElement();
Richard Smith6eedfe72017-01-09 08:01:21 +00003927 }
3928 }
Richard Smithde0d34a2017-01-09 07:14:40 +00003929 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003930
Douglas Gregor7825bf32011-01-06 22:09:01 +00003931 // Build argument packs for each of the parameter packs expanded by this
3932 // pack expansion.
Richard Smith539e8e32017-01-04 01:48:55 +00003933 if (auto Result = PackScope.finish())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003934 return Result;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003935 }
Douglas Gregor05155d82009-08-21 23:19:43 +00003936
Akira Hatanaka4ac16db2018-06-13 05:26:23 +00003937 // Capture the context in which the function call is made. This is the context
3938 // that is needed when the accessibility of template arguments is checked.
3939 DeclContext *CallingCtx = CurContext;
3940
Richard Smith6eedfe72017-01-09 08:01:21 +00003941 return FinishTemplateArgumentDeduction(
3942 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
Akira Hatanaka4ac16db2018-06-13 05:26:23 +00003943 &OriginalCallArgs, PartialOverloading, [&, CallingCtx]() {
3944 ContextRAII SavedContext(*this, CallingCtx);
3945 return CheckNonDependent(ParamTypesForArgChecking);
3946 });
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003947}
3948
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003949QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
Richard Smithbaa47832016-12-01 02:11:49 +00003950 QualType FunctionType,
3951 bool AdjustExceptionSpec) {
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003952 if (ArgFunctionType.isNull())
3953 return ArgFunctionType;
3954
3955 const FunctionProtoType *FunctionTypeP =
3956 FunctionType->castAs<FunctionProtoType>();
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003957 const FunctionProtoType *ArgFunctionTypeP =
3958 ArgFunctionType->getAs<FunctionProtoType>();
Richard Smithbaa47832016-12-01 02:11:49 +00003959
3960 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
3961 bool Rebuild = false;
3962
3963 CallingConv CC = FunctionTypeP->getCallConv();
3964 if (EPI.ExtInfo.getCC() != CC) {
3965 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
3966 Rebuild = true;
3967 }
3968
3969 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3970 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
3971 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
3972 Rebuild = true;
3973 }
3974
3975 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
3976 ArgFunctionTypeP->hasExceptionSpec())) {
3977 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
3978 Rebuild = true;
3979 }
3980
3981 if (!Rebuild)
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003982 return ArgFunctionType;
3983
Richard Smithbaa47832016-12-01 02:11:49 +00003984 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
3985 ArgFunctionTypeP->getParamTypes(), EPI);
Rafael Espindola6edca7d2013-12-01 16:54:29 +00003986}
3987
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003988/// Deduce template arguments when taking the address of a function
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003989/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3990/// a template.
Douglas Gregor9b146582009-07-08 20:55:45 +00003991///
3992/// \param FunctionTemplate the function template for which we are performing
3993/// template argument deduction.
3994///
James Dennett18348b62012-06-22 08:52:37 +00003995/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00003996/// arguments.
Douglas Gregor9b146582009-07-08 20:55:45 +00003997///
3998/// \param ArgFunctionType the function type that will be used as the
3999/// "argument" type (A) when performing template argument deduction from the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004000/// function template's function type. This type may be NULL, if there is no
4001/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
Douglas Gregor9b146582009-07-08 20:55:45 +00004002///
4003/// \param Specialization if template argument deduction was successful,
Mike Stump11289f42009-09-09 15:08:12 +00004004/// this will be set to the function template specialization produced by
Douglas Gregor9b146582009-07-08 20:55:45 +00004005/// template argument deduction.
4006///
4007/// \param Info the argument will be updated to provide additional information
4008/// about template argument deduction.
4009///
Richard Smithbaa47832016-12-01 02:11:49 +00004010/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4011/// the address of a function template per [temp.deduct.funcaddr] and
4012/// [over.over]. If \c false, we are looking up a function template
4013/// specialization based on its signature, per [temp.deduct.decl].
4014///
Douglas Gregor9b146582009-07-08 20:55:45 +00004015/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00004016Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
4017 FunctionTemplateDecl *FunctionTemplate,
4018 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
4019 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4020 bool IsAddressOfFunction) {
Douglas Gregorc5c01a62012-09-13 21:01:57 +00004021 if (FunctionTemplate->isInvalidDecl())
4022 return TDK_Invalid;
4023
Douglas Gregor9b146582009-07-08 20:55:45 +00004024 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4025 TemplateParameterList *TemplateParams
4026 = FunctionTemplate->getTemplateParameters();
4027 QualType FunctionType = Function->getType();
Richard Smithbaa47832016-12-01 02:11:49 +00004028
Douglas Gregor9b146582009-07-08 20:55:45 +00004029 // Substitute any explicit template arguments.
John McCall19c1bfd2010-08-25 05:32:35 +00004030 LocalInstantiationScope InstScope(*this);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004031 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00004032 unsigned NumExplicitlySpecified = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004033 SmallVector<QualType, 4> ParamTypes;
John McCall6b51f282009-11-23 01:53:49 +00004034 if (ExplicitTemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00004035 if (TemplateDeductionResult Result
4036 = SubstituteExplicitTemplateArguments(FunctionTemplate,
John McCall6b51f282009-11-23 01:53:49 +00004037 *ExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004038 Deduced, ParamTypes,
Douglas Gregor9b146582009-07-08 20:55:45 +00004039 &FunctionType, Info))
4040 return Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00004041
4042 NumExplicitlySpecified = Deduced.size();
Douglas Gregor9b146582009-07-08 20:55:45 +00004043 }
4044
Richard Smithcd198152017-06-07 21:46:22 +00004045 // When taking the address of a function, we require convertibility of
4046 // the resulting function type. Otherwise, we allow arbitrary mismatches
4047 // of calling convention and noreturn.
4048 if (!IsAddressOfFunction)
4049 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
4050 /*AdjustExceptionSpec*/false);
4051
Eli Friedman77dcc722012-02-08 03:07:05 +00004052 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00004053 EnterExpressionEvaluationContext Unevaluated(
4054 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00004055 SFINAETrap Trap(*this);
4056
John McCallc1f69982010-02-02 02:21:27 +00004057 Deduced.resize(TemplateParams->size());
4058
Richard Smith2a7d4812013-05-04 07:00:32 +00004059 // If the function has a deduced return type, substitute it for a dependent
Richard Smithbaa47832016-12-01 02:11:49 +00004060 // type so that we treat it as a non-deduced context in what follows. If we
4061 // are looking up by signature, the signature type should also have a deduced
4062 // return type, which we instead expect to exactly match.
Richard Smithc58f38f2013-08-14 20:16:31 +00004063 bool HasDeducedReturnType = false;
Richard Smithbaa47832016-12-01 02:11:49 +00004064 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
Alp Toker314cc812014-01-25 16:55:45 +00004065 Function->getReturnType()->getContainedAutoType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00004066 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
Richard Smithc58f38f2013-08-14 20:16:31 +00004067 HasDeducedReturnType = true;
Richard Smith2a7d4812013-05-04 07:00:32 +00004068 }
4069
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004070 if (!ArgFunctionType.isNull()) {
Richard Smithcd198152017-06-07 21:46:22 +00004071 unsigned TDF =
4072 TDF_TopLevelParameterTypeList | TDF_AllowCompatibleFunctionType;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004073 // Deduce template arguments from the function type.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004074 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004075 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
Douglas Gregor19a41f12013-04-17 08:45:07 +00004076 FunctionType, ArgFunctionType,
4077 Info, Deduced, TDF))
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004078 return Result;
4079 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00004080
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004081 if (TemplateDeductionResult Result
Douglas Gregor4ed49f32010-09-29 21:14:36 +00004082 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
4083 NumExplicitlySpecified,
4084 Specialization, Info))
4085 return Result;
4086
Richard Smith2a7d4812013-05-04 07:00:32 +00004087 // If the function has a deduced return type, deduce it now, so we can check
4088 // that the deduced function type matches the requested type.
Richard Smithc58f38f2013-08-14 20:16:31 +00004089 if (HasDeducedReturnType &&
Alp Toker314cc812014-01-25 16:55:45 +00004090 Specialization->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00004091 DeduceReturnType(Specialization, Info.getLocation(), false))
4092 return TDK_MiscellaneousDeductionFailure;
4093
Richard Smith9095e5b2016-11-01 01:31:23 +00004094 // If the function has a dependent exception specification, resolve it now,
4095 // so we can check that the exception specification matches.
4096 auto *SpecializationFPT =
4097 Specialization->getType()->castAs<FunctionProtoType>();
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004098 if (getLangOpts().CPlusPlus17 &&
Richard Smith9095e5b2016-11-01 01:31:23 +00004099 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
4100 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
4101 return TDK_MiscellaneousDeductionFailure;
4102
Richard Smithcd198152017-06-07 21:46:22 +00004103 // Adjust the exception specification of the argument to match the
Richard Smithbaa47832016-12-01 02:11:49 +00004104 // substituted and resolved type we just formed. (Calling convention and
4105 // noreturn can't be dependent, so we don't actually need this for them
4106 // right now.)
4107 QualType SpecializationType = Specialization->getType();
4108 if (!IsAddressOfFunction)
4109 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
4110 /*AdjustExceptionSpec*/true);
4111
Douglas Gregor4ed49f32010-09-29 21:14:36 +00004112 // If the requested function type does not match the actual type of the
Douglas Gregor19a41f12013-04-17 08:45:07 +00004113 // specialization with respect to arguments of compatible pointer to function
4114 // types, template argument deduction fails.
4115 if (!ArgFunctionType.isNull()) {
Richard Smithbaa47832016-12-01 02:11:49 +00004116 if (IsAddressOfFunction &&
4117 !isSameOrCompatibleFunctionType(
4118 Context.getCanonicalType(SpecializationType),
4119 Context.getCanonicalType(ArgFunctionType)))
Douglas Gregor19a41f12013-04-17 08:45:07 +00004120 return TDK_MiscellaneousDeductionFailure;
Richard Smithbaa47832016-12-01 02:11:49 +00004121
4122 if (!IsAddressOfFunction &&
4123 !Context.hasSameType(SpecializationType, ArgFunctionType))
Douglas Gregor19a41f12013-04-17 08:45:07 +00004124 return TDK_MiscellaneousDeductionFailure;
4125 }
Douglas Gregor4ed49f32010-09-29 21:14:36 +00004126
4127 return TDK_Success;
Douglas Gregor9b146582009-07-08 20:55:45 +00004128}
4129
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004130/// Deduce template arguments for a templated conversion
Douglas Gregor05155d82009-08-21 23:19:43 +00004131/// function (C++ [temp.deduct.conv]) and, if successful, produce a
4132/// conversion function template specialization.
4133Sema::TemplateDeductionResult
Faisal Vali571df122013-09-29 08:45:24 +00004134Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
Douglas Gregor05155d82009-08-21 23:19:43 +00004135 QualType ToType,
4136 CXXConversionDecl *&Specialization,
4137 TemplateDeductionInfo &Info) {
Faisal Vali571df122013-09-29 08:45:24 +00004138 if (ConversionTemplate->isInvalidDecl())
Douglas Gregorc5c01a62012-09-13 21:01:57 +00004139 return TDK_Invalid;
4140
Faisal Vali2b3a3012013-10-24 23:40:02 +00004141 CXXConversionDecl *ConversionGeneric
Faisal Vali571df122013-09-29 08:45:24 +00004142 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
4143
Faisal Vali2b3a3012013-10-24 23:40:02 +00004144 QualType FromType = ConversionGeneric->getConversionType();
Douglas Gregor05155d82009-08-21 23:19:43 +00004145
4146 // Canonicalize the types for deduction.
4147 QualType P = Context.getCanonicalType(FromType);
4148 QualType A = Context.getCanonicalType(ToType);
4149
Douglas Gregord99609a2011-03-06 09:03:20 +00004150 // C++0x [temp.deduct.conv]p2:
Douglas Gregor05155d82009-08-21 23:19:43 +00004151 // If P is a reference type, the type referred to by P is used for
4152 // type deduction.
4153 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
4154 P = PRef->getPointeeType();
4155
Douglas Gregord99609a2011-03-06 09:03:20 +00004156 // C++0x [temp.deduct.conv]p4:
4157 // [...] If A is a reference type, the type referred to by A is used
Douglas Gregor05155d82009-08-21 23:19:43 +00004158 // for type deduction.
Richard Smithb884ed12018-07-11 23:19:41 +00004159 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
4160 A = ARef->getPointeeType();
4161 // We work around a defect in the standard here: cv-qualifiers are also
4162 // removed from P and A in this case, unless P was a reference type. This
4163 // seems to mostly match what other compilers are doing.
4164 if (!FromType->getAs<ReferenceType>()) {
4165 A = A.getUnqualifiedType();
4166 P = P.getUnqualifiedType();
4167 }
4168
Douglas Gregord99609a2011-03-06 09:03:20 +00004169 // C++ [temp.deduct.conv]p3:
Douglas Gregor05155d82009-08-21 23:19:43 +00004170 //
Mike Stump11289f42009-09-09 15:08:12 +00004171 // If A is not a reference type:
Richard Smithb884ed12018-07-11 23:19:41 +00004172 } else {
Douglas Gregor05155d82009-08-21 23:19:43 +00004173 assert(!A->isReferenceType() && "Reference types were handled above");
4174
4175 // - If P is an array type, the pointer type produced by the
Mike Stump11289f42009-09-09 15:08:12 +00004176 // array-to-pointer standard conversion (4.2) is used in place
Douglas Gregor05155d82009-08-21 23:19:43 +00004177 // of P for type deduction; otherwise,
4178 if (P->isArrayType())
4179 P = Context.getArrayDecayedType(P);
4180 // - If P is a function type, the pointer type produced by the
4181 // function-to-pointer standard conversion (4.3) is used in
4182 // place of P for type deduction; otherwise,
4183 else if (P->isFunctionType())
4184 P = Context.getPointerType(P);
4185 // - If P is a cv-qualified type, the top level cv-qualifiers of
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004186 // P's type are ignored for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00004187 else
4188 P = P.getUnqualifiedType();
4189
Douglas Gregord99609a2011-03-06 09:03:20 +00004190 // C++0x [temp.deduct.conv]p4:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004191 // If A is a cv-qualified type, the top level cv-qualifiers of A's
Nico Weberc153d242014-07-28 00:02:09 +00004192 // type are ignored for type deduction. If A is a reference type, the type
Douglas Gregord99609a2011-03-06 09:03:20 +00004193 // referred to by A is used for type deduction.
Douglas Gregor05155d82009-08-21 23:19:43 +00004194 A = A.getUnqualifiedType();
4195 }
4196
Eli Friedman77dcc722012-02-08 03:07:05 +00004197 // Unevaluated SFINAE context.
Faisal Valid143a0c2017-04-01 21:30:49 +00004198 EnterExpressionEvaluationContext Unevaluated(
4199 *this, Sema::ExpressionEvaluationContext::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +00004200 SFINAETrap Trap(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00004201
4202 // C++ [temp.deduct.conv]p1:
4203 // Template argument deduction is done by comparing the return
4204 // type of the template conversion function (call it P) with the
4205 // type that is required as the result of the conversion (call it
4206 // A) as described in 14.8.2.4.
4207 TemplateParameterList *TemplateParams
Faisal Vali571df122013-09-29 08:45:24 +00004208 = ConversionTemplate->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004209 SmallVector<DeducedTemplateArgument, 4> Deduced;
Mike Stump11289f42009-09-09 15:08:12 +00004210 Deduced.resize(TemplateParams->size());
Douglas Gregor05155d82009-08-21 23:19:43 +00004211
4212 // C++0x [temp.deduct.conv]p4:
4213 // In general, the deduction process attempts to find template
4214 // argument values that will make the deduced A identical to
4215 // A. However, there are two cases that allow a difference:
4216 unsigned TDF = 0;
4217 // - If the original A is a reference type, A can be more
4218 // cv-qualified than the deduced A (i.e., the type referred to
4219 // by the reference)
4220 if (ToType->isReferenceType())
Richard Smithb884ed12018-07-11 23:19:41 +00004221 TDF |= TDF_ArgWithReferenceType;
Douglas Gregor05155d82009-08-21 23:19:43 +00004222 // - The deduced A can be another pointer or pointer to member
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004223 // type that can be converted to A via a qualification
Douglas Gregor05155d82009-08-21 23:19:43 +00004224 // conversion.
4225 //
4226 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
4227 // both P and A are pointers or member pointers. In this case, we
4228 // just ignore cv-qualifiers completely).
4229 if ((P->isPointerType() && A->isPointerType()) ||
Douglas Gregor9f05ed52011-08-30 00:37:54 +00004230 (P->isMemberPointerType() && A->isMemberPointerType()))
Douglas Gregor05155d82009-08-21 23:19:43 +00004231 TDF |= TDF_IgnoreQualifiers;
4232 if (TemplateDeductionResult Result
Sebastian Redlfb0b1f12012-01-17 22:49:52 +00004233 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
4234 P, A, Info, Deduced, TDF))
Douglas Gregor05155d82009-08-21 23:19:43 +00004235 return Result;
Faisal Vali850da1a2013-09-29 17:08:32 +00004236
4237 // Create an Instantiation Scope for finalizing the operator.
4238 LocalInstantiationScope InstScope(*this);
Douglas Gregor05155d82009-08-21 23:19:43 +00004239 // Finish template argument deduction.
Craig Topperc3ec1492014-05-26 06:22:03 +00004240 FunctionDecl *ConversionSpecialized = nullptr;
Faisal Vali850da1a2013-09-29 17:08:32 +00004241 TemplateDeductionResult Result
Simon Pilgrim728134c2016-08-12 11:43:57 +00004242 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
Faisal Vali2b3a3012013-10-24 23:40:02 +00004243 ConversionSpecialized, Info);
4244 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
Douglas Gregor05155d82009-08-21 23:19:43 +00004245 return Result;
4246}
4247
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004248/// Deduce template arguments for a function template when there is
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004249/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
4250///
4251/// \param FunctionTemplate the function template for which we are performing
4252/// template argument deduction.
4253///
James Dennett18348b62012-06-22 08:52:37 +00004254/// \param ExplicitTemplateArgs the explicitly-specified template
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004255/// arguments.
4256///
4257/// \param Specialization if template argument deduction was successful,
4258/// this will be set to the function template specialization produced by
4259/// template argument deduction.
4260///
4261/// \param Info the argument will be updated to provide additional information
4262/// about template argument deduction.
4263///
Richard Smithbaa47832016-12-01 02:11:49 +00004264/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4265/// the address of a function template in a context where we do not have a
4266/// target type, per [over.over]. If \c false, we are looking up a function
4267/// template specialization based on its signature, which only happens when
4268/// deducing a function parameter type from an argument that is a template-id
4269/// naming a function template specialization.
4270///
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004271/// \returns the result of template argument deduction.
Richard Smithbaa47832016-12-01 02:11:49 +00004272Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
4273 FunctionTemplateDecl *FunctionTemplate,
4274 TemplateArgumentListInfo *ExplicitTemplateArgs,
4275 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4276 bool IsAddressOfFunction) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004277 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00004278 QualType(), Specialization, Info,
Richard Smithbaa47832016-12-01 02:11:49 +00004279 IsAddressOfFunction);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00004280}
4281
Richard Smith30482bc2011-02-20 03:19:35 +00004282namespace {
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00004283
Richard Smith60437622017-02-09 19:17:44 +00004284 /// Substitute the 'auto' specifier or deduced template specialization type
4285 /// specifier within a type for a given replacement type.
4286 class SubstituteDeducedTypeTransform :
4287 public TreeTransform<SubstituteDeducedTypeTransform> {
Richard Smith30482bc2011-02-20 03:19:35 +00004288 QualType Replacement;
Richard Smith60437622017-02-09 19:17:44 +00004289 bool UseTypeSugar;
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00004290
Richard Smith30482bc2011-02-20 03:19:35 +00004291 public:
Richard Smith60437622017-02-09 19:17:44 +00004292 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
4293 bool UseTypeSugar = true)
4294 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
4295 Replacement(Replacement), UseTypeSugar(UseTypeSugar) {}
4296
4297 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
4298 assert(isa<TemplateTypeParmType>(Replacement) &&
4299 "unexpected unsugared replacement kind");
4300 QualType Result = Replacement;
4301 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
4302 NewTL.setNameLoc(TL.getNameLoc());
4303 return Result;
4304 }
Nico Weberc153d242014-07-28 00:02:09 +00004305
Richard Smith30482bc2011-02-20 03:19:35 +00004306 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
4307 // If we're building the type pattern to deduce against, don't wrap the
4308 // substituted type in an AutoType. Certain template deduction rules
4309 // apply only when a template type parameter appears directly (and not if
4310 // the parameter is found through desugaring). For instance:
4311 // auto &&lref = lvalue;
4312 // must transform into "rvalue reference to T" not "rvalue reference to
4313 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
Richard Smith60437622017-02-09 19:17:44 +00004314 //
4315 // FIXME: Is this still necessary?
4316 if (!UseTypeSugar)
4317 return TransformDesugared(TLB, TL);
4318
4319 QualType Result = SemaRef.Context.getAutoType(
4320 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull());
4321 auto NewTL = TLB.push<AutoTypeLoc>(Result);
4322 NewTL.setNameLoc(TL.getNameLoc());
4323 return Result;
4324 }
4325
4326 QualType TransformDeducedTemplateSpecializationType(
4327 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
4328 if (!UseTypeSugar)
4329 return TransformDesugared(TLB, TL);
4330
4331 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
4332 TL.getTypePtr()->getTemplateName(),
4333 Replacement, Replacement.isNull());
4334 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
4335 NewTL.setNameLoc(TL.getNameLoc());
4336 return Result;
Richard Smith30482bc2011-02-20 03:19:35 +00004337 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00004338
4339 ExprResult TransformLambdaExpr(LambdaExpr *E) {
4340 // Lambdas never need to be transformed.
4341 return E;
4342 }
Richard Smith061f1e22013-04-30 21:23:01 +00004343
Richard Smith2a7d4812013-05-04 07:00:32 +00004344 QualType Apply(TypeLoc TL) {
4345 // Create some scratch storage for the transformed type locations.
4346 // FIXME: We're just going to throw this information away. Don't build it.
4347 TypeLocBuilder TLB;
4348 TLB.reserve(TL.getFullDataSize());
4349 return TransformType(TLB, TL);
Richard Smith061f1e22013-04-30 21:23:01 +00004350 }
Richard Smith30482bc2011-02-20 03:19:35 +00004351 };
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00004352
4353} // namespace
Richard Smith30482bc2011-02-20 03:19:35 +00004354
Richard Smith2a7d4812013-05-04 07:00:32 +00004355Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004356Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result,
4357 Optional<unsigned> DependentDeductionDepth) {
4358 return DeduceAutoType(Type->getTypeLoc(), Init, Result,
4359 DependentDeductionDepth);
Richard Smith2a7d4812013-05-04 07:00:32 +00004360}
4361
Richard Smithb1efc9b2017-08-30 00:44:08 +00004362/// Attempt to produce an informative diagostic explaining why auto deduction
4363/// failed.
4364/// \return \c true if diagnosed, \c false if not.
4365static bool diagnoseAutoDeductionFailure(Sema &S,
4366 Sema::TemplateDeductionResult TDK,
4367 TemplateDeductionInfo &Info,
4368 ArrayRef<SourceRange> Ranges) {
4369 switch (TDK) {
4370 case Sema::TDK_Inconsistent: {
4371 // Inconsistent deduction means we were deducing from an initializer list.
4372 auto D = S.Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction);
4373 D << Info.FirstArg << Info.SecondArg;
4374 for (auto R : Ranges)
4375 D << R;
4376 return true;
4377 }
4378
4379 // FIXME: Are there other cases for which a custom diagnostic is more useful
4380 // than the basic "types don't match" diagnostic?
4381
4382 default:
4383 return false;
4384 }
4385}
4386
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004387/// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
Richard Smith30482bc2011-02-20 03:19:35 +00004388///
Richard Smith87d263e2016-12-25 08:05:23 +00004389/// Note that this is done even if the initializer is dependent. (This is
4390/// necessary to support partial ordering of templates using 'auto'.)
4391/// A dependent type will be produced when deducing from a dependent type.
4392///
Richard Smith30482bc2011-02-20 03:19:35 +00004393/// \param Type the type pattern using the auto type-specifier.
Richard Smith30482bc2011-02-20 03:19:35 +00004394/// \param Init the initializer for the variable whose type is to be deduced.
Richard Smith30482bc2011-02-20 03:19:35 +00004395/// \param Result if type deduction was successful, this will be set to the
Richard Smith061f1e22013-04-30 21:23:01 +00004396/// deduced type.
Richard Smith87d263e2016-12-25 08:05:23 +00004397/// \param DependentDeductionDepth Set if we should permit deduction in
4398/// dependent cases. This is necessary for template partial ordering with
4399/// 'auto' template parameters. The value specified is the template
4400/// parameter depth at which we should perform 'auto' deduction.
Sebastian Redl09edce02012-01-23 22:09:39 +00004401Sema::DeduceAutoResult
Richard Smith87d263e2016-12-25 08:05:23 +00004402Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result,
4403 Optional<unsigned> DependentDeductionDepth) {
John McCalld5c98ae2011-11-15 01:35:18 +00004404 if (Init->getType()->isNonOverloadPlaceholderType()) {
Richard Smith061f1e22013-04-30 21:23:01 +00004405 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4406 if (NonPlaceholder.isInvalid())
4407 return DAR_FailedAlreadyDiagnosed;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004408 Init = NonPlaceholder.get();
John McCalld5c98ae2011-11-15 01:35:18 +00004409 }
4410
Richard Smith87d263e2016-12-25 08:05:23 +00004411 if (!DependentDeductionDepth &&
4412 (Type.getType()->isDependentType() || Init->isTypeDependent())) {
Richard Smith60437622017-02-09 19:17:44 +00004413 Result = SubstituteDeducedTypeTransform(*this, QualType()).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004414 assert(!Result.isNull() && "substituting DependentTy can't fail");
Sebastian Redl09edce02012-01-23 22:09:39 +00004415 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004416 }
4417
Richard Smith87d263e2016-12-25 08:05:23 +00004418 // Find the depth of template parameter to synthesize.
4419 unsigned Depth = DependentDeductionDepth.getValueOr(0);
4420
Richard Smith74aeef52013-04-26 16:15:35 +00004421 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4422 // Since 'decltype(auto)' can only occur at the top of the type, we
4423 // don't need to go digging for it.
Richard Smith2a7d4812013-05-04 07:00:32 +00004424 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
Richard Smith74aeef52013-04-26 16:15:35 +00004425 if (AT->isDecltypeAuto()) {
4426 if (isa<InitListExpr>(Init)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004427 Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list);
Richard Smith74aeef52013-04-26 16:15:35 +00004428 return DAR_FailedAlreadyDiagnosed;
4429 }
4430
Akira Hatanaka0a848562019-01-10 20:12:16 +00004431 ExprResult ER = CheckPlaceholderExpr(Init);
4432 if (ER.isInvalid())
4433 return DAR_FailedAlreadyDiagnosed;
4434 Init = ER.get();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004435 QualType Deduced = BuildDecltypeType(Init, Init->getBeginLoc(), false);
David Majnemer3c20ab22015-07-01 00:29:28 +00004436 if (Deduced.isNull())
4437 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004438 // FIXME: Support a non-canonical deduced type for 'auto'.
4439 Deduced = Context.getCanonicalType(Deduced);
Richard Smith60437622017-02-09 19:17:44 +00004440 Result = SubstituteDeducedTypeTransform(*this, Deduced).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004441 if (Result.isNull())
4442 return DAR_FailedAlreadyDiagnosed;
Richard Smith74aeef52013-04-26 16:15:35 +00004443 return DAR_Succeeded;
Richard Smithe301ba22015-11-11 02:02:15 +00004444 } else if (!getLangOpts().CPlusPlus) {
4445 if (isa<InitListExpr>(Init)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004446 Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c);
Richard Smithe301ba22015-11-11 02:02:15 +00004447 return DAR_FailedAlreadyDiagnosed;
4448 }
Richard Smith74aeef52013-04-26 16:15:35 +00004449 }
4450 }
4451
Richard Smith30482bc2011-02-20 03:19:35 +00004452 SourceLocation Loc = Init->getExprLoc();
4453
4454 LocalInstantiationScope InstScope(*this);
4455
4456 // Build template<class TemplParam> void Func(FuncParam);
Richard Smith87d263e2016-12-25 08:05:23 +00004457 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
4458 Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false);
Chandler Carruth08836322011-05-01 00:51:33 +00004459 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4460 NamedDecl *TemplParamPtr = TemplParam;
Hubert Tonge4a0c0e2016-07-30 22:33:34 +00004461 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4462 Loc, Loc, TemplParamPtr, Loc, nullptr);
Richard Smithb2bc2e62011-02-21 20:05:19 +00004463
Richard Smith87d263e2016-12-25 08:05:23 +00004464 QualType FuncParam =
Richard Smith60437622017-02-09 19:17:44 +00004465 SubstituteDeducedTypeTransform(*this, TemplArg, /*UseTypeSugar*/false)
Richard Smith87d263e2016-12-25 08:05:23 +00004466 .Apply(Type);
Richard Smith061f1e22013-04-30 21:23:01 +00004467 assert(!FuncParam.isNull() &&
4468 "substituting template parameter for 'auto' failed");
Richard Smith30482bc2011-02-20 03:19:35 +00004469
4470 // Deduce type of TemplParam in Func(Init)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004471 SmallVector<DeducedTemplateArgument, 1> Deduced;
Richard Smith30482bc2011-02-20 03:19:35 +00004472 Deduced.resize(1);
Richard Smith30482bc2011-02-20 03:19:35 +00004473
Richard Smith87d263e2016-12-25 08:05:23 +00004474 TemplateDeductionInfo Info(Loc, Depth);
4475
4476 // If deduction failed, don't diagnose if the initializer is dependent; it
4477 // might acquire a matching type in the instantiation.
Richard Smithb1efc9b2017-08-30 00:44:08 +00004478 auto DeductionFailed = [&](TemplateDeductionResult TDK,
4479 ArrayRef<SourceRange> Ranges) -> DeduceAutoResult {
Richard Smith87d263e2016-12-25 08:05:23 +00004480 if (Init->isTypeDependent()) {
Richard Smith60437622017-02-09 19:17:44 +00004481 Result = SubstituteDeducedTypeTransform(*this, QualType()).Apply(Type);
Richard Smith87d263e2016-12-25 08:05:23 +00004482 assert(!Result.isNull() && "substituting DependentTy can't fail");
4483 return DAR_Succeeded;
4484 }
Richard Smithb1efc9b2017-08-30 00:44:08 +00004485 if (diagnoseAutoDeductionFailure(*this, TDK, Info, Ranges))
4486 return DAR_FailedAlreadyDiagnosed;
Richard Smith87d263e2016-12-25 08:05:23 +00004487 return DAR_Failed;
4488 };
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004489
Richard Smith707eab62017-01-05 04:08:31 +00004490 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
4491
Richard Smith74801c82012-07-08 04:13:07 +00004492 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004493 if (InitList) {
Richard Smithc8a32e52017-01-05 23:12:16 +00004494 // Notionally, we substitute std::initializer_list<T> for 'auto' and deduce
4495 // against that. Such deduction only succeeds if removing cv-qualifiers and
4496 // references results in std::initializer_list<T>.
4497 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
4498 return DAR_Failed;
4499
Richard Smithb1efc9b2017-08-30 00:44:08 +00004500 SourceRange DeducedFromInitRange;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004501 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
Richard Smithb1efc9b2017-08-30 00:44:08 +00004502 Expr *Init = InitList->getInit(i);
4503
4504 if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
4505 *this, TemplateParamsSt.get(), 0, TemplArg, Init,
Richard Smithc92d2062017-01-05 23:02:44 +00004506 Info, Deduced, OriginalCallArgs, /*Decomposed*/ true,
4507 /*ArgIdx*/ 0, /*TDF*/ 0))
Richard Smithb1efc9b2017-08-30 00:44:08 +00004508 return DeductionFailed(TDK, {DeducedFromInitRange,
4509 Init->getSourceRange()});
4510
4511 if (DeducedFromInitRange.isInvalid() &&
4512 Deduced[0].getKind() != TemplateArgument::Null)
4513 DeducedFromInitRange = Init->getSourceRange();
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004514 }
4515 } else {
Richard Smithe301ba22015-11-11 02:02:15 +00004516 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4517 Diag(Loc, diag::err_auto_bitfield);
4518 return DAR_FailedAlreadyDiagnosed;
4519 }
4520
Richard Smithb1efc9b2017-08-30 00:44:08 +00004521 if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
Richard Smith32918772017-02-14 00:25:28 +00004522 *this, TemplateParamsSt.get(), 0, FuncParam, Init, Info, Deduced,
Richard Smithc92d2062017-01-05 23:02:44 +00004523 OriginalCallArgs, /*Decomposed*/ false, /*ArgIdx*/ 0, /*TDF*/ 0))
Richard Smithb1efc9b2017-08-30 00:44:08 +00004524 return DeductionFailed(TDK, {});
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004525 }
Richard Smith30482bc2011-02-20 03:19:35 +00004526
Richard Smith87d263e2016-12-25 08:05:23 +00004527 // Could be null if somehow 'auto' appears in a non-deduced context.
Eli Friedmane4310952012-11-06 23:56:42 +00004528 if (Deduced[0].getKind() != TemplateArgument::Type)
Richard Smithb1efc9b2017-08-30 00:44:08 +00004529 return DeductionFailed(TDK_Incomplete, {});
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004530
Eli Friedmane4310952012-11-06 23:56:42 +00004531 QualType DeducedType = Deduced[0].getAsType();
4532
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004533 if (InitList) {
4534 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4535 if (DeducedType.isNull())
Sebastian Redl09edce02012-01-23 22:09:39 +00004536 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004537 }
4538
Richard Smith60437622017-02-09 19:17:44 +00004539 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
Richard Smith2a7d4812013-05-04 07:00:32 +00004540 if (Result.isNull())
Richard Smith87d263e2016-12-25 08:05:23 +00004541 return DAR_FailedAlreadyDiagnosed;
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004542
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004543 // Check that the deduced argument type is compatible with the original
4544 // argument type per C++ [temp.deduct.call]p4.
Richard Smithc92d2062017-01-05 23:02:44 +00004545 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
Richard Smith707eab62017-01-05 04:08:31 +00004546 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
Richard Smithc92d2062017-01-05 23:02:44 +00004547 assert((bool)InitList == OriginalArg.DecomposedParam &&
4548 "decomposed non-init-list in auto deduction?");
Richard Smithb1efc9b2017-08-30 00:44:08 +00004549 if (auto TDK =
4550 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA)) {
Richard Smith707eab62017-01-05 04:08:31 +00004551 Result = QualType();
Richard Smithb1efc9b2017-08-30 00:44:08 +00004552 return DeductionFailed(TDK, {});
Richard Smith707eab62017-01-05 04:08:31 +00004553 }
Douglas Gregor518bc4c2011-06-17 05:31:46 +00004554 }
4555
Sebastian Redl09edce02012-01-23 22:09:39 +00004556 return DAR_Succeeded;
Richard Smith30482bc2011-02-20 03:19:35 +00004557}
4558
Simon Pilgrim728134c2016-08-12 11:43:57 +00004559QualType Sema::SubstAutoType(QualType TypeWithAuto,
Faisal Vali2b391ab2013-09-26 19:54:12 +00004560 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004561 if (TypeToReplaceAuto->isDependentType())
4562 TypeToReplaceAuto = QualType();
Richard Smith60437622017-02-09 19:17:44 +00004563 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
Richard Smith87d263e2016-12-25 08:05:23 +00004564 .TransformType(TypeWithAuto);
Faisal Vali2b391ab2013-09-26 19:54:12 +00004565}
4566
Richard Smith60437622017-02-09 19:17:44 +00004567TypeSourceInfo *Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4568 QualType TypeToReplaceAuto) {
Richard Smith87d263e2016-12-25 08:05:23 +00004569 if (TypeToReplaceAuto->isDependentType())
4570 TypeToReplaceAuto = QualType();
Richard Smith60437622017-02-09 19:17:44 +00004571 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
Richard Smith87d263e2016-12-25 08:05:23 +00004572 .TransformType(TypeWithAuto);
Richard Smith27d807c2013-04-30 13:56:41 +00004573}
4574
Richard Smith33c33c32017-02-04 01:28:01 +00004575QualType Sema::ReplaceAutoType(QualType TypeWithAuto,
4576 QualType TypeToReplaceAuto) {
Richard Smith60437622017-02-09 19:17:44 +00004577 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
4578 /*UseTypeSugar*/ false)
Richard Smith33c33c32017-02-04 01:28:01 +00004579 .TransformType(TypeWithAuto);
4580}
4581
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004582void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4583 if (isa<InitListExpr>(Init))
4584 Diag(VDecl->getLocation(),
Richard Smithbb13c9a2013-09-28 04:02:39 +00004585 VDecl->isInitCapture()
4586 ? diag::err_init_capture_deduction_failure_from_init_list
4587 : diag::err_auto_var_deduction_failure_from_init_list)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004588 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4589 else
Richard Smithbb13c9a2013-09-28 04:02:39 +00004590 Diag(VDecl->getLocation(),
4591 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4592 : diag::err_auto_var_deduction_failure)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00004593 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4594 << Init->getSourceRange();
4595}
4596
Richard Smith2a7d4812013-05-04 07:00:32 +00004597bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4598 bool Diagnose) {
Alp Toker314cc812014-01-25 16:55:45 +00004599 assert(FD->getReturnType()->isUndeducedType());
Richard Smith2a7d4812013-05-04 07:00:32 +00004600
Richard Smith50e291e2018-01-02 23:52:42 +00004601 // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
4602 // within the return type from the call operator's type.
4603 if (isLambdaConversionOperator(FD)) {
4604 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
4605 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
4606
Fangrui Song6907ce22018-07-30 19:24:48 +00004607 // For a generic lambda, instantiate the call operator if needed.
Richard Smith50e291e2018-01-02 23:52:42 +00004608 if (auto *Args = FD->getTemplateSpecializationArgs()) {
4609 CallOp = InstantiateFunctionDeclaration(
4610 CallOp->getDescribedFunctionTemplate(), Args, Loc);
4611 if (!CallOp || CallOp->isInvalidDecl())
4612 return true;
4613
4614 // We might need to deduce the return type by instantiating the definition
4615 // of the operator() function.
4616 if (CallOp->getReturnType()->isUndeducedType())
4617 InstantiateFunctionDefinition(Loc, CallOp);
4618 }
4619
4620 if (CallOp->isInvalidDecl())
4621 return true;
4622 assert(!CallOp->getReturnType()->isUndeducedType() &&
4623 "failed to deduce lambda return type");
4624
4625 // Build the new return type from scratch.
4626 QualType RetType = getLambdaConversionFunctionResultType(
4627 CallOp->getType()->castAs<FunctionProtoType>());
4628 if (FD->getReturnType()->getAs<PointerType>())
4629 RetType = Context.getPointerType(RetType);
4630 else {
4631 assert(FD->getReturnType()->getAs<BlockPointerType>());
4632 RetType = Context.getBlockPointerType(RetType);
4633 }
4634 Context.adjustDeducedFunctionResultType(FD, RetType);
4635 return false;
4636 }
4637
Richard Smith2a7d4812013-05-04 07:00:32 +00004638 if (FD->getTemplateInstantiationPattern())
4639 InstantiateFunctionDefinition(Loc, FD);
4640
Alp Toker314cc812014-01-25 16:55:45 +00004641 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
Richard Smith2a7d4812013-05-04 07:00:32 +00004642 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4643 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4644 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4645 }
4646
4647 return StillUndeduced;
4648}
4649
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004650/// If this is a non-static member function,
Craig Topper79653572013-07-08 04:13:06 +00004651static void
4652AddImplicitObjectParameterType(ASTContext &Context,
4653 CXXMethodDecl *Method,
4654 SmallVectorImpl<QualType> &ArgTypes) {
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004655 // C++11 [temp.func.order]p3:
4656 // [...] The new parameter is of type "reference to cv A," where cv are
4657 // the cv-qualifiers of the function template (if any) and A is
4658 // the class of which the function template is a member.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004659 //
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004660 // The standard doesn't say explicitly, but we pick the appropriate kind of
4661 // reference type based on [over.match.funcs]p4.
Douglas Gregor52773dc2010-11-12 23:44:13 +00004662 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00004663 ArgTy = Context.getQualifiedType(ArgTy, Method->getTypeQualifiers());
Eli Friedmanee2ff1c2012-09-19 23:52:13 +00004664 if (Method->getRefQualifier() == RQ_RValue)
4665 ArgTy = Context.getRValueReferenceType(ArgTy);
4666 else
4667 ArgTy = Context.getLValueReferenceType(ArgTy);
Douglas Gregor52773dc2010-11-12 23:44:13 +00004668 ArgTypes.push_back(ArgTy);
4669}
4670
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004671/// Determine whether the function template \p FT1 is at least as
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004672/// specialized as \p FT2.
4673static bool isAtLeastAsSpecializedAs(Sema &S,
John McCallbc077cf2010-02-08 23:07:23 +00004674 SourceLocation Loc,
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004675 FunctionTemplateDecl *FT1,
4676 FunctionTemplateDecl *FT2,
4677 TemplatePartialOrderingContext TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004678 unsigned NumCallArguments1) {
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004679 FunctionDecl *FD1 = FT1->getTemplatedDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004680 FunctionDecl *FD2 = FT2->getTemplatedDecl();
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004681 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4682 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004683
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004684 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4685 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004686 SmallVector<DeducedTemplateArgument, 4> Deduced;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004687 Deduced.resize(TemplateParams->size());
4688
4689 // C++0x [temp.deduct.partial]p3:
4690 // The types used to determine the ordering depend on the context in which
4691 // the partial ordering is done:
Craig Toppere6706e42012-09-19 02:26:47 +00004692 TemplateDeductionInfo Info(Loc);
Richard Smithe5b52202013-09-11 00:52:39 +00004693 SmallVector<QualType, 4> Args2;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004694 switch (TPOC) {
4695 case TPOC_Call: {
4696 // - In the context of a function call, the function parameter types are
4697 // used.
Richard Smithe5b52202013-09-11 00:52:39 +00004698 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4699 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
Douglas Gregoree430a32010-11-15 15:41:16 +00004700
Eli Friedman3b5774a2012-09-19 23:27:04 +00004701 // C++11 [temp.func.order]p3:
Douglas Gregoree430a32010-11-15 15:41:16 +00004702 // [...] If only one of the function templates is a non-static
4703 // member, that function template is considered to have a new
4704 // first parameter inserted in its function parameter list. The
4705 // new parameter is of type "reference to cv A," where cv are
4706 // the cv-qualifiers of the function template (if any) and A is
4707 // the class of which the function template is a member.
4708 //
Eli Friedman3b5774a2012-09-19 23:27:04 +00004709 // Note that we interpret this to mean "if one of the function
4710 // templates is a non-static member and the other is a non-member";
4711 // otherwise, the ordering rules for static functions against non-static
4712 // functions don't make any sense.
4713 //
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004714 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4715 // it as wording was broken prior to it.
Richard Smithf0393bf2017-02-16 04:22:56 +00004716 SmallVector<QualType, 4> Args1;
4717
Richard Smithe5b52202013-09-11 00:52:39 +00004718 unsigned NumComparedArguments = NumCallArguments1;
4719
4720 if (!Method2 && Method1 && !Method1->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004721 // Compare 'this' from Method1 against first parameter from Method2.
4722 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4723 ++NumComparedArguments;
Richard Smithe5b52202013-09-11 00:52:39 +00004724 } else if (!Method1 && Method2 && !Method2->isStatic()) {
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004725 // Compare 'this' from Method2 against first parameter from Method1.
4726 AddImplicitObjectParameterType(S.Context, Method2, Args2);
Richard Smithe5b52202013-09-11 00:52:39 +00004727 }
4728
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004729 Args1.insert(Args1.end(), Proto1->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004730 Proto1->param_type_end());
Nikola Smiljanic4461de22014-05-31 02:10:59 +00004731 Args2.insert(Args2.end(), Proto2->param_type_begin(),
Alp Toker9cacbab2014-01-20 20:26:09 +00004732 Proto2->param_type_end());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004733
Douglas Gregorb837ea42011-01-11 17:34:58 +00004734 // C++ [temp.func.order]p5:
4735 // The presence of unused ellipsis and default arguments has no effect on
4736 // the partial ordering of function templates.
Richard Smithe5b52202013-09-11 00:52:39 +00004737 if (Args1.size() > NumComparedArguments)
4738 Args1.resize(NumComparedArguments);
4739 if (Args2.size() > NumComparedArguments)
4740 Args2.resize(NumComparedArguments);
Richard Smithf0393bf2017-02-16 04:22:56 +00004741 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4742 Args1.data(), Args1.size(), Info, Deduced,
4743 TDF_None, /*PartialOrdering=*/true))
4744 return false;
4745
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004746 break;
4747 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004748
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004749 case TPOC_Conversion:
4750 // - In the context of a call to a conversion operator, the return types
4751 // of the conversion function templates are used.
Richard Smithf0393bf2017-02-16 04:22:56 +00004752 if (DeduceTemplateArgumentsByTypeMatch(
4753 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4754 Info, Deduced, TDF_None,
4755 /*PartialOrdering=*/true))
4756 return false;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004757 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004758
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004759 case TPOC_Other:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004760 // - In other contexts (14.6.6.2) the function template's function type
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004761 // is used.
Richard Smithf0393bf2017-02-16 04:22:56 +00004762 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4763 FD2->getType(), FD1->getType(),
4764 Info, Deduced, TDF_None,
4765 /*PartialOrdering=*/true))
4766 return false;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004767 break;
4768 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004769
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004770 // C++0x [temp.deduct.partial]p11:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004771 // In most cases, all template parameters must have values in order for
4772 // deduction to succeed, but for partial ordering purposes a template
4773 // parameter may remain without a value provided it is not used in the
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004774 // types being used for partial ordering. [ Note: a template parameter used
4775 // in a non-deduced context is considered used. -end note]
4776 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4777 for (; ArgIdx != NumArgs; ++ArgIdx)
4778 if (Deduced[ArgIdx].isNull())
4779 break;
4780
Richard Smithf0393bf2017-02-16 04:22:56 +00004781 // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
4782 // to substitute the deduced arguments back into the template and check that
4783 // we get the right type.
Richard Smithcf824862016-12-30 04:32:02 +00004784
Richard Smithf0393bf2017-02-16 04:22:56 +00004785 if (ArgIdx == NumArgs) {
4786 // All template arguments were deduced. FT1 is at least as specialized
4787 // as FT2.
4788 return true;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004789 }
4790
Richard Smithf0393bf2017-02-16 04:22:56 +00004791 // Figure out which template parameters were used.
4792 llvm::SmallBitVector UsedParameters(TemplateParams->size());
4793 switch (TPOC) {
4794 case TPOC_Call:
4795 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4796 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
4797 TemplateParams->getDepth(),
4798 UsedParameters);
4799 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004800
Richard Smithf0393bf2017-02-16 04:22:56 +00004801 case TPOC_Conversion:
4802 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4803 TemplateParams->getDepth(), UsedParameters);
4804 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004805
Richard Smithf0393bf2017-02-16 04:22:56 +00004806 case TPOC_Other:
4807 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
4808 TemplateParams->getDepth(),
4809 UsedParameters);
4810 break;
Richard Smith86a1b132017-02-16 03:49:44 +00004811 }
4812
Richard Smithf0393bf2017-02-16 04:22:56 +00004813 for (; ArgIdx != NumArgs; ++ArgIdx)
4814 // If this argument had no value deduced but was used in one of the types
4815 // used for partial ordering, then deduction fails.
4816 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4817 return false;
4818
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004819 return true;
4820}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004821
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004822/// Determine whether this a function template whose parameter-type-list
Douglas Gregorcef1a032011-01-16 16:03:23 +00004823/// ends with a function parameter pack.
4824static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4825 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4826 unsigned NumParams = Function->getNumParams();
4827 if (NumParams == 0)
4828 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004829
Douglas Gregorcef1a032011-01-16 16:03:23 +00004830 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4831 if (!Last->isParameterPack())
4832 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004833
Douglas Gregorcef1a032011-01-16 16:03:23 +00004834 // Make sure that no previous parameter is a parameter pack.
4835 while (--NumParams > 0) {
4836 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4837 return false;
4838 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004839
Douglas Gregorcef1a032011-01-16 16:03:23 +00004840 return true;
4841}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004842
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004843/// Returns the more specialized function template according
Douglas Gregor05155d82009-08-21 23:19:43 +00004844/// to the rules of function template partial ordering (C++ [temp.func.order]).
4845///
4846/// \param FT1 the first function template
4847///
4848/// \param FT2 the second function template
4849///
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004850/// \param TPOC the context in which we are performing partial ordering of
4851/// function templates.
Mike Stump11289f42009-09-09 15:08:12 +00004852///
Richard Smithe5b52202013-09-11 00:52:39 +00004853/// \param NumCallArguments1 The number of arguments in the call to FT1, used
4854/// only when \c TPOC is \c TPOC_Call.
4855///
4856/// \param NumCallArguments2 The number of arguments in the call to FT2, used
4857/// only when \c TPOC is \c TPOC_Call.
Douglas Gregorb837ea42011-01-11 17:34:58 +00004858///
Douglas Gregorbe999392009-09-15 16:23:51 +00004859/// \returns the more specialized function template. If neither
Douglas Gregor05155d82009-08-21 23:19:43 +00004860/// template is more specialized, returns NULL.
4861FunctionTemplateDecl *
4862Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4863 FunctionTemplateDecl *FT2,
John McCallbc077cf2010-02-08 23:07:23 +00004864 SourceLocation Loc,
Douglas Gregorb837ea42011-01-11 17:34:58 +00004865 TemplatePartialOrderingContext TPOC,
Richard Smithe5b52202013-09-11 00:52:39 +00004866 unsigned NumCallArguments1,
4867 unsigned NumCallArguments2) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004868 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004869 NumCallArguments1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004870 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
Richard Smithed563c22015-02-20 04:45:22 +00004871 NumCallArguments2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004872
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004873 if (Better1 != Better2) // We have a clear winner
Richard Smithed563c22015-02-20 04:45:22 +00004874 return Better1 ? FT1 : FT2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004875
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004876 if (!Better1 && !Better2) // Neither is better than the other
Craig Topperc3ec1492014-05-26 06:22:03 +00004877 return nullptr;
Douglas Gregor0ff7d922009-09-14 18:39:43 +00004878
Douglas Gregorcef1a032011-01-16 16:03:23 +00004879 // FIXME: This mimics what GCC implements, but doesn't match up with the
4880 // proposed resolution for core issue 692. This area needs to be sorted out,
4881 // but for now we attempt to maintain compatibility.
4882 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4883 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4884 if (Variadic1 != Variadic2)
4885 return Variadic1? FT2 : FT1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004886
Craig Topperc3ec1492014-05-26 06:22:03 +00004887 return nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00004888}
Douglas Gregor9b146582009-07-08 20:55:45 +00004889
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004890/// Determine if the two templates are equivalent.
Douglas Gregor450f00842009-09-25 18:43:00 +00004891static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4892 if (T1 == T2)
4893 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004894
Douglas Gregor450f00842009-09-25 18:43:00 +00004895 if (!T1 || !T2)
4896 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004897
Douglas Gregor450f00842009-09-25 18:43:00 +00004898 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4899}
4900
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004901/// Retrieve the most specialized of the given function template
Douglas Gregor450f00842009-09-25 18:43:00 +00004902/// specializations.
4903///
John McCall58cc69d2010-01-27 01:50:18 +00004904/// \param SpecBegin the start iterator of the function template
4905/// specializations that we will be comparing.
Douglas Gregor450f00842009-09-25 18:43:00 +00004906///
John McCall58cc69d2010-01-27 01:50:18 +00004907/// \param SpecEnd the end iterator of the function template
4908/// specializations, paired with \p SpecBegin.
Douglas Gregor450f00842009-09-25 18:43:00 +00004909///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004910/// \param Loc the location where the ambiguity or no-specializations
Douglas Gregor450f00842009-09-25 18:43:00 +00004911/// diagnostic should occur.
4912///
4913/// \param NoneDiag partial diagnostic used to diagnose cases where there are
4914/// no matching candidates.
4915///
4916/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4917/// occurs.
4918///
4919/// \param CandidateDiag partial diagnostic used for each function template
4920/// specialization that is a candidate in the ambiguous ordering. One parameter
4921/// in this diagnostic should be unbound, which will correspond to the string
4922/// describing the template arguments for the function template specialization.
4923///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004924/// \returns the most specialized function template specialization, if
John McCall58cc69d2010-01-27 01:50:18 +00004925/// found. Otherwise, returns SpecEnd.
Larisse Voufo98b20f12013-07-19 23:00:19 +00004926UnresolvedSetIterator Sema::getMostSpecialized(
4927 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4928 TemplateSpecCandidateSet &FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00004929 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4930 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4931 bool Complain, QualType TargetType) {
John McCall58cc69d2010-01-27 01:50:18 +00004932 if (SpecBegin == SpecEnd) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00004933 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004934 Diag(Loc, NoneDiag);
Larisse Voufo98b20f12013-07-19 23:00:19 +00004935 FailedCandidates.NoteCandidates(*this, Loc);
4936 }
John McCall58cc69d2010-01-27 01:50:18 +00004937 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004938 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004939
4940 if (SpecBegin + 1 == SpecEnd)
John McCall58cc69d2010-01-27 01:50:18 +00004941 return SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004942
Douglas Gregor450f00842009-09-25 18:43:00 +00004943 // Find the function template that is better than all of the templates it
4944 // has been compared to.
John McCall58cc69d2010-01-27 01:50:18 +00004945 UnresolvedSetIterator Best = SpecBegin;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004946 FunctionTemplateDecl *BestTemplate
John McCall58cc69d2010-01-27 01:50:18 +00004947 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004948 assert(BestTemplate && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004949 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4950 FunctionTemplateDecl *Challenger
4951 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004952 assert(Challenger && "Not a function template specialization?");
John McCall58cc69d2010-01-27 01:50:18 +00004953 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004954 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004955 Challenger)) {
4956 Best = I;
4957 BestTemplate = Challenger;
4958 }
4959 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004960
Douglas Gregor450f00842009-09-25 18:43:00 +00004961 // Make sure that the "best" function template is more specialized than all
4962 // of the others.
4963 bool Ambiguous = false;
John McCall58cc69d2010-01-27 01:50:18 +00004964 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4965 FunctionTemplateDecl *Challenger
4966 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
Douglas Gregor450f00842009-09-25 18:43:00 +00004967 if (I != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004968 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
Richard Smithe5b52202013-09-11 00:52:39 +00004969 Loc, TPOC_Other, 0, 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00004970 BestTemplate)) {
4971 Ambiguous = true;
4972 break;
4973 }
4974 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004975
Douglas Gregor450f00842009-09-25 18:43:00 +00004976 if (!Ambiguous) {
4977 // We found an answer. Return it.
John McCall58cc69d2010-01-27 01:50:18 +00004978 return Best;
Douglas Gregor450f00842009-09-25 18:43:00 +00004979 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004980
Douglas Gregor450f00842009-09-25 18:43:00 +00004981 // Diagnose the ambiguity.
Richard Smithb875c432013-05-04 01:51:08 +00004982 if (Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00004983 Diag(Loc, AmbigDiag);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004984
Richard Smithb875c432013-05-04 01:51:08 +00004985 // FIXME: Can we order the candidates in some sane way?
Richard Trieucaff2472011-11-23 22:32:32 +00004986 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4987 PartialDiagnostic PD = CandidateDiag;
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004988 const auto *FD = cast<FunctionDecl>(*I);
4989 PD << FD << getTemplateArgumentBindingsText(
4990 FD->getPrimaryTemplate()->getTemplateParameters(),
4991 *FD->getTemplateSpecializationArgs());
Richard Trieucaff2472011-11-23 22:32:32 +00004992 if (!TargetType.isNull())
Saleem Abdulrasool78704fb2016-12-22 04:26:57 +00004993 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
Richard Trieucaff2472011-11-23 22:32:32 +00004994 Diag((*I)->getLocation(), PD);
4995 }
Richard Smithb875c432013-05-04 01:51:08 +00004996 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004997
John McCall58cc69d2010-01-27 01:50:18 +00004998 return SpecEnd;
Douglas Gregor450f00842009-09-25 18:43:00 +00004999}
5000
Richard Smith0da6dc42016-12-24 16:40:51 +00005001/// Determine whether one partial specialization, P1, is at least as
5002/// specialized than another, P2.
Douglas Gregorbe999392009-09-15 16:23:51 +00005003///
Richard Smith26b86ea2016-12-31 21:41:23 +00005004/// \tparam TemplateLikeDecl The kind of P2, which must be a
5005/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
Richard Smith0da6dc42016-12-24 16:40:51 +00005006/// \param T1 The injected-class-name of P1 (faked for a variable template).
5007/// \param T2 The injected-class-name of P2 (faked for a variable template).
Richard Smith26b86ea2016-12-31 21:41:23 +00005008template<typename TemplateLikeDecl>
Richard Smith0da6dc42016-12-24 16:40:51 +00005009static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
Richard Smith26b86ea2016-12-31 21:41:23 +00005010 TemplateLikeDecl *P2,
Richard Smith0e617ec2016-12-27 07:56:27 +00005011 TemplateDeductionInfo &Info) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005012 // C++ [temp.class.order]p1:
5013 // For two class template partial specializations, the first is at least as
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005014 // specialized as the second if, given the following rewrite to two
5015 // function templates, the first function template is at least as
5016 // specialized as the second according to the ordering rules for function
Douglas Gregorbe999392009-09-15 16:23:51 +00005017 // templates (14.6.6.2):
5018 // - the first function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005019 // first partial specialization and has a single function parameter
5020 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00005021 // arguments of the first partial specialization, and
5022 // - the second function template has the same template parameters as the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005023 // second partial specialization and has a single function parameter
5024 // whose type is a class template specialization with the template
Douglas Gregorbe999392009-09-15 16:23:51 +00005025 // arguments of the second partial specialization.
5026 //
Douglas Gregor684268d2010-04-29 06:21:43 +00005027 // Rather than synthesize function templates, we merely perform the
5028 // equivalent partial ordering by performing deduction directly on
5029 // the template arguments of the class template partial
5030 // specializations. This computation is slightly simpler than the
5031 // general problem of function template partial ordering, because
5032 // class template partial specializations are more constrained. We
5033 // know that every template parameter is deducible from the class
5034 // template partial specialization's template arguments, for
5035 // example.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005036 SmallVector<DeducedTemplateArgument, 4> Deduced;
John McCall2408e322010-04-27 00:57:59 +00005037
Richard Smith0da6dc42016-12-24 16:40:51 +00005038 // Determine whether P1 is at least as specialized as P2.
5039 Deduced.resize(P2->getTemplateParameters()->size());
5040 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
5041 T2, T1, Info, Deduced, TDF_None,
5042 /*PartialOrdering=*/true))
5043 return false;
5044
5045 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
5046 Deduced.end());
Richard Smith0e617ec2016-12-27 07:56:27 +00005047 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
5048 Info);
Richard Smith0da6dc42016-12-24 16:40:51 +00005049 auto *TST1 = T1->castAs<TemplateSpecializationType>();
5050 if (FinishTemplateArgumentDeduction(
Richard Smith87d263e2016-12-25 08:05:23 +00005051 S, P2, /*PartialOrdering=*/true,
5052 TemplateArgumentList(TemplateArgumentList::OnStack,
5053 TST1->template_arguments()),
Richard Smith0da6dc42016-12-24 16:40:51 +00005054 Deduced, Info))
5055 return false;
5056
5057 return true;
5058}
5059
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005060/// Returns the more specialized class template partial specialization
Richard Smith0da6dc42016-12-24 16:40:51 +00005061/// according to the rules of partial ordering of class template partial
5062/// specializations (C++ [temp.class.order]).
5063///
5064/// \param PS1 the first class template partial specialization
5065///
5066/// \param PS2 the second class template partial specialization
5067///
5068/// \returns the more specialized class template partial specialization. If
5069/// neither partial specialization is more specialized, returns NULL.
5070ClassTemplatePartialSpecializationDecl *
5071Sema::getMoreSpecializedPartialSpecialization(
5072 ClassTemplatePartialSpecializationDecl *PS1,
5073 ClassTemplatePartialSpecializationDecl *PS2,
5074 SourceLocation Loc) {
John McCall2408e322010-04-27 00:57:59 +00005075 QualType PT1 = PS1->getInjectedSpecializationType();
5076 QualType PT2 = PS2->getInjectedSpecializationType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005077
Richard Smith0e617ec2016-12-27 07:56:27 +00005078 TemplateDeductionInfo Info(Loc);
5079 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
5080 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
Larisse Voufo39a1e502013-08-06 01:03:05 +00005081
5082 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00005083 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005084
5085 return Better1 ? PS1 : PS2;
5086}
5087
Richard Smith0e617ec2016-12-27 07:56:27 +00005088bool Sema::isMoreSpecializedThanPrimary(
5089 ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
5090 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
5091 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
5092 QualType PartialT = Spec->getInjectedSpecializationType();
5093 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
5094 return false;
5095 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
5096 Info.clearSFINAEDiagnostic();
5097 return false;
5098 }
5099 return true;
5100}
5101
Larisse Voufo39a1e502013-08-06 01:03:05 +00005102VarTemplatePartialSpecializationDecl *
5103Sema::getMoreSpecializedPartialSpecialization(
5104 VarTemplatePartialSpecializationDecl *PS1,
5105 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
Richard Smith0da6dc42016-12-24 16:40:51 +00005106 // Pretend the variable template specializations are class template
5107 // specializations and form a fake injected class name type for comparison.
Richard Smithf04fd0b2013-12-12 23:14:16 +00005108 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00005109 "the partial specializations being compared should specialize"
5110 " the same template.");
5111 TemplateName Name(PS1->getSpecializedTemplate());
5112 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
5113 QualType PT1 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00005114 CanonTemplate, PS1->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00005115 QualType PT2 = Context.getTemplateSpecializationType(
David Majnemer6fbeee32016-07-07 04:43:07 +00005116 CanonTemplate, PS2->getTemplateArgs().asArray());
Larisse Voufo39a1e502013-08-06 01:03:05 +00005117
Richard Smith0e617ec2016-12-27 07:56:27 +00005118 TemplateDeductionInfo Info(Loc);
5119 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
5120 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005121
Douglas Gregorbe999392009-09-15 16:23:51 +00005122 if (Better1 == Better2)
Craig Topperc3ec1492014-05-26 06:22:03 +00005123 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005124
Richard Smith0da6dc42016-12-24 16:40:51 +00005125 return Better1 ? PS1 : PS2;
Douglas Gregorbe999392009-09-15 16:23:51 +00005126}
5127
Richard Smith0e617ec2016-12-27 07:56:27 +00005128bool Sema::isMoreSpecializedThanPrimary(
5129 VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
5130 TemplateDecl *Primary = Spec->getSpecializedTemplate();
5131 // FIXME: Cache the injected template arguments rather than recomputing
5132 // them for each partial specialization.
5133 SmallVector<TemplateArgument, 8> PrimaryArgs;
5134 Context.getInjectedTemplateArgs(Primary->getTemplateParameters(),
5135 PrimaryArgs);
5136
5137 TemplateName CanonTemplate =
5138 Context.getCanonicalTemplateName(TemplateName(Primary));
5139 QualType PrimaryT = Context.getTemplateSpecializationType(
5140 CanonTemplate, PrimaryArgs);
5141 QualType PartialT = Context.getTemplateSpecializationType(
5142 CanonTemplate, Spec->getTemplateArgs().asArray());
5143 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
5144 return false;
5145 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
5146 Info.clearSFINAEDiagnostic();
5147 return false;
5148 }
5149 return true;
5150}
5151
Richard Smith26b86ea2016-12-31 21:41:23 +00005152bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
5153 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) {
5154 // C++1z [temp.arg.template]p4: (DR 150)
5155 // A template template-parameter P is at least as specialized as a
5156 // template template-argument A if, given the following rewrite to two
5157 // function templates...
5158
5159 // Rather than synthesize function templates, we merely perform the
5160 // equivalent partial ordering by performing deduction directly on
5161 // the template parameter lists of the template template parameters.
5162 //
5163 // Given an invented class template X with the template parameter list of
5164 // A (including default arguments):
5165 TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg));
5166 TemplateParameterList *A = AArg->getTemplateParameters();
5167
5168 // - Each function template has a single function parameter whose type is
5169 // a specialization of X with template arguments corresponding to the
5170 // template parameters from the respective function template
5171 SmallVector<TemplateArgument, 8> AArgs;
5172 Context.getInjectedTemplateArgs(A, AArgs);
5173
5174 // Check P's arguments against A's parameter list. This will fill in default
5175 // template arguments as needed. AArgs are already correct by construction.
5176 // We can't just use CheckTemplateIdType because that will expand alias
5177 // templates.
5178 SmallVector<TemplateArgument, 4> PArgs;
5179 {
5180 SFINAETrap Trap(*this);
5181
5182 Context.getInjectedTemplateArgs(P, PArgs);
5183 TemplateArgumentListInfo PArgList(P->getLAngleLoc(), P->getRAngleLoc());
5184 for (unsigned I = 0, N = P->size(); I != N; ++I) {
5185 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
5186 // expansions, to form an "as written" argument list.
5187 TemplateArgument Arg = PArgs[I];
5188 if (Arg.getKind() == TemplateArgument::Pack) {
5189 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
5190 Arg = *Arg.pack_begin();
5191 }
5192 PArgList.addArgument(getTrivialTemplateArgumentLoc(
5193 Arg, QualType(), P->getParam(I)->getLocation()));
5194 }
5195 PArgs.clear();
5196
5197 // C++1z [temp.arg.template]p3:
5198 // If the rewrite produces an invalid type, then P is not at least as
5199 // specialized as A.
5200 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, PArgs) ||
5201 Trap.hasErrorOccurred())
5202 return false;
5203 }
5204
5205 QualType AType = Context.getTemplateSpecializationType(X, AArgs);
5206 QualType PType = Context.getTemplateSpecializationType(X, PArgs);
5207
Richard Smith26b86ea2016-12-31 21:41:23 +00005208 // ... the function template corresponding to P is at least as specialized
5209 // as the function template corresponding to A according to the partial
5210 // ordering rules for function templates.
5211 TemplateDeductionInfo Info(Loc, A->getDepth());
5212 return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info);
5213}
5214
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005215/// Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00005216/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00005217static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005218MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005219 const Expr *E,
5220 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005221 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005222 llvm::SmallBitVector &Used) {
Douglas Gregore8e9dd62011-01-03 17:17:50 +00005223 // We can deduce from a pack expansion.
5224 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
5225 E = Expansion->getPattern();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005226
Richard Smith34349002012-07-09 03:07:20 +00005227 // Skip through any implicit casts we added while type-checking, and any
5228 // substitutions performed by template alias expansion.
Eugene Zelenko82eb70f2018-02-22 22:35:17 +00005229 while (true) {
Richard Smith34349002012-07-09 03:07:20 +00005230 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
5231 E = ICE->getSubExpr();
Fangrui Song407659a2018-11-30 23:41:18 +00005232 else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(E))
5233 E = CE->getSubExpr();
Richard Smith34349002012-07-09 03:07:20 +00005234 else if (const SubstNonTypeTemplateParmExpr *Subst =
5235 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
5236 E = Subst->getReplacement();
5237 else
5238 break;
5239 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005240
5241 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005242 // find other occurrences of template parameters.
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005243 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
Douglas Gregor04b11522010-01-14 18:13:22 +00005244 if (!DRE)
Douglas Gregor91772d12009-06-13 00:26:55 +00005245 return;
5246
Mike Stump11289f42009-09-09 15:08:12 +00005247 const NonTypeTemplateParmDecl *NTTP
Douglas Gregor91772d12009-06-13 00:26:55 +00005248 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
5249 if (!NTTP)
5250 return;
5251
Douglas Gregor21610382009-10-29 00:04:11 +00005252 if (NTTP->getDepth() == Depth)
5253 Used[NTTP->getIndex()] = true;
Richard Smith5f274382016-09-28 23:55:27 +00005254
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005255 // In C++17 mode, additional arguments may be deduced from the type of a
Richard Smith5f274382016-09-28 23:55:27 +00005256 // non-type argument.
Aaron Ballmanc351fba2017-12-04 20:27:34 +00005257 if (Ctx.getLangOpts().CPlusPlus17)
Richard Smith5f274382016-09-28 23:55:27 +00005258 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005259}
5260
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005261/// Mark the template parameters that are used by the given
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005262/// nested name specifier.
5263static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005264MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005265 NestedNameSpecifier *NNS,
5266 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005267 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005268 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005269 if (!NNS)
5270 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005271
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005272 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00005273 Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005274 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00005275 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005276}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005277
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005278/// Mark the template parameters that are used by the given
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005279/// template name.
5280static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005281MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005282 TemplateName Name,
5283 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005284 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005285 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005286 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
5287 if (TemplateTemplateParmDecl *TTP
Douglas Gregor21610382009-10-29 00:04:11 +00005288 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
5289 if (TTP->getDepth() == Depth)
5290 Used[TTP->getIndex()] = true;
5291 }
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005292 return;
5293 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005294
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005295 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005296 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005297 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005298 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005299 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005300 Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005301}
5302
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005303/// Mark the template parameters that are used by the given
Douglas Gregor91772d12009-06-13 00:26:55 +00005304/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005305static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005306MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005307 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005308 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005309 llvm::SmallBitVector &Used) {
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005310 if (T.isNull())
5311 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005312
Douglas Gregor91772d12009-06-13 00:26:55 +00005313 // Non-dependent types have nothing deducible
5314 if (!T->isDependentType())
5315 return;
5316
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005317 T = Ctx.getCanonicalType(T);
Douglas Gregor91772d12009-06-13 00:26:55 +00005318 switch (T->getTypeClass()) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005319 case Type::Pointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005320 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005321 cast<PointerType>(T)->getPointeeType(),
5322 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005323 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005324 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005325 break;
5326
5327 case Type::BlockPointer:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005328 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005329 cast<BlockPointerType>(T)->getPointeeType(),
5330 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005331 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005332 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005333 break;
5334
5335 case Type::LValueReference:
5336 case Type::RValueReference:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005337 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005338 cast<ReferenceType>(T)->getPointeeType(),
5339 OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005340 Depth,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005341 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005342 break;
5343
5344 case Type::MemberPointer: {
5345 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005346 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005347 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005348 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
Douglas Gregor21610382009-10-29 00:04:11 +00005349 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005350 break;
5351 }
5352
5353 case Type::DependentSizedArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005354 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005355 cast<DependentSizedArrayType>(T)->getSizeExpr(),
Douglas Gregor21610382009-10-29 00:04:11 +00005356 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005357 // Fall through to check the element type
Galina Kistanova33399112017-06-03 06:35:06 +00005358 LLVM_FALLTHROUGH;
Douglas Gregor91772d12009-06-13 00:26:55 +00005359
5360 case Type::ConstantArray:
5361 case Type::IncompleteArray:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005362 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005363 cast<ArrayType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005364 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005365 break;
5366
5367 case Type::Vector:
5368 case Type::ExtVector:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005369 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005370 cast<VectorType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005371 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005372 break;
5373
Erich Keanef702b022018-07-13 19:46:04 +00005374 case Type::DependentVector: {
5375 const auto *VecType = cast<DependentVectorType>(T);
5376 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
5377 Depth, Used);
5378 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth,
5379 Used);
5380 break;
5381 }
Douglas Gregor758a8692009-06-17 21:51:59 +00005382 case Type::DependentSizedExtVector: {
5383 const DependentSizedExtVectorType *VecType
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005384 = cast<DependentSizedExtVectorType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005385 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005386 Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005387 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005388 Depth, Used);
Douglas Gregor758a8692009-06-17 21:51:59 +00005389 break;
5390 }
5391
Andrew Gozillon572bbb02017-10-02 06:25:51 +00005392 case Type::DependentAddressSpace: {
5393 const DependentAddressSpaceType *DependentASType =
5394 cast<DependentAddressSpaceType>(T);
5395 MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
5396 OnlyDeduced, Depth, Used);
5397 MarkUsedTemplateParameters(Ctx,
5398 DependentASType->getAddrSpaceExpr(),
5399 OnlyDeduced, Depth, Used);
5400 break;
5401 }
5402
Douglas Gregor91772d12009-06-13 00:26:55 +00005403 case Type::FunctionProto: {
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005404 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
Alp Toker314cc812014-01-25 16:55:45 +00005405 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
5406 Used);
Richard Smithc379d1a2018-07-12 23:32:39 +00005407 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
5408 // C++17 [temp.deduct.type]p5:
5409 // The non-deduced contexts are: [...]
5410 // -- A function parameter pack that does not occur at the end of the
5411 // parameter-declaration-list.
5412 if (!OnlyDeduced || I + 1 == N ||
5413 !Proto->getParamType(I)->getAs<PackExpansionType>()) {
5414 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
5415 Depth, Used);
5416 } else {
5417 // FIXME: C++17 [temp.deduct.call]p1:
5418 // When a function parameter pack appears in a non-deduced context,
5419 // the type of that pack is never deduced.
5420 //
5421 // We should also track a set of "never deduced" parameters, and
5422 // subtract that from the list of deduced parameters after marking.
5423 }
5424 }
Richard Smithcd198152017-06-07 21:46:22 +00005425 if (auto *E = Proto->getNoexceptExpr())
5426 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005427 break;
5428 }
5429
Douglas Gregor21610382009-10-29 00:04:11 +00005430 case Type::TemplateTypeParm: {
5431 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
5432 if (TTP->getDepth() == Depth)
5433 Used[TTP->getIndex()] = true;
Douglas Gregor91772d12009-06-13 00:26:55 +00005434 break;
Douglas Gregor21610382009-10-29 00:04:11 +00005435 }
Douglas Gregor91772d12009-06-13 00:26:55 +00005436
Douglas Gregorfb322d82011-01-14 05:11:40 +00005437 case Type::SubstTemplateTypeParmPack: {
5438 const SubstTemplateTypeParmPackType *Subst
5439 = cast<SubstTemplateTypeParmPackType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005440 MarkUsedTemplateParameters(Ctx,
Douglas Gregorfb322d82011-01-14 05:11:40 +00005441 QualType(Subst->getReplacedParameter(), 0),
5442 OnlyDeduced, Depth, Used);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005443 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
Douglas Gregorfb322d82011-01-14 05:11:40 +00005444 OnlyDeduced, Depth, Used);
5445 break;
5446 }
5447
John McCall2408e322010-04-27 00:57:59 +00005448 case Type::InjectedClassName:
5449 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00005450 LLVM_FALLTHROUGH;
John McCall2408e322010-04-27 00:57:59 +00005451
Douglas Gregor91772d12009-06-13 00:26:55 +00005452 case Type::TemplateSpecialization: {
Mike Stump11289f42009-09-09 15:08:12 +00005453 const TemplateSpecializationType *Spec
Douglas Gregor1e09bf83c2009-06-18 18:45:36 +00005454 = cast<TemplateSpecializationType>(T);
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005455 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005456 Depth, Used);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005457
Douglas Gregord0ad2942010-12-23 01:24:45 +00005458 // C++0x [temp.deduct.type]p9:
Nico Weberc153d242014-07-28 00:02:09 +00005459 // If the template argument list of P contains a pack expansion that is
5460 // not the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005461 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005462 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005463 hasPackExpansionBeforeEnd(Spec->template_arguments()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005464 break;
5465
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005466 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005467 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
Douglas Gregor21610382009-10-29 00:04:11 +00005468 Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005469 break;
5470 }
5471
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005472 case Type::Complex:
5473 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005474 MarkUsedTemplateParameters(Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005475 cast<ComplexType>(T)->getElementType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005476 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005477 break;
5478
Eli Friedman0dfb8892011-10-06 23:00:33 +00005479 case Type::Atomic:
5480 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005481 MarkUsedTemplateParameters(Ctx,
Eli Friedman0dfb8892011-10-06 23:00:33 +00005482 cast<AtomicType>(T)->getValueType(),
5483 OnlyDeduced, Depth, Used);
5484 break;
5485
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005486 case Type::DependentName:
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005487 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005488 MarkUsedTemplateParameters(Ctx,
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005489 cast<DependentNameType>(T)->getQualifier(),
Douglas Gregor21610382009-10-29 00:04:11 +00005490 OnlyDeduced, Depth, Used);
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005491 break;
5492
John McCallc392f372010-06-11 00:33:02 +00005493 case Type::DependentTemplateSpecialization: {
Richard Smith50d5b972015-12-30 20:56:05 +00005494 // C++14 [temp.deduct.type]p5:
5495 // The non-deduced contexts are:
5496 // -- The nested-name-specifier of a type that was specified using a
5497 // qualified-id
5498 //
5499 // C++14 [temp.deduct.type]p6:
5500 // When a type name is specified in a way that includes a non-deduced
5501 // context, all of the types that comprise that type name are also
5502 // non-deduced.
5503 if (OnlyDeduced)
5504 break;
5505
John McCallc392f372010-06-11 00:33:02 +00005506 const DependentTemplateSpecializationType *Spec
5507 = cast<DependentTemplateSpecializationType>(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005508
Richard Smith50d5b972015-12-30 20:56:05 +00005509 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
5510 OnlyDeduced, Depth, Used);
Douglas Gregord0ad2942010-12-23 01:24:45 +00005511
John McCallc392f372010-06-11 00:33:02 +00005512 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005513 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
John McCallc392f372010-06-11 00:33:02 +00005514 Used);
5515 break;
5516 }
5517
John McCallbd8d9bd2010-03-01 23:49:17 +00005518 case Type::TypeOf:
5519 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005520 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005521 cast<TypeOfType>(T)->getUnderlyingType(),
5522 OnlyDeduced, Depth, Used);
5523 break;
5524
5525 case Type::TypeOfExpr:
5526 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005527 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005528 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
5529 OnlyDeduced, Depth, Used);
5530 break;
5531
5532 case Type::Decltype:
5533 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005534 MarkUsedTemplateParameters(Ctx,
John McCallbd8d9bd2010-03-01 23:49:17 +00005535 cast<DecltypeType>(T)->getUnderlyingExpr(),
5536 OnlyDeduced, Depth, Used);
5537 break;
5538
Alexis Hunte852b102011-05-24 22:41:36 +00005539 case Type::UnaryTransform:
5540 if (!OnlyDeduced)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005541 MarkUsedTemplateParameters(Ctx,
Richard Smith5f274382016-09-28 23:55:27 +00005542 cast<UnaryTransformType>(T)->getUnderlyingType(),
Alexis Hunte852b102011-05-24 22:41:36 +00005543 OnlyDeduced, Depth, Used);
5544 break;
5545
Douglas Gregord2fa7662010-12-20 02:24:11 +00005546 case Type::PackExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005547 MarkUsedTemplateParameters(Ctx,
Douglas Gregord2fa7662010-12-20 02:24:11 +00005548 cast<PackExpansionType>(T)->getPattern(),
5549 OnlyDeduced, Depth, Used);
5550 break;
5551
Richard Smith30482bc2011-02-20 03:19:35 +00005552 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00005553 case Type::DeducedTemplateSpecialization:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005554 MarkUsedTemplateParameters(Ctx,
Richard Smith600b5262017-01-26 20:40:47 +00005555 cast<DeducedType>(T)->getDeducedType(),
Richard Smith30482bc2011-02-20 03:19:35 +00005556 OnlyDeduced, Depth, Used);
Adrian Prantl4b490852017-12-19 22:21:48 +00005557 break;
Richard Smith30482bc2011-02-20 03:19:35 +00005558
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005559 // None of these types have any template parameters in them.
Douglas Gregor91772d12009-06-13 00:26:55 +00005560 case Type::Builtin:
Douglas Gregor91772d12009-06-13 00:26:55 +00005561 case Type::VariableArray:
5562 case Type::FunctionNoProto:
5563 case Type::Record:
5564 case Type::Enum:
Douglas Gregor91772d12009-06-13 00:26:55 +00005565 case Type::ObjCInterface:
John McCall8b07ec22010-05-15 11:32:37 +00005566 case Type::ObjCObject:
Steve Narofffb4330f2009-06-17 22:40:22 +00005567 case Type::ObjCObjectPointer:
John McCallb96ec562009-12-04 22:46:56 +00005568 case Type::UnresolvedUsing:
Xiuli Pan9c14e282016-01-09 12:53:17 +00005569 case Type::Pipe:
Douglas Gregor91772d12009-06-13 00:26:55 +00005570#define TYPE(Class, Base)
5571#define ABSTRACT_TYPE(Class, Base)
5572#define DEPENDENT_TYPE(Class, Base)
5573#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5574#include "clang/AST/TypeNodes.def"
5575 break;
5576 }
5577}
5578
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005579/// Mark the template parameters that are used by this
Douglas Gregor91772d12009-06-13 00:26:55 +00005580/// template argument.
Mike Stump11289f42009-09-09 15:08:12 +00005581static void
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005582MarkUsedTemplateParameters(ASTContext &Ctx,
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005583 const TemplateArgument &TemplateArg,
5584 bool OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005585 unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005586 llvm::SmallBitVector &Used) {
Douglas Gregor91772d12009-06-13 00:26:55 +00005587 switch (TemplateArg.getKind()) {
5588 case TemplateArgument::Null:
5589 case TemplateArgument::Integral:
Douglas Gregor31f55dc2012-04-06 22:40:38 +00005590 case TemplateArgument::Declaration:
Douglas Gregor91772d12009-06-13 00:26:55 +00005591 break;
Mike Stump11289f42009-09-09 15:08:12 +00005592
Eli Friedmanb826a002012-09-26 02:36:12 +00005593 case TemplateArgument::NullPtr:
5594 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5595 Depth, Used);
5596 break;
5597
Douglas Gregor91772d12009-06-13 00:26:55 +00005598 case TemplateArgument::Type:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005599 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005600 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005601 break;
5602
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005603 case TemplateArgument::Template:
Douglas Gregore4ff4b52011-01-05 18:58:31 +00005604 case TemplateArgument::TemplateExpansion:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005605 MarkUsedTemplateParameters(Ctx,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005606 TemplateArg.getAsTemplateOrTemplatePattern(),
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005607 OnlyDeduced, Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005608 break;
5609
5610 case TemplateArgument::Expression:
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005611 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005612 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005613 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005614
Anders Carlssonbc343912009-06-15 17:04:53 +00005615 case TemplateArgument::Pack:
Aaron Ballman2a89e852014-07-15 21:32:31 +00005616 for (const auto &P : TemplateArg.pack_elements())
5617 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
Anders Carlssonbc343912009-06-15 17:04:53 +00005618 break;
Douglas Gregor91772d12009-06-13 00:26:55 +00005619 }
5620}
5621
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005622/// Mark which template parameters can be deduced from a given
Douglas Gregor91772d12009-06-13 00:26:55 +00005623/// template argument list.
5624///
5625/// \param TemplateArgs the template argument list from which template
5626/// parameters will be deduced.
5627///
James Dennett41725122012-06-22 10:16:05 +00005628/// \param Used a bit vector whose elements will be set to \c true
Douglas Gregor91772d12009-06-13 00:26:55 +00005629/// to indicate when the corresponding template parameter will be
5630/// deduced.
Mike Stump11289f42009-09-09 15:08:12 +00005631void
Douglas Gregore1d2ef32009-09-14 21:25:05 +00005632Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00005633 bool OnlyDeduced, unsigned Depth,
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005634 llvm::SmallBitVector &Used) {
Douglas Gregord0ad2942010-12-23 01:24:45 +00005635 // C++0x [temp.deduct.type]p9:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005636 // If the template argument list of P contains a pack expansion that is not
5637 // the last template argument, the entire template argument list is a
Douglas Gregord0ad2942010-12-23 01:24:45 +00005638 // non-deduced context.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005639 if (OnlyDeduced &&
Richard Smith0bda5b52016-12-23 23:46:56 +00005640 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
Douglas Gregord0ad2942010-12-23 01:24:45 +00005641 return;
5642
Douglas Gregor91772d12009-06-13 00:26:55 +00005643 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005644 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
Douglas Gregor21610382009-10-29 00:04:11 +00005645 Depth, Used);
Douglas Gregor91772d12009-06-13 00:26:55 +00005646}
Douglas Gregorce23bae2009-09-18 23:21:38 +00005647
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005648/// Marks all of the template parameters that will be deduced by a
Douglas Gregorce23bae2009-09-18 23:21:38 +00005649/// call to the given function template.
Nico Weberc153d242014-07-28 00:02:09 +00005650void Sema::MarkDeducedTemplateParameters(
5651 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5652 llvm::SmallBitVector &Deduced) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005653 TemplateParameterList *TemplateParams
Douglas Gregorce23bae2009-09-18 23:21:38 +00005654 = FunctionTemplate->getTemplateParameters();
5655 Deduced.clear();
5656 Deduced.resize(TemplateParams->size());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005657
Douglas Gregorce23bae2009-09-18 23:21:38 +00005658 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5659 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
Argyrios Kyrtzidisf34950d2012-01-17 02:15:41 +00005660 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
Douglas Gregor21610382009-10-29 00:04:11 +00005661 true, TemplateParams->getDepth(), Deduced);
Douglas Gregorce23bae2009-09-18 23:21:38 +00005662}
Douglas Gregore65aacb2011-06-16 16:50:48 +00005663
Richard Smithf0393bf2017-02-16 04:22:56 +00005664bool hasDeducibleTemplateParameters(Sema &S,
5665 FunctionTemplateDecl *FunctionTemplate,
Douglas Gregore65aacb2011-06-16 16:50:48 +00005666 QualType T) {
5667 if (!T->isDependentType())
5668 return false;
5669
Richard Smithf0393bf2017-02-16 04:22:56 +00005670 TemplateParameterList *TemplateParams
5671 = FunctionTemplate->getTemplateParameters();
5672 llvm::SmallBitVector Deduced(TemplateParams->size());
5673 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
5674 Deduced);
Douglas Gregore65aacb2011-06-16 16:50:48 +00005675
Benjamin Kramere0513cb2012-01-30 16:17:39 +00005676 return Deduced.any();
Douglas Gregore65aacb2011-06-16 16:50:48 +00005677}