Bug Summary

File:build/source/clang/lib/Sema/SemaTemplateDeduction.cpp
Warning:line 2118, column 50
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaTemplateDeduction.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-17/lib/clang/17 -I tools/clang/lib/Sema -I /build/source/clang/lib/Sema -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D CLANG_REPOSITORY_STRING="++20230222100720+55bc18a7de91-1~exp1~20230222220828.1122" -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/source/= -source-date-epoch 1677103708 -O2 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-02-22-234837-16707-1 -x c++ /build/source/clang/lib/Sema/SemaTemplateDeduction.cpp
1//===- SemaTemplateDeduction.cpp - Template Argument Deduction ------------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements C++ template argument deduction.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/Sema/TemplateDeduction.h"
14#include "TreeTransform.h"
15#include "TypeLocBuilder.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTLambda.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclAccessPair.h"
20#include "clang/AST/DeclBase.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/DeclarationName.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/NestedNameSpecifier.h"
27#include "clang/AST/RecursiveASTVisitor.h"
28#include "clang/AST/TemplateBase.h"
29#include "clang/AST/TemplateName.h"
30#include "clang/AST/Type.h"
31#include "clang/AST/TypeLoc.h"
32#include "clang/AST/UnresolvedSet.h"
33#include "clang/Basic/AddressSpaces.h"
34#include "clang/Basic/ExceptionSpecificationType.h"
35#include "clang/Basic/LLVM.h"
36#include "clang/Basic/LangOptions.h"
37#include "clang/Basic/PartialDiagnostic.h"
38#include "clang/Basic/SourceLocation.h"
39#include "clang/Basic/Specifiers.h"
40#include "clang/Sema/Ownership.h"
41#include "clang/Sema/Sema.h"
42#include "clang/Sema/Template.h"
43#include "llvm/ADT/APInt.h"
44#include "llvm/ADT/APSInt.h"
45#include "llvm/ADT/ArrayRef.h"
46#include "llvm/ADT/DenseMap.h"
47#include "llvm/ADT/FoldingSet.h"
48#include "llvm/ADT/SmallBitVector.h"
49#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"
54#include <algorithm>
55#include <cassert>
56#include <optional>
57#include <tuple>
58#include <type_traits>
59#include <utility>
60
61namespace clang {
62
63 /// Various flags that control template argument deduction.
64 ///
65 /// These flags can be bitwise-OR'd together.
66 enum TemplateDeductionFlags {
67 /// No template argument deduction flags, which indicates the
68 /// strictest results for template argument deduction (as used for, e.g.,
69 /// matching class template partial specializations).
70 TDF_None = 0,
71
72 /// Within template argument deduction from a function call, we are
73 /// matching with a parameter type for which the original parameter was
74 /// a reference.
75 TDF_ParamWithReferenceType = 0x1,
76
77 /// Within template argument deduction from a function call, we
78 /// are matching in a case where we ignore cv-qualifiers.
79 TDF_IgnoreQualifiers = 0x02,
80
81 /// Within template argument deduction from a function call,
82 /// we are matching in a case where we can perform template argument
83 /// deduction from a template-id of a derived class of the argument type.
84 TDF_DerivedClass = 0x04,
85
86 /// Allow non-dependent types to differ, e.g., when performing
87 /// template argument deduction from a function call where conversions
88 /// may apply.
89 TDF_SkipNonDependent = 0x08,
90
91 /// Whether we are performing template argument deduction for
92 /// parameters and arguments in a top-level template argument
93 TDF_TopLevelParameterTypeList = 0x10,
94
95 /// Within template argument deduction from overload resolution per
96 /// C++ [over.over] allow matching function types that are compatible in
97 /// terms of noreturn and default calling convention adjustments, or
98 /// similarly matching a declared template specialization against a
99 /// possible template, per C++ [temp.deduct.decl]. In either case, permit
100 /// deduction where the parameter is a function type that can be converted
101 /// to the argument type.
102 TDF_AllowCompatibleFunctionType = 0x20,
103
104 /// Within template argument deduction for a conversion function, we are
105 /// matching with an argument type for which the original argument was
106 /// a reference.
107 TDF_ArgWithReferenceType = 0x40,
108 };
109}
110
111using namespace clang;
112using namespace sema;
113
114/// Compare two APSInts, extending and switching the sign as
115/// necessary to compare their values regardless of underlying type.
116static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
117 if (Y.getBitWidth() > X.getBitWidth())
118 X = X.extend(Y.getBitWidth());
119 else if (Y.getBitWidth() < X.getBitWidth())
120 Y = Y.extend(X.getBitWidth());
121
122 // If there is a signedness mismatch, correct it.
123 if (X.isSigned() != Y.isSigned()) {
124 // If the signed value is negative, then the values cannot be the same.
125 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
126 return false;
127
128 Y.setIsSigned(true);
129 X.setIsSigned(true);
130 }
131
132 return X == Y;
133}
134
135static Sema::TemplateDeductionResult DeduceTemplateArgumentsByTypeMatch(
136 Sema &S, TemplateParameterList *TemplateParams, QualType Param,
137 QualType Arg, TemplateDeductionInfo &Info,
138 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
139 bool PartialOrdering = false, bool DeducedFromArrayBound = false);
140
141static Sema::TemplateDeductionResult
142DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
143 ArrayRef<TemplateArgument> Ps,
144 ArrayRef<TemplateArgument> As,
145 TemplateDeductionInfo &Info,
146 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
147 bool NumberOfArgumentsMustMatch);
148
149static void MarkUsedTemplateParameters(ASTContext &Ctx,
150 const TemplateArgument &TemplateArg,
151 bool OnlyDeduced, unsigned Depth,
152 llvm::SmallBitVector &Used);
153
154static void MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
155 bool OnlyDeduced, unsigned Level,
156 llvm::SmallBitVector &Deduced);
157
158/// If the given expression is of a form that permits the deduction
159/// of a non-type template parameter, return the declaration of that
160/// non-type template parameter.
161static const NonTypeTemplateParmDecl *
162getDeducedParameterFromExpr(const Expr *E, unsigned Depth) {
163 // If we are within an alias template, the expression may have undergone
164 // any number of parameter substitutions already.
165 while (true) {
166 if (const auto *IC = dyn_cast<ImplicitCastExpr>(E))
167 E = IC->getSubExpr();
168 else if (const auto *CE = dyn_cast<ConstantExpr>(E))
169 E = CE->getSubExpr();
170 else if (const auto *Subst = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
171 E = Subst->getReplacement();
172 else if (const auto *CCE = dyn_cast<CXXConstructExpr>(E)) {
173 // Look through implicit copy construction from an lvalue of the same type.
174 if (CCE->getParenOrBraceRange().isValid())
175 break;
176 // Note, there could be default arguments.
177 assert(CCE->getNumArgs() >= 1 && "implicit construct expr should have 1 arg")(static_cast <bool> (CCE->getNumArgs() >= 1 &&
"implicit construct expr should have 1 arg") ? void (0) : __assert_fail
("CCE->getNumArgs() >= 1 && \"implicit construct expr should have 1 arg\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 177, __extension__
__PRETTY_FUNCTION__))
;
178 E = CCE->getArg(0);
179 } else
180 break;
181 }
182
183 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
184 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
185 if (NTTP->getDepth() == Depth)
186 return NTTP;
187
188 return nullptr;
189}
190
191static const NonTypeTemplateParmDecl *
192getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) {
193 return getDeducedParameterFromExpr(E, Info.getDeducedDepth());
194}
195
196/// Determine whether two declaration pointers refer to the same
197/// declaration.
198static bool isSameDeclaration(Decl *X, Decl *Y) {
199 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
200 X = NX->getUnderlyingDecl();
201 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
202 Y = NY->getUnderlyingDecl();
203
204 return X->getCanonicalDecl() == Y->getCanonicalDecl();
205}
206
207/// Verify that the given, deduced template arguments are compatible.
208///
209/// \returns The deduced template argument, or a NULL template argument if
210/// the deduced template arguments were incompatible.
211static DeducedTemplateArgument
212checkDeducedTemplateArguments(ASTContext &Context,
213 const DeducedTemplateArgument &X,
214 const DeducedTemplateArgument &Y) {
215 // We have no deduction for one or both of the arguments; they're compatible.
216 if (X.isNull())
217 return Y;
218 if (Y.isNull())
219 return X;
220
221 // If we have two non-type template argument values deduced for the same
222 // parameter, they must both match the type of the parameter, and thus must
223 // match each other's type. As we're only keeping one of them, we must check
224 // for that now. The exception is that if either was deduced from an array
225 // bound, the type is permitted to differ.
226 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
227 QualType XType = X.getNonTypeTemplateArgumentType();
228 if (!XType.isNull()) {
229 QualType YType = Y.getNonTypeTemplateArgumentType();
230 if (YType.isNull() || !Context.hasSameType(XType, YType))
231 return DeducedTemplateArgument();
232 }
233 }
234
235 switch (X.getKind()) {
236 case TemplateArgument::Null:
237 llvm_unreachable("Non-deduced template arguments handled above")::llvm::llvm_unreachable_internal("Non-deduced template arguments handled above"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 237)
;
238
239 case TemplateArgument::Type: {
240 // If two template type arguments have the same type, they're compatible.
241 QualType TX = X.getAsType(), TY = Y.getAsType();
242 if (Y.getKind() == TemplateArgument::Type && Context.hasSameType(TX, TY))
243 return DeducedTemplateArgument(Context.getCommonSugaredType(TX, TY),
244 X.wasDeducedFromArrayBound() ||
245 Y.wasDeducedFromArrayBound());
246
247 // If one of the two arguments was deduced from an array bound, the other
248 // supersedes it.
249 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
250 return X.wasDeducedFromArrayBound() ? Y : X;
251
252 // The arguments are not compatible.
253 return DeducedTemplateArgument();
254 }
255
256 case TemplateArgument::Integral:
257 // If we deduced a constant in one case and either a dependent expression or
258 // declaration in another case, keep the integral constant.
259 // If both are integral constants with the same value, keep that value.
260 if (Y.getKind() == TemplateArgument::Expression ||
261 Y.getKind() == TemplateArgument::Declaration ||
262 (Y.getKind() == TemplateArgument::Integral &&
263 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
264 return X.wasDeducedFromArrayBound() ? Y : X;
265
266 // All other combinations are incompatible.
267 return DeducedTemplateArgument();
268
269 case TemplateArgument::Template:
270 if (Y.getKind() == TemplateArgument::Template &&
271 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
272 return X;
273
274 // All other combinations are incompatible.
275 return DeducedTemplateArgument();
276
277 case TemplateArgument::TemplateExpansion:
278 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
279 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
280 Y.getAsTemplateOrTemplatePattern()))
281 return X;
282
283 // All other combinations are incompatible.
284 return DeducedTemplateArgument();
285
286 case TemplateArgument::Expression: {
287 if (Y.getKind() != TemplateArgument::Expression)
288 return checkDeducedTemplateArguments(Context, Y, X);
289
290 // Compare the expressions for equality
291 llvm::FoldingSetNodeID ID1, ID2;
292 X.getAsExpr()->Profile(ID1, Context, true);
293 Y.getAsExpr()->Profile(ID2, Context, true);
294 if (ID1 == ID2)
295 return X.wasDeducedFromArrayBound() ? Y : X;
296
297 // Differing dependent expressions are incompatible.
298 return DeducedTemplateArgument();
299 }
300
301 case TemplateArgument::Declaration:
302 assert(!X.wasDeducedFromArrayBound())(static_cast <bool> (!X.wasDeducedFromArrayBound()) ? void
(0) : __assert_fail ("!X.wasDeducedFromArrayBound()", "clang/lib/Sema/SemaTemplateDeduction.cpp"
, 302, __extension__ __PRETTY_FUNCTION__))
;
303
304 // If we deduced a declaration and a dependent expression, keep the
305 // declaration.
306 if (Y.getKind() == TemplateArgument::Expression)
307 return X;
308
309 // If we deduced a declaration and an integral constant, keep the
310 // integral constant and whichever type did not come from an array
311 // bound.
312 if (Y.getKind() == TemplateArgument::Integral) {
313 if (Y.wasDeducedFromArrayBound())
314 return TemplateArgument(Context, Y.getAsIntegral(),
315 X.getParamTypeForDecl());
316 return Y;
317 }
318
319 // If we deduced two declarations, make sure that they refer to the
320 // same declaration.
321 if (Y.getKind() == TemplateArgument::Declaration &&
322 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
323 return X;
324
325 // All other combinations are incompatible.
326 return DeducedTemplateArgument();
327
328 case TemplateArgument::NullPtr:
329 // If we deduced a null pointer and a dependent expression, keep the
330 // null pointer.
331 if (Y.getKind() == TemplateArgument::Expression)
332 return TemplateArgument(Context.getCommonSugaredType(
333 X.getNullPtrType(), Y.getAsExpr()->getType()),
334 true);
335
336 // If we deduced a null pointer and an integral constant, keep the
337 // integral constant.
338 if (Y.getKind() == TemplateArgument::Integral)
339 return Y;
340
341 // If we deduced two null pointers, they are the same.
342 if (Y.getKind() == TemplateArgument::NullPtr)
343 return TemplateArgument(
344 Context.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
345 true);
346
347 // All other combinations are incompatible.
348 return DeducedTemplateArgument();
349
350 case TemplateArgument::Pack: {
351 if (Y.getKind() != TemplateArgument::Pack ||
352 X.pack_size() != Y.pack_size())
353 return DeducedTemplateArgument();
354
355 llvm::SmallVector<TemplateArgument, 8> NewPack;
356 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
357 XAEnd = X.pack_end(),
358 YA = Y.pack_begin();
359 XA != XAEnd; ++XA, ++YA) {
360 TemplateArgument Merged = checkDeducedTemplateArguments(
361 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
362 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()));
363 if (Merged.isNull() && !(XA->isNull() && YA->isNull()))
364 return DeducedTemplateArgument();
365 NewPack.push_back(Merged);
366 }
367
368 return DeducedTemplateArgument(
369 TemplateArgument::CreatePackCopy(Context, NewPack),
370 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
371 }
372 }
373
374 llvm_unreachable("Invalid TemplateArgument Kind!")::llvm::llvm_unreachable_internal("Invalid TemplateArgument Kind!"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 374)
;
375}
376
377/// Deduce the value of the given non-type template parameter
378/// as the given deduced template argument. All non-type template parameter
379/// deduction is funneled through here.
380static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
381 Sema &S, TemplateParameterList *TemplateParams,
382 const NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced,
383 QualType ValueType, TemplateDeductionInfo &Info,
384 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
385 assert(NTTP->getDepth() == Info.getDeducedDepth() &&(static_cast <bool> (NTTP->getDepth() == Info.getDeducedDepth
() && "deducing non-type template argument with wrong depth"
) ? void (0) : __assert_fail ("NTTP->getDepth() == Info.getDeducedDepth() && \"deducing non-type template argument with wrong depth\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 386, __extension__
__PRETTY_FUNCTION__))
386 "deducing non-type template argument with wrong depth")(static_cast <bool> (NTTP->getDepth() == Info.getDeducedDepth
() && "deducing non-type template argument with wrong depth"
) ? void (0) : __assert_fail ("NTTP->getDepth() == Info.getDeducedDepth() && \"deducing non-type template argument with wrong depth\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 386, __extension__
__PRETTY_FUNCTION__))
;
387
388 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
389 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
390 if (Result.isNull()) {
391 Info.Param = const_cast<NonTypeTemplateParmDecl*>(NTTP);
392 Info.FirstArg = Deduced[NTTP->getIndex()];
393 Info.SecondArg = NewDeduced;
394 return Sema::TDK_Inconsistent;
395 }
396
397 Deduced[NTTP->getIndex()] = Result;
398 if (!S.getLangOpts().CPlusPlus17)
399 return Sema::TDK_Success;
400
401 if (NTTP->isExpandedParameterPack())
402 // FIXME: We may still need to deduce parts of the type here! But we
403 // don't have any way to find which slice of the type to use, and the
404 // type stored on the NTTP itself is nonsense. Perhaps the type of an
405 // expanded NTTP should be a pack expansion type?
406 return Sema::TDK_Success;
407
408 // Get the type of the parameter for deduction. If it's a (dependent) array
409 // or function type, we will not have decayed it yet, so do that now.
410 QualType ParamType = S.Context.getAdjustedParameterType(NTTP->getType());
411 if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
412 ParamType = Expansion->getPattern();
413
414 // FIXME: It's not clear how deduction of a parameter of reference
415 // type from an argument (of non-reference type) should be performed.
416 // For now, we just remove reference types from both sides and let
417 // the final check for matching types sort out the mess.
418 ValueType = ValueType.getNonReferenceType();
419 if (ParamType->isReferenceType())
420 ParamType = ParamType.getNonReferenceType();
421 else
422 // Top-level cv-qualifiers are irrelevant for a non-reference type.
423 ValueType = ValueType.getUnqualifiedType();
424
425 return DeduceTemplateArgumentsByTypeMatch(
426 S, TemplateParams, ParamType, ValueType, Info, Deduced,
427 TDF_SkipNonDependent, /*PartialOrdering=*/false,
428 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound());
429}
430
431/// Deduce the value of the given non-type template parameter
432/// from the given integral constant.
433static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
434 Sema &S, TemplateParameterList *TemplateParams,
435 const NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
436 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
437 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
438 return DeduceNonTypeTemplateArgument(
439 S, TemplateParams, NTTP,
440 DeducedTemplateArgument(S.Context, Value, ValueType,
441 DeducedFromArrayBound),
442 ValueType, Info, Deduced);
443}
444
445/// Deduce the value of the given non-type template parameter
446/// from the given null pointer template argument type.
447static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
448 Sema &S, TemplateParameterList *TemplateParams,
449 const NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
450 TemplateDeductionInfo &Info,
451 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
452 Expr *Value = S.ImpCastExprToType(
453 new (S.Context) CXXNullPtrLiteralExpr(S.Context.NullPtrTy,
454 NTTP->getLocation()),
455 NullPtrType,
456 NullPtrType->isMemberPointerType() ? CK_NullToMemberPointer
457 : CK_NullToPointer)
458 .get();
459 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
460 DeducedTemplateArgument(Value),
461 Value->getType(), Info, Deduced);
462}
463
464/// Deduce the value of the given non-type template parameter
465/// from the given type- or value-dependent expression.
466///
467/// \returns true if deduction succeeded, false otherwise.
468static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
469 Sema &S, TemplateParameterList *TemplateParams,
470 const NonTypeTemplateParmDecl *NTTP, Expr *Value, TemplateDeductionInfo &Info,
471 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
472 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
473 DeducedTemplateArgument(Value),
474 Value->getType(), Info, Deduced);
475}
476
477/// Deduce the value of the given non-type template parameter
478/// from the given declaration.
479///
480/// \returns true if deduction succeeded, false otherwise.
481static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
482 Sema &S, TemplateParameterList *TemplateParams,
483 const NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
484 TemplateDeductionInfo &Info,
485 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
486 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
487 TemplateArgument New(D, T);
488 return DeduceNonTypeTemplateArgument(
489 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
490}
491
492static Sema::TemplateDeductionResult
493DeduceTemplateArguments(Sema &S,
494 TemplateParameterList *TemplateParams,
495 TemplateName Param,
496 TemplateName Arg,
497 TemplateDeductionInfo &Info,
498 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
499 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
500 if (!ParamDecl) {
501 // The parameter type is dependent and is not a template template parameter,
502 // so there is nothing that we can deduce.
503 return Sema::TDK_Success;
504 }
505
506 if (TemplateTemplateParmDecl *TempParam
507 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
508 // If we're not deducing at this depth, there's nothing to deduce.
509 if (TempParam->getDepth() != Info.getDeducedDepth())
510 return Sema::TDK_Success;
511
512 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
513 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
514 Deduced[TempParam->getIndex()],
515 NewDeduced);
516 if (Result.isNull()) {
517 Info.Param = TempParam;
518 Info.FirstArg = Deduced[TempParam->getIndex()];
519 Info.SecondArg = NewDeduced;
520 return Sema::TDK_Inconsistent;
521 }
522
523 Deduced[TempParam->getIndex()] = Result;
524 return Sema::TDK_Success;
525 }
526
527 // Verify that the two template names are equivalent.
528 if (S.Context.hasSameTemplateName(Param, Arg))
529 return Sema::TDK_Success;
530
531 // Mismatch of non-dependent template parameter to argument.
532 Info.FirstArg = TemplateArgument(Param);
533 Info.SecondArg = TemplateArgument(Arg);
534 return Sema::TDK_NonDeducedMismatch;
535}
536
537/// Deduce the template arguments by comparing the template parameter
538/// type (which is a template-id) with the template argument type.
539///
540/// \param S the Sema
541///
542/// \param TemplateParams the template parameters that we are deducing
543///
544/// \param P the parameter type
545///
546/// \param A the argument type
547///
548/// \param Info information about the template argument deduction itself
549///
550/// \param Deduced the deduced template arguments
551///
552/// \returns the result of template argument deduction so far. Note that a
553/// "success" result means that template argument deduction has not yet failed,
554/// but it may still fail, later, for other reasons.
555static Sema::TemplateDeductionResult
556DeduceTemplateSpecArguments(Sema &S, TemplateParameterList *TemplateParams,
557 const QualType P, QualType A,
558 TemplateDeductionInfo &Info,
559 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
560 QualType UP = P;
561 if (const auto *IP = P->getAs<InjectedClassNameType>())
562 UP = IP->getInjectedSpecializationType();
563 // FIXME: Try to preserve type sugar here, which is hard
564 // because of the unresolved template arguments.
565 const auto *TP = UP.getCanonicalType()->castAs<TemplateSpecializationType>();
566 TemplateName TNP = TP->getTemplateName();
567
568 // If the parameter is an alias template, there is nothing to deduce.
569 if (const auto *TD = TNP.getAsTemplateDecl(); TD && TD->isTypeAlias())
570 return Sema::TDK_Success;
571
572 ArrayRef<TemplateArgument> PResolved = TP->template_arguments();
573
574 QualType UA = A;
575 // Treat an injected-class-name as its underlying template-id.
576 if (const auto *Injected = A->getAs<InjectedClassNameType>())
577 UA = Injected->getInjectedSpecializationType();
578
579 // Check whether the template argument is a dependent template-id.
580 // FIXME: Should not lose sugar here.
581 if (const auto *SA =
582 dyn_cast<TemplateSpecializationType>(UA.getCanonicalType())) {
583 TemplateName TNA = SA->getTemplateName();
584
585 // If the argument is an alias template, there is nothing to deduce.
586 if (const auto *TD = TNA.getAsTemplateDecl(); TD && TD->isTypeAlias())
587 return Sema::TDK_Success;
588
589 // Perform template argument deduction for the template name.
590 if (auto Result =
591 DeduceTemplateArguments(S, TemplateParams, TNP, TNA, Info, Deduced))
592 return Result;
593 // Perform template argument deduction on each template
594 // argument. Ignore any missing/extra arguments, since they could be
595 // filled in by default arguments.
596 return DeduceTemplateArguments(S, TemplateParams, PResolved,
597 SA->template_arguments(), Info, Deduced,
598 /*NumberOfArgumentsMustMatch=*/false);
599 }
600
601 // If the argument type is a class template specialization, we
602 // perform template argument deduction using its template
603 // arguments.
604 const auto *RA = UA->getAs<RecordType>();
605 const auto *SA =
606 RA ? dyn_cast<ClassTemplateSpecializationDecl>(RA->getDecl()) : nullptr;
607 if (!SA) {
608 Info.FirstArg = TemplateArgument(P);
609 Info.SecondArg = TemplateArgument(A);
610 return Sema::TDK_NonDeducedMismatch;
611 }
612
613 // Perform template argument deduction for the template name.
614 if (auto Result = DeduceTemplateArguments(
615 S, TemplateParams, TP->getTemplateName(),
616 TemplateName(SA->getSpecializedTemplate()), Info, Deduced))
617 return Result;
618
619 // Perform template argument deduction for the template arguments.
620 return DeduceTemplateArguments(S, TemplateParams, PResolved,
621 SA->getTemplateArgs().asArray(), Info, Deduced,
622 /*NumberOfArgumentsMustMatch=*/true);
623}
624
625static bool IsPossiblyOpaquelyQualifiedTypeInternal(const Type *T) {
626 assert(T->isCanonicalUnqualified())(static_cast <bool> (T->isCanonicalUnqualified()) ? void
(0) : __assert_fail ("T->isCanonicalUnqualified()", "clang/lib/Sema/SemaTemplateDeduction.cpp"
, 626, __extension__ __PRETTY_FUNCTION__))
;
627
628 switch (T->getTypeClass()) {
629 case Type::TypeOfExpr:
630 case Type::TypeOf:
631 case Type::DependentName:
632 case Type::Decltype:
633 case Type::UnresolvedUsing:
634 case Type::TemplateTypeParm:
635 return true;
636
637 case Type::ConstantArray:
638 case Type::IncompleteArray:
639 case Type::VariableArray:
640 case Type::DependentSizedArray:
641 return IsPossiblyOpaquelyQualifiedTypeInternal(
642 cast<ArrayType>(T)->getElementType().getTypePtr());
643
644 default:
645 return false;
646 }
647}
648
649/// Determines whether the given type is an opaque type that
650/// might be more qualified when instantiated.
651static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
652 return IsPossiblyOpaquelyQualifiedTypeInternal(
653 T->getCanonicalTypeInternal().getTypePtr());
654}
655
656/// Helper function to build a TemplateParameter when we don't
657/// know its type statically.
658static TemplateParameter makeTemplateParameter(Decl *D) {
659 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
660 return TemplateParameter(TTP);
661 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
662 return TemplateParameter(NTTP);
663
664 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
665}
666
667/// A pack that we're currently deducing.
668struct clang::DeducedPack {
669 // The index of the pack.
670 unsigned Index;
671
672 // The old value of the pack before we started deducing it.
673 DeducedTemplateArgument Saved;
674
675 // A deferred value of this pack from an inner deduction, that couldn't be
676 // deduced because this deduction hadn't happened yet.
677 DeducedTemplateArgument DeferredDeduction;
678
679 // The new value of the pack.
680 SmallVector<DeducedTemplateArgument, 4> New;
681
682 // The outer deduction for this pack, if any.
683 DeducedPack *Outer = nullptr;
684
685 DeducedPack(unsigned Index) : Index(Index) {}
686};
687
688namespace {
689
690/// A scope in which we're performing pack deduction.
691class PackDeductionScope {
692public:
693 /// Prepare to deduce the packs named within Pattern.
694 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
695 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
696 TemplateDeductionInfo &Info, TemplateArgument Pattern)
697 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
698 unsigned NumNamedPacks = addPacks(Pattern);
699 finishConstruction(NumNamedPacks);
700 }
701
702 /// Prepare to directly deduce arguments of the parameter with index \p Index.
703 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
704 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
705 TemplateDeductionInfo &Info, unsigned Index)
706 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
707 addPack(Index);
708 finishConstruction(1);
709 }
710
711private:
712 void addPack(unsigned Index) {
713 // Save the deduced template argument for the parameter pack expanded
714 // by this pack expansion, then clear out the deduction.
715 DeducedPack Pack(Index);
716 Pack.Saved = Deduced[Index];
717 Deduced[Index] = TemplateArgument();
718
719 // FIXME: What if we encounter multiple packs with different numbers of
720 // pre-expanded expansions? (This should already have been diagnosed
721 // during substitution.)
722 if (std::optional<unsigned> ExpandedPackExpansions =
723 getExpandedPackSize(TemplateParams->getParam(Index)))
724 FixedNumExpansions = ExpandedPackExpansions;
725
726 Packs.push_back(Pack);
727 }
728
729 unsigned addPacks(TemplateArgument Pattern) {
730 // Compute the set of template parameter indices that correspond to
731 // parameter packs expanded by the pack expansion.
732 llvm::SmallBitVector SawIndices(TemplateParams->size());
733 llvm::SmallVector<TemplateArgument, 4> ExtraDeductions;
734
735 auto AddPack = [&](unsigned Index) {
736 if (SawIndices[Index])
737 return;
738 SawIndices[Index] = true;
739 addPack(Index);
740
741 // Deducing a parameter pack that is a pack expansion also constrains the
742 // packs appearing in that parameter to have the same deduced arity. Also,
743 // in C++17 onwards, deducing a non-type template parameter deduces its
744 // type, so we need to collect the pending deduced values for those packs.
745 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(
746 TemplateParams->getParam(Index))) {
747 if (!NTTP->isExpandedParameterPack())
748 if (auto *Expansion = dyn_cast<PackExpansionType>(NTTP->getType()))
749 ExtraDeductions.push_back(Expansion->getPattern());
750 }
751 // FIXME: Also collect the unexpanded packs in any type and template
752 // parameter packs that are pack expansions.
753 };
754
755 auto Collect = [&](TemplateArgument Pattern) {
756 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
757 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
758 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
759 UnexpandedParameterPack U = Unexpanded[I];
760 if (U.first.is<const SubstTemplateTypeParmPackType *>() ||
761 U.first.is<const SubstNonTypeTemplateParmPackExpr *>())
762 continue;
763 auto [Depth, Index] = getDepthAndIndex(U);
764 if (Depth == Info.getDeducedDepth())
765 AddPack(Index);
766 }
767 };
768
769 // Look for unexpanded packs in the pattern.
770 Collect(Pattern);
771 assert(!Packs.empty() && "Pack expansion without unexpanded packs?")(static_cast <bool> (!Packs.empty() && "Pack expansion without unexpanded packs?"
) ? void (0) : __assert_fail ("!Packs.empty() && \"Pack expansion without unexpanded packs?\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 771, __extension__
__PRETTY_FUNCTION__))
;
772
773 unsigned NumNamedPacks = Packs.size();
774
775 // Also look for unexpanded packs that are indirectly deduced by deducing
776 // the sizes of the packs in this pattern.
777 while (!ExtraDeductions.empty())
778 Collect(ExtraDeductions.pop_back_val());
779
780 return NumNamedPacks;
781 }
782
783 void finishConstruction(unsigned NumNamedPacks) {
784 // Dig out the partially-substituted pack, if there is one.
785 const TemplateArgument *PartialPackArgs = nullptr;
786 unsigned NumPartialPackArgs = 0;
787 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
788 if (auto *Scope = S.CurrentInstantiationScope)
789 if (auto *Partial = Scope->getPartiallySubstitutedPack(
790 &PartialPackArgs, &NumPartialPackArgs))
791 PartialPackDepthIndex = getDepthAndIndex(Partial);
792
793 // This pack expansion will have been partially or fully expanded if
794 // it only names explicitly-specified parameter packs (including the
795 // partially-substituted one, if any).
796 bool IsExpanded = true;
797 for (unsigned I = 0; I != NumNamedPacks; ++I) {
798 if (Packs[I].Index >= Info.getNumExplicitArgs()) {
799 IsExpanded = false;
800 IsPartiallyExpanded = false;
801 break;
802 }
803 if (PartialPackDepthIndex ==
804 std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
805 IsPartiallyExpanded = true;
806 }
807 }
808
809 // Skip over the pack elements that were expanded into separate arguments.
810 // If we partially expanded, this is the number of partial arguments.
811 if (IsPartiallyExpanded)
812 PackElements += NumPartialPackArgs;
813 else if (IsExpanded)
814 PackElements += *FixedNumExpansions;
815
816 for (auto &Pack : Packs) {
817 if (Info.PendingDeducedPacks.size() > Pack.Index)
818 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
819 else
820 Info.PendingDeducedPacks.resize(Pack.Index + 1);
821 Info.PendingDeducedPacks[Pack.Index] = &Pack;
822
823 if (PartialPackDepthIndex ==
824 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
825 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
826 // We pre-populate the deduced value of the partially-substituted
827 // pack with the specified value. This is not entirely correct: the
828 // value is supposed to have been substituted, not deduced, but the
829 // cases where this is observable require an exact type match anyway.
830 //
831 // FIXME: If we could represent a "depth i, index j, pack elem k"
832 // parameter, we could substitute the partially-substituted pack
833 // everywhere and avoid this.
834 if (!IsPartiallyExpanded)
835 Deduced[Pack.Index] = Pack.New[PackElements];
836 }
837 }
838 }
839
840public:
841 ~PackDeductionScope() {
842 for (auto &Pack : Packs)
843 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
844 }
845
846 /// Determine whether this pack has already been partially expanded into a
847 /// sequence of (prior) function parameters / template arguments.
848 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
849
850 /// Determine whether this pack expansion scope has a known, fixed arity.
851 /// This happens if it involves a pack from an outer template that has
852 /// (notionally) already been expanded.
853 bool hasFixedArity() { return FixedNumExpansions.has_value(); }
854
855 /// Determine whether the next element of the argument is still part of this
856 /// pack. This is the case unless the pack is already expanded to a fixed
857 /// length.
858 bool hasNextElement() {
859 return !FixedNumExpansions || *FixedNumExpansions > PackElements;
860 }
861
862 /// Move to deducing the next element in each pack that is being deduced.
863 void nextPackElement() {
864 // Capture the deduced template arguments for each parameter pack expanded
865 // by this pack expansion, add them to the list of arguments we've deduced
866 // for that pack, then clear out the deduced argument.
867 for (auto &Pack : Packs) {
868 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
869 if (!Pack.New.empty() || !DeducedArg.isNull()) {
870 while (Pack.New.size() < PackElements)
871 Pack.New.push_back(DeducedTemplateArgument());
872 if (Pack.New.size() == PackElements)
873 Pack.New.push_back(DeducedArg);
874 else
875 Pack.New[PackElements] = DeducedArg;
876 DeducedArg = Pack.New.size() > PackElements + 1
877 ? Pack.New[PackElements + 1]
878 : DeducedTemplateArgument();
879 }
880 }
881 ++PackElements;
882 }
883
884 /// Finish template argument deduction for a set of argument packs,
885 /// producing the argument packs and checking for consistency with prior
886 /// deductions.
887 Sema::TemplateDeductionResult finish() {
888 // Build argument packs for each of the parameter packs expanded by this
889 // pack expansion.
890 for (auto &Pack : Packs) {
891 // Put back the old value for this pack.
892 Deduced[Pack.Index] = Pack.Saved;
893
894 // Always make sure the size of this pack is correct, even if we didn't
895 // deduce any values for it.
896 //
897 // FIXME: This isn't required by the normative wording, but substitution
898 // and post-substitution checking will always fail if the arity of any
899 // pack is not equal to the number of elements we processed. (Either that
900 // or something else has gone *very* wrong.) We're permitted to skip any
901 // hard errors from those follow-on steps by the intent (but not the
902 // wording) of C++ [temp.inst]p8:
903 //
904 // If the function selected by overload resolution can be determined
905 // without instantiating a class template definition, it is unspecified
906 // whether that instantiation actually takes place
907 Pack.New.resize(PackElements);
908
909 // Build or find a new value for this pack.
910 DeducedTemplateArgument NewPack;
911 if (Pack.New.empty()) {
912 // If we deduced an empty argument pack, create it now.
913 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
914 } else {
915 TemplateArgument *ArgumentPack =
916 new (S.Context) TemplateArgument[Pack.New.size()];
917 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
918 NewPack = DeducedTemplateArgument(
919 TemplateArgument(llvm::ArrayRef(ArgumentPack, Pack.New.size())),
920 // FIXME: This is wrong, it's possible that some pack elements are
921 // deduced from an array bound and others are not:
922 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
923 // g({1, 2, 3}, {{}, {}});
924 // ... should deduce T = {int, size_t (from array bound)}.
925 Pack.New[0].wasDeducedFromArrayBound());
926 }
927
928 // Pick where we're going to put the merged pack.
929 DeducedTemplateArgument *Loc;
930 if (Pack.Outer) {
931 if (Pack.Outer->DeferredDeduction.isNull()) {
932 // Defer checking this pack until we have a complete pack to compare
933 // it against.
934 Pack.Outer->DeferredDeduction = NewPack;
935 continue;
936 }
937 Loc = &Pack.Outer->DeferredDeduction;
938 } else {
939 Loc = &Deduced[Pack.Index];
940 }
941
942 // Check the new pack matches any previous value.
943 DeducedTemplateArgument OldPack = *Loc;
944 DeducedTemplateArgument Result =
945 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
946
947 // If we deferred a deduction of this pack, check that one now too.
948 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
949 OldPack = Result;
950 NewPack = Pack.DeferredDeduction;
951 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
952 }
953
954 NamedDecl *Param = TemplateParams->getParam(Pack.Index);
955 if (Result.isNull()) {
956 Info.Param = makeTemplateParameter(Param);
957 Info.FirstArg = OldPack;
958 Info.SecondArg = NewPack;
959 return Sema::TDK_Inconsistent;
960 }
961
962 // If we have a pre-expanded pack and we didn't deduce enough elements
963 // for it, fail deduction.
964 if (std::optional<unsigned> Expansions = getExpandedPackSize(Param)) {
965 if (*Expansions != PackElements) {
966 Info.Param = makeTemplateParameter(Param);
967 Info.FirstArg = Result;
968 return Sema::TDK_IncompletePack;
969 }
970 }
971
972 *Loc = Result;
973 }
974
975 return Sema::TDK_Success;
976 }
977
978private:
979 Sema &S;
980 TemplateParameterList *TemplateParams;
981 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
982 TemplateDeductionInfo &Info;
983 unsigned PackElements = 0;
984 bool IsPartiallyExpanded = false;
985 /// The number of expansions, if we have a fully-expanded pack in this scope.
986 std::optional<unsigned> FixedNumExpansions;
987
988 SmallVector<DeducedPack, 2> Packs;
989};
990
991} // namespace
992
993/// Deduce the template arguments by comparing the list of parameter
994/// types to the list of argument types, as in the parameter-type-lists of
995/// function types (C++ [temp.deduct.type]p10).
996///
997/// \param S The semantic analysis object within which we are deducing
998///
999/// \param TemplateParams The template parameters that we are deducing
1000///
1001/// \param Params The list of parameter types
1002///
1003/// \param NumParams The number of types in \c Params
1004///
1005/// \param Args The list of argument types
1006///
1007/// \param NumArgs The number of types in \c Args
1008///
1009/// \param Info information about the template argument deduction itself
1010///
1011/// \param Deduced the deduced template arguments
1012///
1013/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1014/// how template argument deduction is performed.
1015///
1016/// \param PartialOrdering If true, we are performing template argument
1017/// deduction for during partial ordering for a call
1018/// (C++0x [temp.deduct.partial]).
1019///
1020/// \returns the result of template argument deduction so far. Note that a
1021/// "success" result means that template argument deduction has not yet failed,
1022/// but it may still fail, later, for other reasons.
1023static Sema::TemplateDeductionResult
1024DeduceTemplateArguments(Sema &S,
1025 TemplateParameterList *TemplateParams,
1026 const QualType *Params, unsigned NumParams,
1027 const QualType *Args, unsigned NumArgs,
1028 TemplateDeductionInfo &Info,
1029 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1030 unsigned TDF,
1031 bool PartialOrdering = false) {
1032 // C++0x [temp.deduct.type]p10:
1033 // Similarly, if P has a form that contains (T), then each parameter type
1034 // Pi of the respective parameter-type- list of P is compared with the
1035 // corresponding parameter type Ai of the corresponding parameter-type-list
1036 // of A. [...]
1037 unsigned ArgIdx = 0, ParamIdx = 0;
1038 for (; ParamIdx != NumParams; ++ParamIdx) {
1039 // Check argument types.
1040 const PackExpansionType *Expansion
1041 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
1042 if (!Expansion) {
1043 // Simple case: compare the parameter and argument types at this point.
1044
1045 // Make sure we have an argument.
1046 if (ArgIdx >= NumArgs)
1047 return Sema::TDK_MiscellaneousDeductionFailure;
1048
1049 if (isa<PackExpansionType>(Args[ArgIdx])) {
1050 // C++0x [temp.deduct.type]p22:
1051 // If the original function parameter associated with A is a function
1052 // parameter pack and the function parameter associated with P is not
1053 // a function parameter pack, then template argument deduction fails.
1054 return Sema::TDK_MiscellaneousDeductionFailure;
1055 }
1056
1057 if (Sema::TemplateDeductionResult Result =
1058 DeduceTemplateArgumentsByTypeMatch(
1059 S, TemplateParams, Params[ParamIdx].getUnqualifiedType(),
1060 Args[ArgIdx].getUnqualifiedType(), Info, Deduced, TDF,
1061 PartialOrdering,
1062 /*DeducedFromArrayBound=*/false))
1063 return Result;
1064
1065 ++ArgIdx;
1066 continue;
1067 }
1068
1069 // C++0x [temp.deduct.type]p10:
1070 // If the parameter-declaration corresponding to Pi is a function
1071 // parameter pack, then the type of its declarator- id is compared with
1072 // each remaining parameter type in the parameter-type-list of A. Each
1073 // comparison deduces template arguments for subsequent positions in the
1074 // template parameter packs expanded by the function parameter pack.
1075
1076 QualType Pattern = Expansion->getPattern();
1077 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
1078
1079 // A pack scope with fixed arity is not really a pack any more, so is not
1080 // a non-deduced context.
1081 if (ParamIdx + 1 == NumParams || PackScope.hasFixedArity()) {
1082 for (; ArgIdx < NumArgs && PackScope.hasNextElement(); ++ArgIdx) {
1083 // Deduce template arguments from the pattern.
1084 if (Sema::TemplateDeductionResult Result =
1085 DeduceTemplateArgumentsByTypeMatch(
1086 S, TemplateParams, Pattern.getUnqualifiedType(),
1087 Args[ArgIdx].getUnqualifiedType(), Info, Deduced, TDF,
1088 PartialOrdering, /*DeducedFromArrayBound=*/false))
1089 return Result;
1090
1091 PackScope.nextPackElement();
1092 }
1093 } else {
1094 // C++0x [temp.deduct.type]p5:
1095 // The non-deduced contexts are:
1096 // - A function parameter pack that does not occur at the end of the
1097 // parameter-declaration-clause.
1098 //
1099 // FIXME: There is no wording to say what we should do in this case. We
1100 // choose to resolve this by applying the same rule that is applied for a
1101 // function call: that is, deduce all contained packs to their
1102 // explicitly-specified values (or to <> if there is no such value).
1103 //
1104 // This is seemingly-arbitrarily different from the case of a template-id
1105 // with a non-trailing pack-expansion in its arguments, which renders the
1106 // entire template-argument-list a non-deduced context.
1107
1108 // If the parameter type contains an explicitly-specified pack that we
1109 // could not expand, skip the number of parameters notionally created
1110 // by the expansion.
1111 std::optional<unsigned> NumExpansions = Expansion->getNumExpansions();
1112 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
1113 for (unsigned I = 0; I != *NumExpansions && ArgIdx < NumArgs;
1114 ++I, ++ArgIdx)
1115 PackScope.nextPackElement();
1116 }
1117 }
1118
1119 // Build argument packs for each of the parameter packs expanded by this
1120 // pack expansion.
1121 if (auto Result = PackScope.finish())
1122 return Result;
1123 }
1124
1125 // DR692, DR1395
1126 // C++0x [temp.deduct.type]p10:
1127 // If the parameter-declaration corresponding to P_i ...
1128 // During partial ordering, if Ai was originally a function parameter pack:
1129 // - if P does not contain a function parameter type corresponding to Ai then
1130 // Ai is ignored;
1131 if (PartialOrdering && ArgIdx + 1 == NumArgs &&
1132 isa<PackExpansionType>(Args[ArgIdx]))
1133 return Sema::TDK_Success;
1134
1135 // Make sure we don't have any extra arguments.
1136 if (ArgIdx < NumArgs)
1137 return Sema::TDK_MiscellaneousDeductionFailure;
1138
1139 return Sema::TDK_Success;
1140}
1141
1142/// Determine whether the parameter has qualifiers that the argument
1143/// lacks. Put another way, determine whether there is no way to add
1144/// a deduced set of qualifiers to the ParamType that would result in
1145/// its qualifiers matching those of the ArgType.
1146static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
1147 QualType ArgType) {
1148 Qualifiers ParamQs = ParamType.getQualifiers();
1149 Qualifiers ArgQs = ArgType.getQualifiers();
1150
1151 if (ParamQs == ArgQs)
1152 return false;
1153
1154 // Mismatched (but not missing) Objective-C GC attributes.
1155 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
1156 ParamQs.hasObjCGCAttr())
1157 return true;
1158
1159 // Mismatched (but not missing) address spaces.
1160 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
1161 ParamQs.hasAddressSpace())
1162 return true;
1163
1164 // Mismatched (but not missing) Objective-C lifetime qualifiers.
1165 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
1166 ParamQs.hasObjCLifetime())
1167 return true;
1168
1169 // CVR qualifiers inconsistent or a superset.
1170 return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
1171}
1172
1173/// Compare types for equality with respect to possibly compatible
1174/// function types (noreturn adjustment, implicit calling conventions). If any
1175/// of parameter and argument is not a function, just perform type comparison.
1176///
1177/// \param P the template parameter type.
1178///
1179/// \param A the argument type.
1180bool Sema::isSameOrCompatibleFunctionType(QualType P, QualType A) {
1181 const FunctionType *PF = P->getAs<FunctionType>(),
1182 *AF = A->getAs<FunctionType>();
1183
1184 // Just compare if not functions.
1185 if (!PF || !AF)
1186 return Context.hasSameType(P, A);
1187
1188 // Noreturn and noexcept adjustment.
1189 QualType AdjustedParam;
1190 if (IsFunctionConversion(P, A, AdjustedParam))
1191 return Context.hasSameType(AdjustedParam, A);
1192
1193 // FIXME: Compatible calling conventions.
1194
1195 return Context.hasSameType(P, A);
1196}
1197
1198/// Get the index of the first template parameter that was originally from the
1199/// innermost template-parameter-list. This is 0 except when we concatenate
1200/// the template parameter lists of a class template and a constructor template
1201/// when forming an implicit deduction guide.
1202static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD) {
1203 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1204 if (!Guide || !Guide->isImplicit())
1205 return 0;
1206 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
1207}
1208
1209/// Determine whether a type denotes a forwarding reference.
1210static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1211 // C++1z [temp.deduct.call]p3:
1212 // A forwarding reference is an rvalue reference to a cv-unqualified
1213 // template parameter that does not represent a template parameter of a
1214 // class template.
1215 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1216 if (ParamRef->getPointeeType().getQualifiers())
1217 return false;
1218 auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
1219 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1220 }
1221 return false;
1222}
1223
1224static CXXRecordDecl *getCanonicalRD(QualType T) {
1225 return cast<CXXRecordDecl>(
1226 T->castAs<RecordType>()->getDecl()->getCanonicalDecl());
1227}
1228
1229/// Attempt to deduce the template arguments by checking the base types
1230/// according to (C++20 [temp.deduct.call] p4b3.
1231///
1232/// \param S the semantic analysis object within which we are deducing.
1233///
1234/// \param RD the top level record object we are deducing against.
1235///
1236/// \param TemplateParams the template parameters that we are deducing.
1237///
1238/// \param P the template specialization parameter type.
1239///
1240/// \param Info information about the template argument deduction itself.
1241///
1242/// \param Deduced the deduced template arguments.
1243///
1244/// \returns the result of template argument deduction with the bases. "invalid"
1245/// means no matches, "success" found a single item, and the
1246/// "MiscellaneousDeductionFailure" result happens when the match is ambiguous.
1247static Sema::TemplateDeductionResult
1248DeduceTemplateBases(Sema &S, const CXXRecordDecl *RD,
1249 TemplateParameterList *TemplateParams, QualType P,
1250 TemplateDeductionInfo &Info,
1251 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
1252 // C++14 [temp.deduct.call] p4b3:
1253 // If P is a class and P has the form simple-template-id, then the
1254 // transformed A can be a derived class of the deduced A. Likewise if
1255 // P is a pointer to a class of the form simple-template-id, the
1256 // transformed A can be a pointer to a derived class pointed to by the
1257 // deduced A. However, if there is a class C that is a (direct or
1258 // indirect) base class of D and derived (directly or indirectly) from a
1259 // class B and that would be a valid deduced A, the deduced A cannot be
1260 // B or pointer to B, respectively.
1261 //
1262 // These alternatives are considered only if type deduction would
1263 // otherwise fail. If they yield more than one possible deduced A, the
1264 // type deduction fails.
1265
1266 // Use a breadth-first search through the bases to collect the set of
1267 // successful matches. Visited contains the set of nodes we have already
1268 // visited, while ToVisit is our stack of records that we still need to
1269 // visit. Matches contains a list of matches that have yet to be
1270 // disqualified.
1271 llvm::SmallPtrSet<const CXXRecordDecl *, 8> Visited;
1272 SmallVector<QualType, 8> ToVisit;
1273 // We iterate over this later, so we have to use MapVector to ensure
1274 // determinism.
1275 llvm::MapVector<const CXXRecordDecl *,
1276 SmallVector<DeducedTemplateArgument, 8>>
1277 Matches;
1278
1279 auto AddBases = [&Visited, &ToVisit](const CXXRecordDecl *RD) {
1280 for (const auto &Base : RD->bases()) {
1281 QualType T = Base.getType();
1282 assert(T->isRecordType() && "Base class that isn't a record?")(static_cast <bool> (T->isRecordType() && "Base class that isn't a record?"
) ? void (0) : __assert_fail ("T->isRecordType() && \"Base class that isn't a record?\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 1282, __extension__
__PRETTY_FUNCTION__))
;
1283 if (Visited.insert(::getCanonicalRD(T)).second)
1284 ToVisit.push_back(T);
1285 }
1286 };
1287
1288 // Set up the loop by adding all the bases.
1289 AddBases(RD);
1290
1291 // Search each path of bases until we either run into a successful match
1292 // (where all bases of it are invalid), or we run out of bases.
1293 while (!ToVisit.empty()) {
1294 QualType NextT = ToVisit.pop_back_val();
1295
1296 SmallVector<DeducedTemplateArgument, 8> DeducedCopy(Deduced.begin(),
1297 Deduced.end());
1298 TemplateDeductionInfo BaseInfo(TemplateDeductionInfo::ForBase, Info);
1299 Sema::TemplateDeductionResult BaseResult = DeduceTemplateSpecArguments(
1300 S, TemplateParams, P, NextT, BaseInfo, DeducedCopy);
1301
1302 // If this was a successful deduction, add it to the list of matches,
1303 // otherwise we need to continue searching its bases.
1304 const CXXRecordDecl *RD = ::getCanonicalRD(NextT);
1305 if (BaseResult == Sema::TDK_Success)
1306 Matches.insert({RD, DeducedCopy});
1307 else
1308 AddBases(RD);
1309 }
1310
1311 // At this point, 'Matches' contains a list of seemingly valid bases, however
1312 // in the event that we have more than 1 match, it is possible that the base
1313 // of one of the matches might be disqualified for being a base of another
1314 // valid match. We can count on cyclical instantiations being invalid to
1315 // simplify the disqualifications. That is, if A & B are both matches, and B
1316 // inherits from A (disqualifying A), we know that A cannot inherit from B.
1317 if (Matches.size() > 1) {
1318 Visited.clear();
1319 for (const auto &Match : Matches)
1320 AddBases(Match.first);
1321
1322 // We can give up once we have a single item (or have run out of things to
1323 // search) since cyclical inheritance isn't valid.
1324 while (Matches.size() > 1 && !ToVisit.empty()) {
1325 const CXXRecordDecl *RD = ::getCanonicalRD(ToVisit.pop_back_val());
1326 Matches.erase(RD);
1327
1328 // Always add all bases, since the inheritance tree can contain
1329 // disqualifications for multiple matches.
1330 AddBases(RD);
1331 }
1332 }
1333
1334 if (Matches.empty())
1335 return Sema::TDK_Invalid;
1336 if (Matches.size() > 1)
1337 return Sema::TDK_MiscellaneousDeductionFailure;
1338
1339 std::swap(Matches.front().second, Deduced);
1340 return Sema::TDK_Success;
1341}
1342
1343/// Deduce the template arguments by comparing the parameter type and
1344/// the argument type (C++ [temp.deduct.type]).
1345///
1346/// \param S the semantic analysis object within which we are deducing
1347///
1348/// \param TemplateParams the template parameters that we are deducing
1349///
1350/// \param P the parameter type
1351///
1352/// \param A the argument type
1353///
1354/// \param Info information about the template argument deduction itself
1355///
1356/// \param Deduced the deduced template arguments
1357///
1358/// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1359/// how template argument deduction is performed.
1360///
1361/// \param PartialOrdering Whether we're performing template argument deduction
1362/// in the context of partial ordering (C++0x [temp.deduct.partial]).
1363///
1364/// \returns the result of template argument deduction so far. Note that a
1365/// "success" result means that template argument deduction has not yet failed,
1366/// but it may still fail, later, for other reasons.
1367static Sema::TemplateDeductionResult DeduceTemplateArgumentsByTypeMatch(
1368 Sema &S, TemplateParameterList *TemplateParams, QualType P, QualType A,
1369 TemplateDeductionInfo &Info,
1370 SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF,
1371 bool PartialOrdering, bool DeducedFromArrayBound) {
1372
1373 // If the argument type is a pack expansion, look at its pattern.
1374 // This isn't explicitly called out
1375 if (const auto *AExp
0.1
'AExp' is null
= dyn_cast<PackExpansionType>(A))
1
Taking false branch
1376 A = AExp->getPattern();
1377 assert(!isa<PackExpansionType>(A.getCanonicalType()))(static_cast <bool> (!isa<PackExpansionType>(A.getCanonicalType
())) ? void (0) : __assert_fail ("!isa<PackExpansionType>(A.getCanonicalType())"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 1377, __extension__
__PRETTY_FUNCTION__))
;
2
Assuming the object is not a 'PackExpansionType'
3
'?' condition is true
1378
1379 if (PartialOrdering) {
4
Assuming 'PartialOrdering' is false
5
Taking false branch
1380 // C++11 [temp.deduct.partial]p5:
1381 // Before the partial ordering is done, certain transformations are
1382 // performed on the types used for partial ordering:
1383 // - If P is a reference type, P is replaced by the type referred to.
1384 const ReferenceType *PRef = P->getAs<ReferenceType>();
1385 if (PRef)
1386 P = PRef->getPointeeType();
1387
1388 // - If A is a reference type, A is replaced by the type referred to.
1389 const ReferenceType *ARef = A->getAs<ReferenceType>();
1390 if (ARef)
1391 A = A->getPointeeType();
1392
1393 if (PRef && ARef && S.Context.hasSameUnqualifiedType(P, A)) {
1394 // C++11 [temp.deduct.partial]p9:
1395 // If, for a given type, deduction succeeds in both directions (i.e.,
1396 // the types are identical after the transformations above) and both
1397 // P and A were reference types [...]:
1398 // - if [one type] was an lvalue reference and [the other type] was
1399 // not, [the other type] is not considered to be at least as
1400 // specialized as [the first type]
1401 // - if [one type] is more cv-qualified than [the other type],
1402 // [the other type] is not considered to be at least as specialized
1403 // as [the first type]
1404 // Objective-C ARC adds:
1405 // - [one type] has non-trivial lifetime, [the other type] has
1406 // __unsafe_unretained lifetime, and the types are otherwise
1407 // identical
1408 //
1409 // A is "considered to be at least as specialized" as P iff deduction
1410 // succeeds, so we model this as a deduction failure. Note that
1411 // [the first type] is P and [the other type] is A here; the standard
1412 // gets this backwards.
1413 Qualifiers PQuals = P.getQualifiers(), AQuals = A.getQualifiers();
1414 if ((PRef->isLValueReferenceType() && !ARef->isLValueReferenceType()) ||
1415 PQuals.isStrictSupersetOf(AQuals) ||
1416 (PQuals.hasNonTrivialObjCLifetime() &&
1417 AQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1418 PQuals.withoutObjCLifetime() == AQuals.withoutObjCLifetime())) {
1419 Info.FirstArg = TemplateArgument(P);
1420 Info.SecondArg = TemplateArgument(A);
1421 return Sema::TDK_NonDeducedMismatch;
1422 }
1423 }
1424 Qualifiers DiscardedQuals;
1425 // C++11 [temp.deduct.partial]p7:
1426 // Remove any top-level cv-qualifiers:
1427 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
1428 // version of P.
1429 P = S.Context.getUnqualifiedArrayType(P, DiscardedQuals);
1430 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
1431 // version of A.
1432 A = S.Context.getUnqualifiedArrayType(A, DiscardedQuals);
1433 } else {
1434 // C++0x [temp.deduct.call]p4 bullet 1:
1435 // - If the original P is a reference type, the deduced A (i.e., the type
1436 // referred to by the reference) can be more cv-qualified than the
1437 // transformed A.
1438 if (TDF & TDF_ParamWithReferenceType) {
6
Assuming the condition is false
1439 Qualifiers Quals;
1440 QualType UnqualP = S.Context.getUnqualifiedArrayType(P, Quals);
1441 Quals.setCVRQualifiers(Quals.getCVRQualifiers() & A.getCVRQualifiers());
1442 P = S.Context.getQualifiedType(UnqualP, Quals);
1443 }
1444
1445 if ((TDF & TDF_TopLevelParameterTypeList) && !P->isFunctionType()) {
7
Assuming the condition is false
1446 // C++0x [temp.deduct.type]p10:
1447 // If P and A are function types that originated from deduction when
1448 // taking the address of a function template (14.8.2.2) or when deducing
1449 // template arguments from a function declaration (14.8.2.6) and Pi and
1450 // Ai are parameters of the top-level parameter-type-list of P and A,
1451 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1452 // is an lvalue reference, in
1453 // which case the type of Pi is changed to be the template parameter
1454 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1455 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
1456 // deduced as X&. - end note ]
1457 TDF &= ~TDF_TopLevelParameterTypeList;
1458 if (isForwardingReference(P, /*FirstInnerIndex=*/0) &&
1459 A->isLValueReferenceType())
1460 P = P->getPointeeType();
1461 }
1462 }
1463
1464 // C++ [temp.deduct.type]p9:
1465 // A template type argument T, a template template argument TT or a
1466 // template non-type argument i can be deduced if P and A have one of
1467 // the following forms:
1468 //
1469 // T
1470 // cv-list T
1471 if (const auto *TTP
8.1
'TTP' is null
= P->getAs<TemplateTypeParmType>()) {
8
Assuming the object is not a 'const TemplateTypeParmType *'
9
Taking false branch
1472 // Just skip any attempts to deduce from a placeholder type or a parameter
1473 // at a different depth.
1474 if (A->isPlaceholderType() || Info.getDeducedDepth() != TTP->getDepth())
1475 return Sema::TDK_Success;
1476
1477 unsigned Index = TTP->getIndex();
1478
1479 // If the argument type is an array type, move the qualifiers up to the
1480 // top level, so they can be matched with the qualifiers on the parameter.
1481 if (A->isArrayType()) {
1482 Qualifiers Quals;
1483 A = S.Context.getUnqualifiedArrayType(A, Quals);
1484 if (Quals)
1485 A = S.Context.getQualifiedType(A, Quals);
1486 }
1487
1488 // The argument type can not be less qualified than the parameter
1489 // type.
1490 if (!(TDF & TDF_IgnoreQualifiers) &&
1491 hasInconsistentOrSupersetQualifiersOf(P, A)) {
1492 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1493 Info.FirstArg = TemplateArgument(P);
1494 Info.SecondArg = TemplateArgument(A);
1495 return Sema::TDK_Underqualified;
1496 }
1497
1498 // Do not match a function type with a cv-qualified type.
1499 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
1500 if (A->isFunctionType() && P.hasQualifiers())
1501 return Sema::TDK_NonDeducedMismatch;
1502
1503 assert(TTP->getDepth() == Info.getDeducedDepth() &&(static_cast <bool> (TTP->getDepth() == Info.getDeducedDepth
() && "saw template type parameter with wrong depth")
? void (0) : __assert_fail ("TTP->getDepth() == Info.getDeducedDepth() && \"saw template type parameter with wrong depth\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 1504, __extension__
__PRETTY_FUNCTION__))
1504 "saw template type parameter with wrong depth")(static_cast <bool> (TTP->getDepth() == Info.getDeducedDepth
() && "saw template type parameter with wrong depth")
? void (0) : __assert_fail ("TTP->getDepth() == Info.getDeducedDepth() && \"saw template type parameter with wrong depth\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 1504, __extension__
__PRETTY_FUNCTION__))
;
1505 assert(A->getCanonicalTypeInternal() != S.Context.OverloadTy &&(static_cast <bool> (A->getCanonicalTypeInternal() !=
S.Context.OverloadTy && "Unresolved overloaded function"
) ? void (0) : __assert_fail ("A->getCanonicalTypeInternal() != S.Context.OverloadTy && \"Unresolved overloaded function\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 1506, __extension__
__PRETTY_FUNCTION__))
1506 "Unresolved overloaded function")(static_cast <bool> (A->getCanonicalTypeInternal() !=
S.Context.OverloadTy && "Unresolved overloaded function"
) ? void (0) : __assert_fail ("A->getCanonicalTypeInternal() != S.Context.OverloadTy && \"Unresolved overloaded function\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 1506, __extension__
__PRETTY_FUNCTION__))
;
1507 QualType DeducedType = A;
1508
1509 // Remove any qualifiers on the parameter from the deduced type.
1510 // We checked the qualifiers for consistency above.
1511 Qualifiers DeducedQs = DeducedType.getQualifiers();
1512 Qualifiers ParamQs = P.getQualifiers();
1513 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1514 if (ParamQs.hasObjCGCAttr())
1515 DeducedQs.removeObjCGCAttr();
1516 if (ParamQs.hasAddressSpace())
1517 DeducedQs.removeAddressSpace();
1518 if (ParamQs.hasObjCLifetime())
1519 DeducedQs.removeObjCLifetime();
1520
1521 // Objective-C ARC:
1522 // If template deduction would produce a lifetime qualifier on a type
1523 // that is not a lifetime type, template argument deduction fails.
1524 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1525 !DeducedType->isDependentType()) {
1526 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1527 Info.FirstArg = TemplateArgument(P);
1528 Info.SecondArg = TemplateArgument(A);
1529 return Sema::TDK_Underqualified;
1530 }
1531
1532 // Objective-C ARC:
1533 // If template deduction would produce an argument type with lifetime type
1534 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1535 if (S.getLangOpts().ObjCAutoRefCount && DeducedType->isObjCLifetimeType() &&
1536 !DeducedQs.hasObjCLifetime())
1537 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
1538
1539 DeducedType =
1540 S.Context.getQualifiedType(DeducedType.getUnqualifiedType(), DeducedQs);
1541
1542 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
1543 DeducedTemplateArgument Result =
1544 checkDeducedTemplateArguments(S.Context, Deduced[Index], NewDeduced);
1545 if (Result.isNull()) {
1546 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1547 Info.FirstArg = Deduced[Index];
1548 Info.SecondArg = NewDeduced;
1549 return Sema::TDK_Inconsistent;
1550 }
1551
1552 Deduced[Index] = Result;
1553 return Sema::TDK_Success;
1554 }
1555
1556 // Set up the template argument deduction information for a failure.
1557 Info.FirstArg = TemplateArgument(P);
1558 Info.SecondArg = TemplateArgument(A);
1559
1560 // If the parameter is an already-substituted template parameter
1561 // pack, do nothing: we don't know which of its arguments to look
1562 // at, so we have to wait until all of the parameter packs in this
1563 // expansion have arguments.
1564 if (P->getAs<SubstTemplateTypeParmPackType>())
10
Assuming the object is not a 'const class clang::SubstTemplateTypeParmPackType *'
11
Taking false branch
1565 return Sema::TDK_Success;
1566
1567 // Check the cv-qualifiers on the parameter and argument types.
1568 if (!(TDF & TDF_IgnoreQualifiers)) {
12
Assuming the condition is false
13
Taking false branch
1569 if (TDF & TDF_ParamWithReferenceType) {
1570 if (hasInconsistentOrSupersetQualifiersOf(P, A))
1571 return Sema::TDK_NonDeducedMismatch;
1572 } else if (TDF & TDF_ArgWithReferenceType) {
1573 // C++ [temp.deduct.conv]p4:
1574 // If the original A is a reference type, A can be more cv-qualified
1575 // than the deduced A
1576 if (!A.getQualifiers().compatiblyIncludes(P.getQualifiers()))
1577 return Sema::TDK_NonDeducedMismatch;
1578
1579 // Strip out all extra qualifiers from the argument to figure out the
1580 // type we're converting to, prior to the qualification conversion.
1581 Qualifiers Quals;
1582 A = S.Context.getUnqualifiedArrayType(A, Quals);
1583 A = S.Context.getQualifiedType(A, P.getQualifiers());
1584 } else if (!IsPossiblyOpaquelyQualifiedType(P)) {
1585 if (P.getCVRQualifiers() != A.getCVRQualifiers())
1586 return Sema::TDK_NonDeducedMismatch;
1587 }
1588 }
1589
1590 // If the parameter type is not dependent, there is nothing to deduce.
1591 if (!P->isDependentType()) {
14
Assuming the condition is false
15
Taking false branch
1592 if (TDF & TDF_SkipNonDependent)
1593 return Sema::TDK_Success;
1594 if ((TDF & TDF_IgnoreQualifiers) ? S.Context.hasSameUnqualifiedType(P, A)
1595 : S.Context.hasSameType(P, A))
1596 return Sema::TDK_Success;
1597 if (TDF & TDF_AllowCompatibleFunctionType &&
1598 S.isSameOrCompatibleFunctionType(P, A))
1599 return Sema::TDK_Success;
1600 if (!(TDF & TDF_IgnoreQualifiers))
1601 return Sema::TDK_NonDeducedMismatch;
1602 // Otherwise, when ignoring qualifiers, the types not having the same
1603 // unqualified type does not mean they do not match, so in this case we
1604 // must keep going and analyze with a non-dependent parameter type.
1605 }
1606
1607 switch (P.getCanonicalType()->getTypeClass()) {
16
Control jumps to 'case DependentSizedMatrix:' at line 2063
1608 // Non-canonical types cannot appear here.
1609#define NON_CANONICAL_TYPE(Class, Base) \
1610 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class)::llvm::llvm_unreachable_internal("deducing non-canonical type: "
#Class, "clang/lib/Sema/SemaTemplateDeduction.cpp", 1610)
;
1611#define TYPE(Class, Base)
1612#include "clang/AST/TypeNodes.inc"
1613
1614 case Type::TemplateTypeParm:
1615 case Type::SubstTemplateTypeParmPack:
1616 llvm_unreachable("Type nodes handled above")::llvm::llvm_unreachable_internal("Type nodes handled above",
"clang/lib/Sema/SemaTemplateDeduction.cpp", 1616)
;
1617
1618 case Type::Auto:
1619 // FIXME: Implement deduction in dependent case.
1620 if (P->isDependentType())
1621 return Sema::TDK_Success;
1622 [[fallthrough]];
1623 case Type::Builtin:
1624 case Type::VariableArray:
1625 case Type::Vector:
1626 case Type::FunctionNoProto:
1627 case Type::Record:
1628 case Type::Enum:
1629 case Type::ObjCObject:
1630 case Type::ObjCInterface:
1631 case Type::ObjCObjectPointer:
1632 case Type::BitInt:
1633 return (TDF & TDF_SkipNonDependent) ||
1634 ((TDF & TDF_IgnoreQualifiers)
1635 ? S.Context.hasSameUnqualifiedType(P, A)
1636 : S.Context.hasSameType(P, A))
1637 ? Sema::TDK_Success
1638 : Sema::TDK_NonDeducedMismatch;
1639
1640 // _Complex T [placeholder extension]
1641 case Type::Complex: {
1642 const auto *CP = P->castAs<ComplexType>(), *CA = A->getAs<ComplexType>();
1643 if (!CA)
1644 return Sema::TDK_NonDeducedMismatch;
1645 return DeduceTemplateArgumentsByTypeMatch(
1646 S, TemplateParams, CP->getElementType(), CA->getElementType(), Info,
1647 Deduced, TDF);
1648 }
1649
1650 // _Atomic T [extension]
1651 case Type::Atomic: {
1652 const auto *PA = P->castAs<AtomicType>(), *AA = A->getAs<AtomicType>();
1653 if (!AA)
1654 return Sema::TDK_NonDeducedMismatch;
1655 return DeduceTemplateArgumentsByTypeMatch(
1656 S, TemplateParams, PA->getValueType(), AA->getValueType(), Info,
1657 Deduced, TDF);
1658 }
1659
1660 // T *
1661 case Type::Pointer: {
1662 QualType PointeeType;
1663 if (const auto *PA = A->getAs<PointerType>()) {
1664 PointeeType = PA->getPointeeType();
1665 } else if (const auto *PA = A->getAs<ObjCObjectPointerType>()) {
1666 PointeeType = PA->getPointeeType();
1667 } else {
1668 return Sema::TDK_NonDeducedMismatch;
1669 }
1670 return DeduceTemplateArgumentsByTypeMatch(
1671 S, TemplateParams, P->castAs<PointerType>()->getPointeeType(),
1672 PointeeType, Info, Deduced,
1673 TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass));
1674 }
1675
1676 // T &
1677 case Type::LValueReference: {
1678 const auto *RP = P->castAs<LValueReferenceType>(),
1679 *RA = A->getAs<LValueReferenceType>();
1680 if (!RA)
1681 return Sema::TDK_NonDeducedMismatch;
1682
1683 return DeduceTemplateArgumentsByTypeMatch(
1684 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1685 Deduced, 0);
1686 }
1687
1688 // T && [C++0x]
1689 case Type::RValueReference: {
1690 const auto *RP = P->castAs<RValueReferenceType>(),
1691 *RA = A->getAs<RValueReferenceType>();
1692 if (!RA)
1693 return Sema::TDK_NonDeducedMismatch;
1694
1695 return DeduceTemplateArgumentsByTypeMatch(
1696 S, TemplateParams, RP->getPointeeType(), RA->getPointeeType(), Info,
1697 Deduced, 0);
1698 }
1699
1700 // T [] (implied, but not stated explicitly)
1701 case Type::IncompleteArray: {
1702 const auto *IAA = S.Context.getAsIncompleteArrayType(A);
1703 if (!IAA)
1704 return Sema::TDK_NonDeducedMismatch;
1705
1706 return DeduceTemplateArgumentsByTypeMatch(
1707 S, TemplateParams,
1708 S.Context.getAsIncompleteArrayType(P)->getElementType(),
1709 IAA->getElementType(), Info, Deduced, TDF & TDF_IgnoreQualifiers);
1710 }
1711
1712 // T [integer-constant]
1713 case Type::ConstantArray: {
1714 const auto *CAA = S.Context.getAsConstantArrayType(A),
1715 *CAP = S.Context.getAsConstantArrayType(P);
1716 assert(CAP)(static_cast <bool> (CAP) ? void (0) : __assert_fail ("CAP"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 1716, __extension__
__PRETTY_FUNCTION__))
;
1717 if (!CAA || CAA->getSize() != CAP->getSize())
1718 return Sema::TDK_NonDeducedMismatch;
1719
1720 return DeduceTemplateArgumentsByTypeMatch(
1721 S, TemplateParams, CAP->getElementType(), CAA->getElementType(), Info,
1722 Deduced, TDF & TDF_IgnoreQualifiers);
1723 }
1724
1725 // type [i]
1726 case Type::DependentSizedArray: {
1727 const auto *AA = S.Context.getAsArrayType(A);
1728 if (!AA)
1729 return Sema::TDK_NonDeducedMismatch;
1730
1731 // Check the element type of the arrays
1732 const auto *DAP = S.Context.getAsDependentSizedArrayType(P);
1733 assert(DAP)(static_cast <bool> (DAP) ? void (0) : __assert_fail ("DAP"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 1733, __extension__
__PRETTY_FUNCTION__))
;
1734 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
1735 S, TemplateParams, DAP->getElementType(), AA->getElementType(),
1736 Info, Deduced, TDF & TDF_IgnoreQualifiers))
1737 return Result;
1738
1739 // Determine the array bound is something we can deduce.
1740 const NonTypeTemplateParmDecl *NTTP =
1741 getDeducedParameterFromExpr(Info, DAP->getSizeExpr());
1742 if (!NTTP)
1743 return Sema::TDK_Success;
1744
1745 // We can perform template argument deduction for the given non-type
1746 // template parameter.
1747 assert(NTTP->getDepth() == Info.getDeducedDepth() &&(static_cast <bool> (NTTP->getDepth() == Info.getDeducedDepth
() && "saw non-type template parameter with wrong depth"
) ? void (0) : __assert_fail ("NTTP->getDepth() == Info.getDeducedDepth() && \"saw non-type template parameter with wrong depth\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 1748, __extension__
__PRETTY_FUNCTION__))
1748 "saw non-type template parameter with wrong depth")(static_cast <bool> (NTTP->getDepth() == Info.getDeducedDepth
() && "saw non-type template parameter with wrong depth"
) ? void (0) : __assert_fail ("NTTP->getDepth() == Info.getDeducedDepth() && \"saw non-type template parameter with wrong depth\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 1748, __extension__
__PRETTY_FUNCTION__))
;
1749 if (const auto *CAA = dyn_cast<ConstantArrayType>(AA)) {
1750 llvm::APSInt Size(CAA->getSize());
1751 return DeduceNonTypeTemplateArgument(
1752 S, TemplateParams, NTTP, Size, S.Context.getSizeType(),
1753 /*ArrayBound=*/true, Info, Deduced);
1754 }
1755 if (const auto *DAA = dyn_cast<DependentSizedArrayType>(AA))
1756 if (DAA->getSizeExpr())
1757 return DeduceNonTypeTemplateArgument(
1758 S, TemplateParams, NTTP, DAA->getSizeExpr(), Info, Deduced);
1759
1760 // Incomplete type does not match a dependently-sized array type
1761 return Sema::TDK_NonDeducedMismatch;
1762 }
1763
1764 // type(*)(T)
1765 // T(*)()
1766 // T(*)(T)
1767 case Type::FunctionProto: {
1768 const auto *FPP = P->castAs<FunctionProtoType>(),
1769 *FPA = A->getAs<FunctionProtoType>();
1770 if (!FPA)
1771 return Sema::TDK_NonDeducedMismatch;
1772
1773 if (FPP->getMethodQuals() != FPA->getMethodQuals() ||
1774 FPP->getRefQualifier() != FPA->getRefQualifier() ||
1775 FPP->isVariadic() != FPA->isVariadic())
1776 return Sema::TDK_NonDeducedMismatch;
1777
1778 // Check return types.
1779 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
1780 S, TemplateParams, FPP->getReturnType(), FPA->getReturnType(),
1781 Info, Deduced, 0,
1782 /*PartialOrdering=*/false,
1783 /*DeducedFromArrayBound=*/false))
1784 return Result;
1785
1786 // Check parameter types.
1787 if (auto Result = DeduceTemplateArguments(
1788 S, TemplateParams, FPP->param_type_begin(), FPP->getNumParams(),
1789 FPA->param_type_begin(), FPA->getNumParams(), Info, Deduced,
1790 TDF & TDF_TopLevelParameterTypeList, PartialOrdering))
1791 return Result;
1792
1793 if (TDF & TDF_AllowCompatibleFunctionType)
1794 return Sema::TDK_Success;
1795
1796 // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
1797 // deducing through the noexcept-specifier if it's part of the canonical
1798 // type. libstdc++ relies on this.
1799 Expr *NoexceptExpr = FPP->getNoexceptExpr();
1800 if (const NonTypeTemplateParmDecl *NTTP =
1801 NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr)
1802 : nullptr) {
1803 assert(NTTP->getDepth() == Info.getDeducedDepth() &&(static_cast <bool> (NTTP->getDepth() == Info.getDeducedDepth
() && "saw non-type template parameter with wrong depth"
) ? void (0) : __assert_fail ("NTTP->getDepth() == Info.getDeducedDepth() && \"saw non-type template parameter with wrong depth\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 1804, __extension__
__PRETTY_FUNCTION__))
1804 "saw non-type template parameter with wrong depth")(static_cast <bool> (NTTP->getDepth() == Info.getDeducedDepth
() && "saw non-type template parameter with wrong depth"
) ? void (0) : __assert_fail ("NTTP->getDepth() == Info.getDeducedDepth() && \"saw non-type template parameter with wrong depth\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 1804, __extension__
__PRETTY_FUNCTION__))
;
1805
1806 llvm::APSInt Noexcept(1);
1807 switch (FPA->canThrow()) {
1808 case CT_Cannot:
1809 Noexcept = 1;
1810 [[fallthrough]];
1811
1812 case CT_Can:
1813 // We give E in noexcept(E) the "deduced from array bound" treatment.
1814 // FIXME: Should we?
1815 return DeduceNonTypeTemplateArgument(
1816 S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
1817 /*DeducedFromArrayBound=*/true, Info, Deduced);
1818
1819 case CT_Dependent:
1820 if (Expr *ArgNoexceptExpr = FPA->getNoexceptExpr())
1821 return DeduceNonTypeTemplateArgument(
1822 S, TemplateParams, NTTP, ArgNoexceptExpr, Info, Deduced);
1823 // Can't deduce anything from throw(T...).
1824 break;
1825 }
1826 }
1827 // FIXME: Detect non-deduced exception specification mismatches?
1828 //
1829 // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
1830 // top-level differences in noexcept-specifications.
1831
1832 return Sema::TDK_Success;
1833 }
1834
1835 case Type::InjectedClassName:
1836 // Treat a template's injected-class-name as if the template
1837 // specialization type had been used.
1838
1839 // template-name<T> (where template-name refers to a class template)
1840 // template-name<i>
1841 // TT<T>
1842 // TT<i>
1843 // TT<>
1844 case Type::TemplateSpecialization: {
1845 // When Arg cannot be a derived class, we can just try to deduce template
1846 // arguments from the template-id.
1847 if (!(TDF & TDF_DerivedClass) || !A->isRecordType())
1848 return DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info,
1849 Deduced);
1850
1851 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1852 Deduced.end());
1853
1854 auto Result =
1855 DeduceTemplateSpecArguments(S, TemplateParams, P, A, Info, Deduced);
1856 if (Result == Sema::TDK_Success)
1857 return Result;
1858
1859 // We cannot inspect base classes as part of deduction when the type
1860 // is incomplete, so either instantiate any templates necessary to
1861 // complete the type, or skip over it if it cannot be completed.
1862 if (!S.isCompleteType(Info.getLocation(), A))
1863 return Result;
1864
1865 // Reset the incorrectly deduced argument from above.
1866 Deduced = DeducedOrig;
1867
1868 // Check bases according to C++14 [temp.deduct.call] p4b3:
1869 auto BaseResult = DeduceTemplateBases(S, getCanonicalRD(A),
1870 TemplateParams, P, Info, Deduced);
1871 return BaseResult != Sema::TDK_Invalid ? BaseResult : Result;
1872 }
1873
1874 // T type::*
1875 // T T::*
1876 // T (type::*)()
1877 // type (T::*)()
1878 // type (type::*)(T)
1879 // type (T::*)(T)
1880 // T (type::*)(T)
1881 // T (T::*)()
1882 // T (T::*)(T)
1883 case Type::MemberPointer: {
1884 const auto *MPP = P->castAs<MemberPointerType>(),
1885 *MPA = A->getAs<MemberPointerType>();
1886 if (!MPA)
1887 return Sema::TDK_NonDeducedMismatch;
1888
1889 QualType PPT = MPP->getPointeeType();
1890 if (PPT->isFunctionType())
1891 S.adjustMemberFunctionCC(PPT, /*IsStatic=*/true,
1892 /*IsCtorOrDtor=*/false, Info.getLocation());
1893 QualType APT = MPA->getPointeeType();
1894 if (APT->isFunctionType())
1895 S.adjustMemberFunctionCC(APT, /*IsStatic=*/true,
1896 /*IsCtorOrDtor=*/false, Info.getLocation());
1897
1898 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1899 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
1900 S, TemplateParams, PPT, APT, Info, Deduced, SubTDF))
1901 return Result;
1902 return DeduceTemplateArgumentsByTypeMatch(
1903 S, TemplateParams, QualType(MPP->getClass(), 0),
1904 QualType(MPA->getClass(), 0), Info, Deduced, SubTDF);
1905 }
1906
1907 // (clang extension)
1908 //
1909 // type(^)(T)
1910 // T(^)()
1911 // T(^)(T)
1912 case Type::BlockPointer: {
1913 const auto *BPP = P->castAs<BlockPointerType>(),
1914 *BPA = A->getAs<BlockPointerType>();
1915 if (!BPA)
1916 return Sema::TDK_NonDeducedMismatch;
1917 return DeduceTemplateArgumentsByTypeMatch(
1918 S, TemplateParams, BPP->getPointeeType(), BPA->getPointeeType(), Info,
1919 Deduced, 0);
1920 }
1921
1922 // (clang extension)
1923 //
1924 // T __attribute__(((ext_vector_type(<integral constant>))))
1925 case Type::ExtVector: {
1926 const auto *VP = P->castAs<ExtVectorType>();
1927 QualType ElementType;
1928 if (const auto *VA = A->getAs<ExtVectorType>()) {
1929 // Make sure that the vectors have the same number of elements.
1930 if (VP->getNumElements() != VA->getNumElements())
1931 return Sema::TDK_NonDeducedMismatch;
1932 ElementType = VA->getElementType();
1933 } else if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
1934 // We can't check the number of elements, since the argument has a
1935 // dependent number of elements. This can only occur during partial
1936 // ordering.
1937 ElementType = VA->getElementType();
1938 } else {
1939 return Sema::TDK_NonDeducedMismatch;
1940 }
1941 // Perform deduction on the element types.
1942 return DeduceTemplateArgumentsByTypeMatch(
1943 S, TemplateParams, VP->getElementType(), ElementType, Info, Deduced,
1944 TDF);
1945 }
1946
1947 case Type::DependentVector: {
1948 const auto *VP = P->castAs<DependentVectorType>();
1949
1950 if (const auto *VA = A->getAs<VectorType>()) {
1951 // Perform deduction on the element types.
1952 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
1953 S, TemplateParams, VP->getElementType(), VA->getElementType(),
1954 Info, Deduced, TDF))
1955 return Result;
1956
1957 // Perform deduction on the vector size, if we can.
1958 const NonTypeTemplateParmDecl *NTTP =
1959 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
1960 if (!NTTP)
1961 return Sema::TDK_Success;
1962
1963 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1964 ArgSize = VA->getNumElements();
1965 // Note that we use the "array bound" rules here; just like in that
1966 // case, we don't have any particular type for the vector size, but
1967 // we can provide one if necessary.
1968 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
1969 S.Context.UnsignedIntTy, true,
1970 Info, Deduced);
1971 }
1972
1973 if (const auto *VA = A->getAs<DependentVectorType>()) {
1974 // Perform deduction on the element types.
1975 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
1976 S, TemplateParams, VP->getElementType(), VA->getElementType(),
1977 Info, Deduced, TDF))
1978 return Result;
1979
1980 // Perform deduction on the vector size, if we can.
1981 const NonTypeTemplateParmDecl *NTTP =
1982 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
1983 if (!NTTP)
1984 return Sema::TDK_Success;
1985
1986 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1987 VA->getSizeExpr(), Info, Deduced);
1988 }
1989
1990 return Sema::TDK_NonDeducedMismatch;
1991 }
1992
1993 // (clang extension)
1994 //
1995 // T __attribute__(((ext_vector_type(N))))
1996 case Type::DependentSizedExtVector: {
1997 const auto *VP = P->castAs<DependentSizedExtVectorType>();
1998
1999 if (const auto *VA = A->getAs<ExtVectorType>()) {
2000 // Perform deduction on the element types.
2001 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2002 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2003 Info, Deduced, TDF))
2004 return Result;
2005
2006 // Perform deduction on the vector size, if we can.
2007 const NonTypeTemplateParmDecl *NTTP =
2008 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2009 if (!NTTP)
2010 return Sema::TDK_Success;
2011
2012 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2013 ArgSize = VA->getNumElements();
2014 // Note that we use the "array bound" rules here; just like in that
2015 // case, we don't have any particular type for the vector size, but
2016 // we can provide one if necessary.
2017 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
2018 S.Context.IntTy, true, Info,
2019 Deduced);
2020 }
2021
2022 if (const auto *VA = A->getAs<DependentSizedExtVectorType>()) {
2023 // Perform deduction on the element types.
2024 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2025 S, TemplateParams, VP->getElementType(), VA->getElementType(),
2026 Info, Deduced, TDF))
2027 return Result;
2028
2029 // Perform deduction on the vector size, if we can.
2030 const NonTypeTemplateParmDecl *NTTP =
2031 getDeducedParameterFromExpr(Info, VP->getSizeExpr());
2032 if (!NTTP)
2033 return Sema::TDK_Success;
2034
2035 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2036 VA->getSizeExpr(), Info, Deduced);
2037 }
2038
2039 return Sema::TDK_NonDeducedMismatch;
2040 }
2041
2042 // (clang extension)
2043 //
2044 // T __attribute__((matrix_type(<integral constant>,
2045 // <integral constant>)))
2046 case Type::ConstantMatrix: {
2047 const auto *MP = P->castAs<ConstantMatrixType>(),
2048 *MA = A->getAs<ConstantMatrixType>();
2049 if (!MA)
2050 return Sema::TDK_NonDeducedMismatch;
2051
2052 // Check that the dimensions are the same
2053 if (MP->getNumRows() != MA->getNumRows() ||
2054 MP->getNumColumns() != MA->getNumColumns()) {
2055 return Sema::TDK_NonDeducedMismatch;
2056 }
2057 // Perform deduction on element types.
2058 return DeduceTemplateArgumentsByTypeMatch(
2059 S, TemplateParams, MP->getElementType(), MA->getElementType(), Info,
2060 Deduced, TDF);
2061 }
2062
2063 case Type::DependentSizedMatrix: {
2064 const auto *MP = P->castAs<DependentSizedMatrixType>();
17
The object is a 'const class clang::DependentSizedMatrixType *'
2065 const auto *MA = A->getAs<MatrixType>();
18
Assuming the object is a 'const class clang::MatrixType *'
2066 if (!MA)
19
Assuming 'MA' is non-null
20
Taking false branch
2067 return Sema::TDK_NonDeducedMismatch;
2068
2069 // Check the element type of the matrixes.
2070 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
21
Assuming 'Result' is 0
22
Taking false branch
2071 S, TemplateParams, MP->getElementType(), MA->getElementType(),
2072 Info, Deduced, TDF))
2073 return Result;
2074
2075 // Try to deduce a matrix dimension.
2076 auto DeduceMatrixArg =
2077 [&S, &Info, &Deduced, &TemplateParams](
2078 Expr *ParamExpr, const MatrixType *A,
2079 unsigned (ConstantMatrixType::*GetArgDimension)() const,
2080 Expr *(DependentSizedMatrixType::*GetArgDimensionExpr)() const) {
2081 const auto *ACM = dyn_cast<ConstantMatrixType>(A);
24
Assuming 'A' is not a 'CastReturnType'
2082 const auto *ADM = dyn_cast<DependentSizedMatrixType>(A);
25
Assuming 'A' is not a 'CastReturnType'
26
'ADM' initialized to a null pointer value
2083 if (!ParamExpr->isValueDependent()) {
27
Assuming the condition is false
28
Taking false branch
2084 std::optional<llvm::APSInt> ParamConst =
2085 ParamExpr->getIntegerConstantExpr(S.Context);
2086 if (!ParamConst)
2087 return Sema::TDK_NonDeducedMismatch;
2088
2089 if (ACM) {
2090 if ((ACM->*GetArgDimension)() == *ParamConst)
2091 return Sema::TDK_Success;
2092 return Sema::TDK_NonDeducedMismatch;
2093 }
2094
2095 Expr *ArgExpr = (ADM->*GetArgDimensionExpr)();
2096 if (std::optional<llvm::APSInt> ArgConst =
2097 ArgExpr->getIntegerConstantExpr(S.Context))
2098 if (*ArgConst == *ParamConst)
2099 return Sema::TDK_Success;
2100 return Sema::TDK_NonDeducedMismatch;
2101 }
2102
2103 const NonTypeTemplateParmDecl *NTTP =
2104 getDeducedParameterFromExpr(Info, ParamExpr);
2105 if (!NTTP)
29
Assuming 'NTTP' is non-null
30
Taking false branch
2106 return Sema::TDK_Success;
2107
2108 if (ACM
30.1
'ACM' is null
) {
31
Taking false branch
2109 llvm::APSInt ArgConst(
2110 S.Context.getTypeSize(S.Context.getSizeType()));
2111 ArgConst = (ACM->*GetArgDimension)();
2112 return DeduceNonTypeTemplateArgument(
2113 S, TemplateParams, NTTP, ArgConst, S.Context.getSizeType(),
2114 /*ArrayBound=*/true, Info, Deduced);
2115 }
2116
2117 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2118 (ADM->*GetArgDimensionExpr)(),
32
Called C++ object pointer is null
2119 Info, Deduced);
2120 };
2121
2122 if (auto Result = DeduceMatrixArg(MP->getRowExpr(), MA,
23
Calling 'operator()'
2123 &ConstantMatrixType::getNumRows,
2124 &DependentSizedMatrixType::getRowExpr))
2125 return Result;
2126
2127 return DeduceMatrixArg(MP->getColumnExpr(), MA,
2128 &ConstantMatrixType::getNumColumns,
2129 &DependentSizedMatrixType::getColumnExpr);
2130 }
2131
2132 // (clang extension)
2133 //
2134 // T __attribute__(((address_space(N))))
2135 case Type::DependentAddressSpace: {
2136 const auto *ASP = P->castAs<DependentAddressSpaceType>();
2137
2138 if (const auto *ASA = A->getAs<DependentAddressSpaceType>()) {
2139 // Perform deduction on the pointer type.
2140 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2141 S, TemplateParams, ASP->getPointeeType(), ASA->getPointeeType(),
2142 Info, Deduced, TDF))
2143 return Result;
2144
2145 // Perform deduction on the address space, if we can.
2146 const NonTypeTemplateParmDecl *NTTP =
2147 getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2148 if (!NTTP)
2149 return Sema::TDK_Success;
2150
2151 return DeduceNonTypeTemplateArgument(
2152 S, TemplateParams, NTTP, ASA->getAddrSpaceExpr(), Info, Deduced);
2153 }
2154
2155 if (isTargetAddressSpace(A.getAddressSpace())) {
2156 llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
2157 false);
2158 ArgAddressSpace = toTargetAddressSpace(A.getAddressSpace());
2159
2160 // Perform deduction on the pointer types.
2161 if (auto Result = DeduceTemplateArgumentsByTypeMatch(
2162 S, TemplateParams, ASP->getPointeeType(),
2163 S.Context.removeAddrSpaceQualType(A), Info, Deduced, TDF))
2164 return Result;
2165
2166 // Perform deduction on the address space, if we can.
2167 const NonTypeTemplateParmDecl *NTTP =
2168 getDeducedParameterFromExpr(Info, ASP->getAddrSpaceExpr());
2169 if (!NTTP)
2170 return Sema::TDK_Success;
2171
2172 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2173 ArgAddressSpace, S.Context.IntTy,
2174 true, Info, Deduced);
2175 }
2176
2177 return Sema::TDK_NonDeducedMismatch;
2178 }
2179 case Type::DependentBitInt: {
2180 const auto *IP = P->castAs<DependentBitIntType>();
2181
2182 if (const auto *IA = A->getAs<BitIntType>()) {
2183 if (IP->isUnsigned() != IA->isUnsigned())
2184 return Sema::TDK_NonDeducedMismatch;
2185
2186 const NonTypeTemplateParmDecl *NTTP =
2187 getDeducedParameterFromExpr(Info, IP->getNumBitsExpr());
2188 if (!NTTP)
2189 return Sema::TDK_Success;
2190
2191 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
2192 ArgSize = IA->getNumBits();
2193
2194 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
2195 S.Context.IntTy, true, Info,
2196 Deduced);
2197 }
2198
2199 if (const auto *IA = A->getAs<DependentBitIntType>()) {
2200 if (IP->isUnsigned() != IA->isUnsigned())
2201 return Sema::TDK_NonDeducedMismatch;
2202 return Sema::TDK_Success;
2203 }
2204
2205 return Sema::TDK_NonDeducedMismatch;
2206 }
2207
2208 case Type::TypeOfExpr:
2209 case Type::TypeOf:
2210 case Type::DependentName:
2211 case Type::UnresolvedUsing:
2212 case Type::Decltype:
2213 case Type::UnaryTransform:
2214 case Type::DeducedTemplateSpecialization:
2215 case Type::DependentTemplateSpecialization:
2216 case Type::PackExpansion:
2217 case Type::Pipe:
2218 // No template argument deduction for these types
2219 return Sema::TDK_Success;
2220 }
2221
2222 llvm_unreachable("Invalid Type Class!")::llvm::llvm_unreachable_internal("Invalid Type Class!", "clang/lib/Sema/SemaTemplateDeduction.cpp"
, 2222)
;
2223}
2224
2225static Sema::TemplateDeductionResult
2226DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
2227 const TemplateArgument &P, TemplateArgument A,
2228 TemplateDeductionInfo &Info,
2229 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
2230 // If the template argument is a pack expansion, perform template argument
2231 // deduction against the pattern of that expansion. This only occurs during
2232 // partial ordering.
2233 if (A.isPackExpansion())
2234 A = A.getPackExpansionPattern();
2235
2236 switch (P.getKind()) {
2237 case TemplateArgument::Null:
2238 llvm_unreachable("Null template argument in parameter list")::llvm::llvm_unreachable_internal("Null template argument in parameter list"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 2238)
;
2239
2240 case TemplateArgument::Type:
2241 if (A.getKind() == TemplateArgument::Type)
2242 return DeduceTemplateArgumentsByTypeMatch(
2243 S, TemplateParams, P.getAsType(), A.getAsType(), Info, Deduced, 0);
2244 Info.FirstArg = P;
2245 Info.SecondArg = A;
2246 return Sema::TDK_NonDeducedMismatch;
2247
2248 case TemplateArgument::Template:
2249 if (A.getKind() == TemplateArgument::Template)
2250 return DeduceTemplateArguments(S, TemplateParams, P.getAsTemplate(),
2251 A.getAsTemplate(), Info, Deduced);
2252 Info.FirstArg = P;
2253 Info.SecondArg = A;
2254 return Sema::TDK_NonDeducedMismatch;
2255
2256 case TemplateArgument::TemplateExpansion:
2257 llvm_unreachable("caller should handle pack expansions")::llvm::llvm_unreachable_internal("caller should handle pack expansions"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 2257)
;
2258
2259 case TemplateArgument::Declaration:
2260 if (A.getKind() == TemplateArgument::Declaration &&
2261 isSameDeclaration(P.getAsDecl(), A.getAsDecl()))
2262 return Sema::TDK_Success;
2263
2264 Info.FirstArg = P;
2265 Info.SecondArg = A;
2266 return Sema::TDK_NonDeducedMismatch;
2267
2268 case TemplateArgument::NullPtr:
2269 if (A.getKind() == TemplateArgument::NullPtr &&
2270 S.Context.hasSameType(P.getNullPtrType(), A.getNullPtrType()))
2271 return Sema::TDK_Success;
2272
2273 Info.FirstArg = P;
2274 Info.SecondArg = A;
2275 return Sema::TDK_NonDeducedMismatch;
2276
2277 case TemplateArgument::Integral:
2278 if (A.getKind() == TemplateArgument::Integral) {
2279 if (hasSameExtendedValue(P.getAsIntegral(), A.getAsIntegral()))
2280 return Sema::TDK_Success;
2281 }
2282 Info.FirstArg = P;
2283 Info.SecondArg = A;
2284 return Sema::TDK_NonDeducedMismatch;
2285
2286 case TemplateArgument::Expression:
2287 if (const NonTypeTemplateParmDecl *NTTP =
2288 getDeducedParameterFromExpr(Info, P.getAsExpr())) {
2289 if (A.getKind() == TemplateArgument::Integral)
2290 return DeduceNonTypeTemplateArgument(
2291 S, TemplateParams, NTTP, A.getAsIntegral(), A.getIntegralType(),
2292 /*ArrayBound=*/false, Info, Deduced);
2293 if (A.getKind() == TemplateArgument::NullPtr)
2294 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
2295 A.getNullPtrType(), Info, Deduced);
2296 if (A.getKind() == TemplateArgument::Expression)
2297 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
2298 A.getAsExpr(), Info, Deduced);
2299 if (A.getKind() == TemplateArgument::Declaration)
2300 return DeduceNonTypeTemplateArgument(
2301 S, TemplateParams, NTTP, A.getAsDecl(), A.getParamTypeForDecl(),
2302 Info, Deduced);
2303
2304 Info.FirstArg = P;
2305 Info.SecondArg = A;
2306 return Sema::TDK_NonDeducedMismatch;
2307 }
2308
2309 // Can't deduce anything, but that's okay.
2310 return Sema::TDK_Success;
2311 case TemplateArgument::Pack:
2312 llvm_unreachable("Argument packs should be expanded by the caller!")::llvm::llvm_unreachable_internal("Argument packs should be expanded by the caller!"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 2312)
;
2313 }
2314
2315 llvm_unreachable("Invalid TemplateArgument Kind!")::llvm::llvm_unreachable_internal("Invalid TemplateArgument Kind!"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 2315)
;
2316}
2317
2318/// Determine whether there is a template argument to be used for
2319/// deduction.
2320///
2321/// This routine "expands" argument packs in-place, overriding its input
2322/// parameters so that \c Args[ArgIdx] will be the available template argument.
2323///
2324/// \returns true if there is another template argument (which will be at
2325/// \c Args[ArgIdx]), false otherwise.
2326static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
2327 unsigned &ArgIdx) {
2328 if (ArgIdx == Args.size())
2329 return false;
2330
2331 const TemplateArgument &Arg = Args[ArgIdx];
2332 if (Arg.getKind() != TemplateArgument::Pack)
2333 return true;
2334
2335 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?")(static_cast <bool> (ArgIdx == Args.size() - 1 &&
"Pack not at the end of argument list?") ? void (0) : __assert_fail
("ArgIdx == Args.size() - 1 && \"Pack not at the end of argument list?\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 2335, __extension__
__PRETTY_FUNCTION__))
;
2336 Args = Arg.pack_elements();
2337 ArgIdx = 0;
2338 return ArgIdx < Args.size();
2339}
2340
2341/// Determine whether the given set of template arguments has a pack
2342/// expansion that is not the last template argument.
2343static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
2344 bool FoundPackExpansion = false;
2345 for (const auto &A : Args) {
2346 if (FoundPackExpansion)
2347 return true;
2348
2349 if (A.getKind() == TemplateArgument::Pack)
2350 return hasPackExpansionBeforeEnd(A.pack_elements());
2351
2352 // FIXME: If this is a fixed-arity pack expansion from an outer level of
2353 // templates, it should not be treated as a pack expansion.
2354 if (A.isPackExpansion())
2355 FoundPackExpansion = true;
2356 }
2357
2358 return false;
2359}
2360
2361static Sema::TemplateDeductionResult
2362DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
2363 ArrayRef<TemplateArgument> Ps,
2364 ArrayRef<TemplateArgument> As,
2365 TemplateDeductionInfo &Info,
2366 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2367 bool NumberOfArgumentsMustMatch) {
2368 // C++0x [temp.deduct.type]p9:
2369 // If the template argument list of P contains a pack expansion that is not
2370 // the last template argument, the entire template argument list is a
2371 // non-deduced context.
2372 if (hasPackExpansionBeforeEnd(Ps))
2373 return Sema::TDK_Success;
2374
2375 // C++0x [temp.deduct.type]p9:
2376 // If P has a form that contains <T> or <i>, then each argument Pi of the
2377 // respective template argument list P is compared with the corresponding
2378 // argument Ai of the corresponding template argument list of A.
2379 unsigned ArgIdx = 0, ParamIdx = 0;
2380 for (; hasTemplateArgumentForDeduction(Ps, ParamIdx); ++ParamIdx) {
2381 const TemplateArgument &P = Ps[ParamIdx];
2382 if (!P.isPackExpansion()) {
2383 // The simple case: deduce template arguments by matching Pi and Ai.
2384
2385 // Check whether we have enough arguments.
2386 if (!hasTemplateArgumentForDeduction(As, ArgIdx))
2387 return NumberOfArgumentsMustMatch
2388 ? Sema::TDK_MiscellaneousDeductionFailure
2389 : Sema::TDK_Success;
2390
2391 // C++1z [temp.deduct.type]p9:
2392 // During partial ordering, if Ai was originally a pack expansion [and]
2393 // Pi is not a pack expansion, template argument deduction fails.
2394 if (As[ArgIdx].isPackExpansion())
2395 return Sema::TDK_MiscellaneousDeductionFailure;
2396
2397 // Perform deduction for this Pi/Ai pair.
2398 if (auto Result = DeduceTemplateArguments(S, TemplateParams, P,
2399 As[ArgIdx], Info, Deduced))
2400 return Result;
2401
2402 // Move to the next argument.
2403 ++ArgIdx;
2404 continue;
2405 }
2406
2407 // The parameter is a pack expansion.
2408
2409 // C++0x [temp.deduct.type]p9:
2410 // If Pi is a pack expansion, then the pattern of Pi is compared with
2411 // each remaining argument in the template argument list of A. Each
2412 // comparison deduces template arguments for subsequent positions in the
2413 // template parameter packs expanded by Pi.
2414 TemplateArgument Pattern = P.getPackExpansionPattern();
2415
2416 // Prepare to deduce the packs within the pattern.
2417 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
2418
2419 // Keep track of the deduced template arguments for each parameter pack
2420 // expanded by this pack expansion (the outer index) and for each
2421 // template argument (the inner SmallVectors).
2422 for (; hasTemplateArgumentForDeduction(As, ArgIdx) &&
2423 PackScope.hasNextElement();
2424 ++ArgIdx) {
2425 // Deduce template arguments from the pattern.
2426 if (auto Result = DeduceTemplateArguments(S, TemplateParams, Pattern,
2427 As[ArgIdx], Info, Deduced))
2428 return Result;
2429
2430 PackScope.nextPackElement();
2431 }
2432
2433 // Build argument packs for each of the parameter packs expanded by this
2434 // pack expansion.
2435 if (auto Result = PackScope.finish())
2436 return Result;
2437 }
2438
2439 return Sema::TDK_Success;
2440}
2441
2442static Sema::TemplateDeductionResult
2443DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
2444 const TemplateArgumentList &ParamList,
2445 const TemplateArgumentList &ArgList,
2446 TemplateDeductionInfo &Info,
2447 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
2448 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
2449 ArgList.asArray(), Info, Deduced,
2450 /*NumberOfArgumentsMustMatch=*/false);
2451}
2452
2453/// Determine whether two template arguments are the same.
2454static bool isSameTemplateArg(ASTContext &Context,
2455 TemplateArgument X,
2456 const TemplateArgument &Y,
2457 bool PartialOrdering,
2458 bool PackExpansionMatchesPack = false) {
2459 // If we're checking deduced arguments (X) against original arguments (Y),
2460 // we will have flattened packs to non-expansions in X.
2461 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
2462 X = X.getPackExpansionPattern();
2463
2464 if (X.getKind() != Y.getKind())
2465 return false;
2466
2467 switch (X.getKind()) {
2468 case TemplateArgument::Null:
2469 llvm_unreachable("Comparing NULL template argument")::llvm::llvm_unreachable_internal("Comparing NULL template argument"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 2469)
;
2470
2471 case TemplateArgument::Type:
2472 return Context.getCanonicalType(X.getAsType()) ==
2473 Context.getCanonicalType(Y.getAsType());
2474
2475 case TemplateArgument::Declaration:
2476 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
2477
2478 case TemplateArgument::NullPtr:
2479 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
2480
2481 case TemplateArgument::Template:
2482 case TemplateArgument::TemplateExpansion:
2483 return Context.getCanonicalTemplateName(
2484 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2485 Context.getCanonicalTemplateName(
2486 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
2487
2488 case TemplateArgument::Integral:
2489 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
2490
2491 case TemplateArgument::Expression: {
2492 llvm::FoldingSetNodeID XID, YID;
2493 X.getAsExpr()->Profile(XID, Context, true);
2494 Y.getAsExpr()->Profile(YID, Context, true);
2495 return XID == YID;
2496 }
2497
2498 case TemplateArgument::Pack: {
2499 unsigned PackIterationSize = X.pack_size();
2500 if (X.pack_size() != Y.pack_size()) {
2501 if (!PartialOrdering)
2502 return false;
2503
2504 // C++0x [temp.deduct.type]p9:
2505 // During partial ordering, if Ai was originally a pack expansion:
2506 // - if P does not contain a template argument corresponding to Ai
2507 // then Ai is ignored;
2508 bool XHasMoreArg = X.pack_size() > Y.pack_size();
2509 if (!(XHasMoreArg && X.pack_elements().back().isPackExpansion()) &&
2510 !(!XHasMoreArg && Y.pack_elements().back().isPackExpansion()))
2511 return false;
2512
2513 if (XHasMoreArg)
2514 PackIterationSize = Y.pack_size();
2515 }
2516
2517 ArrayRef<TemplateArgument> XP = X.pack_elements();
2518 ArrayRef<TemplateArgument> YP = Y.pack_elements();
2519 for (unsigned i = 0; i < PackIterationSize; ++i)
2520 if (!isSameTemplateArg(Context, XP[i], YP[i], PartialOrdering,
2521 PackExpansionMatchesPack))
2522 return false;
2523 return true;
2524 }
2525 }
2526
2527 llvm_unreachable("Invalid TemplateArgument Kind!")::llvm::llvm_unreachable_internal("Invalid TemplateArgument Kind!"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 2527)
;
2528}
2529
2530/// Allocate a TemplateArgumentLoc where all locations have
2531/// been initialized to the given location.
2532///
2533/// \param Arg The template argument we are producing template argument
2534/// location information for.
2535///
2536/// \param NTTPType For a declaration template argument, the type of
2537/// the non-type template parameter that corresponds to this template
2538/// argument. Can be null if no type sugar is available to add to the
2539/// type from the template argument.
2540///
2541/// \param Loc The source location to use for the resulting template
2542/// argument.
2543TemplateArgumentLoc
2544Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2545 QualType NTTPType, SourceLocation Loc) {
2546 switch (Arg.getKind()) {
2547 case TemplateArgument::Null:
2548 llvm_unreachable("Can't get a NULL template argument here")::llvm::llvm_unreachable_internal("Can't get a NULL template argument here"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 2548)
;
2549
2550 case TemplateArgument::Type:
2551 return TemplateArgumentLoc(
2552 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
2553
2554 case TemplateArgument::Declaration: {
2555 if (NTTPType.isNull())
2556 NTTPType = Arg.getParamTypeForDecl();
2557 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2558 .getAs<Expr>();
2559 return TemplateArgumentLoc(TemplateArgument(E), E);
2560 }
2561
2562 case TemplateArgument::NullPtr: {
2563 if (NTTPType.isNull())
2564 NTTPType = Arg.getNullPtrType();
2565 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2566 .getAs<Expr>();
2567 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2568 E);
2569 }
2570
2571 case TemplateArgument::Integral: {
2572 Expr *E =
2573 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
2574 return TemplateArgumentLoc(TemplateArgument(E), E);
2575 }
2576
2577 case TemplateArgument::Template:
2578 case TemplateArgument::TemplateExpansion: {
2579 NestedNameSpecifierLocBuilder Builder;
2580 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
2581 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
2582 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
2583 else if (QualifiedTemplateName *QTN =
2584 Template.getAsQualifiedTemplateName())
2585 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
2586
2587 if (Arg.getKind() == TemplateArgument::Template)
2588 return TemplateArgumentLoc(Context, Arg,
2589 Builder.getWithLocInContext(Context), Loc);
2590
2591 return TemplateArgumentLoc(
2592 Context, Arg, Builder.getWithLocInContext(Context), Loc, Loc);
2593 }
2594
2595 case TemplateArgument::Expression:
2596 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2597
2598 case TemplateArgument::Pack:
2599 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2600 }
2601
2602 llvm_unreachable("Invalid TemplateArgument Kind!")::llvm::llvm_unreachable_internal("Invalid TemplateArgument Kind!"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 2602)
;
2603}
2604
2605TemplateArgumentLoc
2606Sema::getIdentityTemplateArgumentLoc(NamedDecl *TemplateParm,
2607 SourceLocation Location) {
2608 return getTrivialTemplateArgumentLoc(
2609 Context.getInjectedTemplateArg(TemplateParm), QualType(), Location);
2610}
2611
2612/// Convert the given deduced template argument and add it to the set of
2613/// fully-converted template arguments.
2614static bool ConvertDeducedTemplateArgument(
2615 Sema &S, NamedDecl *Param, DeducedTemplateArgument Arg, NamedDecl *Template,
2616 TemplateDeductionInfo &Info, bool IsDeduced,
2617 SmallVectorImpl<TemplateArgument> &SugaredOutput,
2618 SmallVectorImpl<TemplateArgument> &CanonicalOutput) {
2619 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2620 unsigned ArgumentPackIndex) {
2621 // Convert the deduced template argument into a template
2622 // argument that we can check, almost as if the user had written
2623 // the template argument explicitly.
2624 TemplateArgumentLoc ArgLoc =
2625 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
2626
2627 // Check the template argument, converting it as necessary.
2628 return S.CheckTemplateArgument(
2629 Param, ArgLoc, Template, Template->getLocation(),
2630 Template->getSourceRange().getEnd(), ArgumentPackIndex, SugaredOutput,
2631 CanonicalOutput,
2632 IsDeduced
2633 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2634 : Sema::CTAK_Deduced)
2635 : Sema::CTAK_Specified);
2636 };
2637
2638 if (Arg.getKind() == TemplateArgument::Pack) {
2639 // This is a template argument pack, so check each of its arguments against
2640 // the template parameter.
2641 SmallVector<TemplateArgument, 2> SugaredPackedArgsBuilder,
2642 CanonicalPackedArgsBuilder;
2643 for (const auto &P : Arg.pack_elements()) {
2644 // When converting the deduced template argument, append it to the
2645 // general output list. We need to do this so that the template argument
2646 // checking logic has all of the prior template arguments available.
2647 DeducedTemplateArgument InnerArg(P);
2648 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
2649 assert(InnerArg.getKind() != TemplateArgument::Pack &&(static_cast <bool> (InnerArg.getKind() != TemplateArgument
::Pack && "deduced nested pack") ? void (0) : __assert_fail
("InnerArg.getKind() != TemplateArgument::Pack && \"deduced nested pack\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 2650, __extension__
__PRETTY_FUNCTION__))
2650 "deduced nested pack")(static_cast <bool> (InnerArg.getKind() != TemplateArgument
::Pack && "deduced nested pack") ? void (0) : __assert_fail
("InnerArg.getKind() != TemplateArgument::Pack && \"deduced nested pack\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 2650, __extension__
__PRETTY_FUNCTION__))
;
2651 if (P.isNull()) {
2652 // We deduced arguments for some elements of this pack, but not for
2653 // all of them. This happens if we get a conditionally-non-deduced
2654 // context in a pack expansion (such as an overload set in one of the
2655 // arguments).
2656 S.Diag(Param->getLocation(),
2657 diag::err_template_arg_deduced_incomplete_pack)
2658 << Arg << Param;
2659 return true;
2660 }
2661 if (ConvertArg(InnerArg, SugaredPackedArgsBuilder.size()))
2662 return true;
2663
2664 // Move the converted template argument into our argument pack.
2665 SugaredPackedArgsBuilder.push_back(SugaredOutput.pop_back_val());
2666 CanonicalPackedArgsBuilder.push_back(CanonicalOutput.pop_back_val());
2667 }
2668
2669 // If the pack is empty, we still need to substitute into the parameter
2670 // itself, in case that substitution fails.
2671 if (SugaredPackedArgsBuilder.empty()) {
2672 LocalInstantiationScope Scope(S);
2673 MultiLevelTemplateArgumentList Args(Template, SugaredOutput,
2674 /*Final=*/true);
2675
2676 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2677 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2678 NTTP, SugaredOutput,
2679 Template->getSourceRange());
2680 if (Inst.isInvalid() ||
2681 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2682 NTTP->getDeclName()).isNull())
2683 return true;
2684 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2685 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2686 TTP, SugaredOutput,
2687 Template->getSourceRange());
2688 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2689 return true;
2690 }
2691 // For type parameters, no substitution is ever required.
2692 }
2693
2694 // Create the resulting argument pack.
2695 SugaredOutput.push_back(
2696 TemplateArgument::CreatePackCopy(S.Context, SugaredPackedArgsBuilder));
2697 CanonicalOutput.push_back(TemplateArgument::CreatePackCopy(
2698 S.Context, CanonicalPackedArgsBuilder));
2699 return false;
2700 }
2701
2702 return ConvertArg(Arg, 0);
2703}
2704
2705// FIXME: This should not be a template, but
2706// ClassTemplatePartialSpecializationDecl sadly does not derive from
2707// TemplateDecl.
2708template <typename TemplateDeclT>
2709static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
2710 Sema &S, TemplateDeclT *Template, bool IsDeduced,
2711 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2712 TemplateDeductionInfo &Info,
2713 SmallVectorImpl<TemplateArgument> &SugaredBuilder,
2714 SmallVectorImpl<TemplateArgument> &CanonicalBuilder,
2715 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
2716 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2717 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2718
2719 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2720 NamedDecl *Param = TemplateParams->getParam(I);
2721
2722 // C++0x [temp.arg.explicit]p3:
2723 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2724 // be deduced to an empty sequence of template arguments.
2725 // FIXME: Where did the word "trailing" come from?
2726 if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
2727 if (auto Result =
2728 PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish())
2729 return Result;
2730 }
2731
2732 if (!Deduced[I].isNull()) {
2733 if (I < NumAlreadyConverted) {
2734 // We may have had explicitly-specified template arguments for a
2735 // template parameter pack (that may or may not have been extended
2736 // via additional deduced arguments).
2737 if (Param->isParameterPack() && CurrentInstantiationScope &&
2738 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2739 // Forget the partially-substituted pack; its substitution is now
2740 // complete.
2741 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2742 // We still need to check the argument in case it was extended by
2743 // deduction.
2744 } else {
2745 // We have already fully type-checked and converted this
2746 // argument, because it was explicitly-specified. Just record the
2747 // presence of this argument.
2748 SugaredBuilder.push_back(Deduced[I]);
2749 CanonicalBuilder.push_back(
2750 S.Context.getCanonicalTemplateArgument(Deduced[I]));
2751 continue;
2752 }
2753 }
2754
2755 // We may have deduced this argument, so it still needs to be
2756 // checked and converted.
2757 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
2758 IsDeduced, SugaredBuilder,
2759 CanonicalBuilder)) {
2760 Info.Param = makeTemplateParameter(Param);
2761 // FIXME: These template arguments are temporary. Free them!
2762 Info.reset(
2763 TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
2764 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
2765 return Sema::TDK_SubstitutionFailure;
2766 }
2767
2768 continue;
2769 }
2770
2771 // Substitute into the default template argument, if available.
2772 bool HasDefaultArg = false;
2773 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2774 if (!TD) {
2775 assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||(static_cast <bool> (isa<ClassTemplatePartialSpecializationDecl
>(Template) || isa<VarTemplatePartialSpecializationDecl
>(Template)) ? void (0) : __assert_fail ("isa<ClassTemplatePartialSpecializationDecl>(Template) || isa<VarTemplatePartialSpecializationDecl>(Template)"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 2776, __extension__
__PRETTY_FUNCTION__))
2776 isa<VarTemplatePartialSpecializationDecl>(Template))(static_cast <bool> (isa<ClassTemplatePartialSpecializationDecl
>(Template) || isa<VarTemplatePartialSpecializationDecl
>(Template)) ? void (0) : __assert_fail ("isa<ClassTemplatePartialSpecializationDecl>(Template) || isa<VarTemplatePartialSpecializationDecl>(Template)"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 2776, __extension__
__PRETTY_FUNCTION__))
;
2777 return Sema::TDK_Incomplete;
2778 }
2779
2780 TemplateArgumentLoc DefArg;
2781 {
2782 Qualifiers ThisTypeQuals;
2783 CXXRecordDecl *ThisContext = nullptr;
2784 if (auto *Rec = dyn_cast<CXXRecordDecl>(TD->getDeclContext()))
2785 if (Rec->isLambda())
2786 if (auto *Method = dyn_cast<CXXMethodDecl>(Rec->getDeclContext())) {
2787 ThisContext = Method->getParent();
2788 ThisTypeQuals = Method->getMethodQualifiers();
2789 }
2790
2791 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, ThisTypeQuals,
2792 S.getLangOpts().CPlusPlus17);
2793
2794 DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2795 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param,
2796 SugaredBuilder, CanonicalBuilder, HasDefaultArg);
2797 }
2798
2799 // If there was no default argument, deduction is incomplete.
2800 if (DefArg.getArgument().isNull()) {
2801 Info.Param = makeTemplateParameter(
2802 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2803 Info.reset(TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
2804 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
2805 if (PartialOverloading) break;
2806
2807 return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2808 : Sema::TDK_Incomplete;
2809 }
2810
2811 // Check whether we can actually use the default argument.
2812 if (S.CheckTemplateArgument(
2813 Param, DefArg, TD, TD->getLocation(), TD->getSourceRange().getEnd(),
2814 0, SugaredBuilder, CanonicalBuilder, Sema::CTAK_Specified)) {
2815 Info.Param = makeTemplateParameter(
2816 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2817 // FIXME: These template arguments are temporary. Free them!
2818 Info.reset(TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder),
2819 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder));
2820 return Sema::TDK_SubstitutionFailure;
2821 }
2822
2823 // If we get here, we successfully used the default template argument.
2824 }
2825
2826 return Sema::TDK_Success;
2827}
2828
2829static DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
2830 if (auto *DC = dyn_cast<DeclContext>(D))
2831 return DC;
2832 return D->getDeclContext();
2833}
2834
2835template<typename T> struct IsPartialSpecialization {
2836 static constexpr bool value = false;
2837};
2838template<>
2839struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
2840 static constexpr bool value = true;
2841};
2842template<>
2843struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
2844 static constexpr bool value = true;
2845};
2846template <typename TemplateDeclT>
2847static bool DeducedArgsNeedReplacement(TemplateDeclT *Template) {
2848 return false;
2849}
2850template <>
2851bool DeducedArgsNeedReplacement<VarTemplatePartialSpecializationDecl>(
2852 VarTemplatePartialSpecializationDecl *Spec) {
2853 return !Spec->isClassScopeExplicitSpecialization();
2854}
2855template <>
2856bool DeducedArgsNeedReplacement<ClassTemplatePartialSpecializationDecl>(
2857 ClassTemplatePartialSpecializationDecl *Spec) {
2858 return !Spec->isClassScopeExplicitSpecialization();
2859}
2860
2861template <typename TemplateDeclT>
2862static Sema::TemplateDeductionResult
2863CheckDeducedArgumentConstraints(Sema &S, TemplateDeclT *Template,
2864 ArrayRef<TemplateArgument> SugaredDeducedArgs,
2865 ArrayRef<TemplateArgument> CanonicalDeducedArgs,
2866 TemplateDeductionInfo &Info) {
2867 llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
2868 Template->getAssociatedConstraints(AssociatedConstraints);
2869
2870 bool NeedsReplacement = DeducedArgsNeedReplacement(Template);
2871 TemplateArgumentList DeducedTAL{TemplateArgumentList::OnStack,
2872 CanonicalDeducedArgs};
2873
2874 MultiLevelTemplateArgumentList MLTAL = S.getTemplateInstantiationArgs(
2875 Template, /*Final=*/false,
2876 /*InnerMost=*/NeedsReplacement ? nullptr : &DeducedTAL,
2877 /*RelativeToPrimary=*/true, /*Pattern=*/
2878 nullptr, /*ForConstraintInstantiation=*/true);
2879
2880 // getTemplateInstantiationArgs picks up the non-deduced version of the
2881 // template args when this is a variable template partial specialization and
2882 // not class-scope explicit specialization, so replace with Deduced Args
2883 // instead of adding to inner-most.
2884 if (NeedsReplacement)
2885 MLTAL.replaceInnermostTemplateArguments(CanonicalDeducedArgs);
2886
2887 if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints, MLTAL,
2888 Info.getLocation(),
2889 Info.AssociatedConstraintsSatisfaction) ||
2890 !Info.AssociatedConstraintsSatisfaction.IsSatisfied) {
2891 Info.reset(
2892 TemplateArgumentList::CreateCopy(S.Context, SugaredDeducedArgs),
2893 TemplateArgumentList::CreateCopy(S.Context, CanonicalDeducedArgs));
2894 return Sema::TDK_ConstraintsNotSatisfied;
2895 }
2896 return Sema::TDK_Success;
2897}
2898
2899/// Complete template argument deduction for a partial specialization.
2900template <typename T>
2901static std::enable_if_t<IsPartialSpecialization<T>::value,
2902 Sema::TemplateDeductionResult>
2903FinishTemplateArgumentDeduction(
2904 Sema &S, T *Partial, bool IsPartialOrdering,
2905 const TemplateArgumentList &TemplateArgs,
2906 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2907 TemplateDeductionInfo &Info) {
2908 // Unevaluated SFINAE context.
2909 EnterExpressionEvaluationContext Unevaluated(
2910 S, Sema::ExpressionEvaluationContext::Unevaluated);
2911 Sema::SFINAETrap Trap(S);
2912
2913 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
2914
2915 // C++ [temp.deduct.type]p2:
2916 // [...] or if any template argument remains neither deduced nor
2917 // explicitly specified, template argument deduction fails.
2918 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
2919 if (auto Result = ConvertDeducedTemplateArguments(
2920 S, Partial, IsPartialOrdering, Deduced, Info, SugaredBuilder,
2921 CanonicalBuilder))
2922 return Result;
2923
2924 // Form the template argument list from the deduced template arguments.
2925 TemplateArgumentList *SugaredDeducedArgumentList =
2926 TemplateArgumentList::CreateCopy(S.Context, SugaredBuilder);
2927 TemplateArgumentList *CanonicalDeducedArgumentList =
2928 TemplateArgumentList::CreateCopy(S.Context, CanonicalBuilder);
2929
2930 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
2931
2932 // Substitute the deduced template arguments into the template
2933 // arguments of the class template partial specialization, and
2934 // verify that the instantiated template arguments are both valid
2935 // and are equivalent to the template arguments originally provided
2936 // to the class template.
2937 LocalInstantiationScope InstScope(S);
2938 auto *Template = Partial->getSpecializedTemplate();
2939 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2940 Partial->getTemplateArgsAsWritten();
2941
2942 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2943 PartialTemplArgInfo->RAngleLoc);
2944
2945 if (S.SubstTemplateArguments(PartialTemplArgInfo->arguments(),
2946 MultiLevelTemplateArgumentList(Partial,
2947 SugaredBuilder,
2948 /*Final=*/true),
2949 InstArgs)) {
2950 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2951 if (ParamIdx >= Partial->getTemplateParameters()->size())
2952 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2953
2954 Decl *Param = const_cast<NamedDecl *>(
2955 Partial->getTemplateParameters()->getParam(ParamIdx));
2956 Info.Param = makeTemplateParameter(Param);
2957 Info.FirstArg = (*PartialTemplArgInfo)[ArgIdx].getArgument();
2958 return Sema::TDK_SubstitutionFailure;
2959 }
2960
2961 bool ConstraintsNotSatisfied;
2962 SmallVector<TemplateArgument, 4> SugaredConvertedInstArgs,
2963 CanonicalConvertedInstArgs;
2964 if (S.CheckTemplateArgumentList(
2965 Template, Partial->getLocation(), InstArgs, false,
2966 SugaredConvertedInstArgs, CanonicalConvertedInstArgs,
2967 /*UpdateArgsWithConversions=*/true, &ConstraintsNotSatisfied))
2968 return ConstraintsNotSatisfied ? Sema::TDK_ConstraintsNotSatisfied
2969 : Sema::TDK_SubstitutionFailure;
2970
2971 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2972 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2973 TemplateArgument InstArg = SugaredConvertedInstArgs.data()[I];
2974 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
2975 IsPartialOrdering)) {
2976 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2977 Info.FirstArg = TemplateArgs[I];
2978 Info.SecondArg = InstArg;
2979 return Sema::TDK_NonDeducedMismatch;
2980 }
2981 }
2982
2983 if (Trap.hasErrorOccurred())
2984 return Sema::TDK_SubstitutionFailure;
2985
2986 if (auto Result = CheckDeducedArgumentConstraints(S, Partial, SugaredBuilder,
2987 CanonicalBuilder, Info))
2988 return Result;
2989
2990 return Sema::TDK_Success;
2991}
2992
2993/// Complete template argument deduction for a class or variable template,
2994/// when partial ordering against a partial specialization.
2995// FIXME: Factor out duplication with partial specialization version above.
2996static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2997 Sema &S, TemplateDecl *Template, bool PartialOrdering,
2998 const TemplateArgumentList &TemplateArgs,
2999 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3000 TemplateDeductionInfo &Info) {
3001 // Unevaluated SFINAE context.
3002 EnterExpressionEvaluationContext Unevaluated(
3003 S, Sema::ExpressionEvaluationContext::Unevaluated);
3004 Sema::SFINAETrap Trap(S);
3005
3006 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
3007
3008 // C++ [temp.deduct.type]p2:
3009 // [...] or if any template argument remains neither deduced nor
3010 // explicitly specified, template argument deduction fails.
3011 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3012 if (auto Result = ConvertDeducedTemplateArguments(
3013 S, Template, /*IsDeduced*/ PartialOrdering, Deduced, Info,
3014 SugaredBuilder, CanonicalBuilder,
3015 /*CurrentInstantiationScope=*/nullptr,
3016 /*NumAlreadyConverted=*/0U, /*PartialOverloading=*/false))
3017 return Result;
3018
3019 // Check that we produced the correct argument list.
3020 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
3021 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
3022 TemplateArgument InstArg = CanonicalBuilder[I];
3023 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg, PartialOrdering,
3024 /*PackExpansionMatchesPack=*/true)) {
3025 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
3026 Info.FirstArg = TemplateArgs[I];
3027 Info.SecondArg = InstArg;
3028 return Sema::TDK_NonDeducedMismatch;
3029 }
3030 }
3031
3032 if (Trap.hasErrorOccurred())
3033 return Sema::TDK_SubstitutionFailure;
3034
3035 if (auto Result = CheckDeducedArgumentConstraints(S, Template, SugaredBuilder,
3036 CanonicalBuilder, Info))
3037 return Result;
3038
3039 return Sema::TDK_Success;
3040}
3041
3042/// Perform template argument deduction to determine whether
3043/// the given template arguments match the given class template
3044/// partial specialization per C++ [temp.class.spec.match].
3045Sema::TemplateDeductionResult
3046Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
3047 const TemplateArgumentList &TemplateArgs,
3048 TemplateDeductionInfo &Info) {
3049 if (Partial->isInvalidDecl())
3050 return TDK_Invalid;
3051
3052 // C++ [temp.class.spec.match]p2:
3053 // A partial specialization matches a given actual template
3054 // argument list if the template arguments of the partial
3055 // specialization can be deduced from the actual template argument
3056 // list (14.8.2).
3057
3058 // Unevaluated SFINAE context.
3059 EnterExpressionEvaluationContext Unevaluated(
3060 *this, Sema::ExpressionEvaluationContext::Unevaluated);
3061 SFINAETrap Trap(*this);
3062
3063 // This deduction has no relation to any outer instantiation we might be
3064 // performing.
3065 LocalInstantiationScope InstantiationScope(*this);
3066
3067 SmallVector<DeducedTemplateArgument, 4> Deduced;
3068 Deduced.resize(Partial->getTemplateParameters()->size());
3069 if (TemplateDeductionResult Result
3070 = ::DeduceTemplateArguments(*this,
3071 Partial->getTemplateParameters(),
3072 Partial->getTemplateArgs(),
3073 TemplateArgs, Info, Deduced))
3074 return Result;
3075
3076 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3077 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
3078 Info);
3079 if (Inst.isInvalid())
3080 return TDK_InstantiationDepth;
3081
3082 if (Trap.hasErrorOccurred())
3083 return Sema::TDK_SubstitutionFailure;
3084
3085 TemplateDeductionResult Result;
3086 runWithSufficientStackSpace(Info.getLocation(), [&] {
3087 Result = ::FinishTemplateArgumentDeduction(*this, Partial,
3088 /*IsPartialOrdering=*/false,
3089 TemplateArgs, Deduced, Info);
3090 });
3091 return Result;
3092}
3093
3094/// Perform template argument deduction to determine whether
3095/// the given template arguments match the given variable template
3096/// partial specialization per C++ [temp.class.spec.match].
3097Sema::TemplateDeductionResult
3098Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
3099 const TemplateArgumentList &TemplateArgs,
3100 TemplateDeductionInfo &Info) {
3101 if (Partial->isInvalidDecl())
3102 return TDK_Invalid;
3103
3104 // C++ [temp.class.spec.match]p2:
3105 // A partial specialization matches a given actual template
3106 // argument list if the template arguments of the partial
3107 // specialization can be deduced from the actual template argument
3108 // list (14.8.2).
3109
3110 // Unevaluated SFINAE context.
3111 EnterExpressionEvaluationContext Unevaluated(
3112 *this, Sema::ExpressionEvaluationContext::Unevaluated);
3113 SFINAETrap Trap(*this);
3114
3115 // This deduction has no relation to any outer instantiation we might be
3116 // performing.
3117 LocalInstantiationScope InstantiationScope(*this);
3118
3119 SmallVector<DeducedTemplateArgument, 4> Deduced;
3120 Deduced.resize(Partial->getTemplateParameters()->size());
3121 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
3122 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
3123 TemplateArgs, Info, Deduced))
3124 return Result;
3125
3126 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3127 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
3128 Info);
3129 if (Inst.isInvalid())
3130 return TDK_InstantiationDepth;
3131
3132 if (Trap.hasErrorOccurred())
3133 return Sema::TDK_SubstitutionFailure;
3134
3135 TemplateDeductionResult Result;
3136 runWithSufficientStackSpace(Info.getLocation(), [&] {
3137 Result = ::FinishTemplateArgumentDeduction(*this, Partial,
3138 /*IsPartialOrdering=*/false,
3139 TemplateArgs, Deduced, Info);
3140 });
3141 return Result;
3142}
3143
3144/// Determine whether the given type T is a simple-template-id type.
3145static bool isSimpleTemplateIdType(QualType T) {
3146 if (const TemplateSpecializationType *Spec
3147 = T->getAs<TemplateSpecializationType>())
3148 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
3149
3150 // C++17 [temp.local]p2:
3151 // the injected-class-name [...] is equivalent to the template-name followed
3152 // by the template-arguments of the class template specialization or partial
3153 // specialization enclosed in <>
3154 // ... which means it's equivalent to a simple-template-id.
3155 //
3156 // This only arises during class template argument deduction for a copy
3157 // deduction candidate, where it permits slicing.
3158 if (T->getAs<InjectedClassNameType>())
3159 return true;
3160
3161 return false;
3162}
3163
3164/// Substitute the explicitly-provided template arguments into the
3165/// given function template according to C++ [temp.arg.explicit].
3166///
3167/// \param FunctionTemplate the function template into which the explicit
3168/// template arguments will be substituted.
3169///
3170/// \param ExplicitTemplateArgs the explicitly-specified template
3171/// arguments.
3172///
3173/// \param Deduced the deduced template arguments, which will be populated
3174/// with the converted and checked explicit template arguments.
3175///
3176/// \param ParamTypes will be populated with the instantiated function
3177/// parameters.
3178///
3179/// \param FunctionType if non-NULL, the result type of the function template
3180/// will also be instantiated and the pointed-to value will be updated with
3181/// the instantiated function type.
3182///
3183/// \param Info if substitution fails for any reason, this object will be
3184/// populated with more information about the failure.
3185///
3186/// \returns TDK_Success if substitution was successful, or some failure
3187/// condition.
3188Sema::TemplateDeductionResult Sema::SubstituteExplicitTemplateArguments(
3189 FunctionTemplateDecl *FunctionTemplate,
3190 TemplateArgumentListInfo &ExplicitTemplateArgs,
3191 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3192 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
3193 TemplateDeductionInfo &Info) {
3194 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3195 TemplateParameterList *TemplateParams
3196 = FunctionTemplate->getTemplateParameters();
3197
3198 if (ExplicitTemplateArgs.size() == 0) {
3199 // No arguments to substitute; just copy over the parameter types and
3200 // fill in the function type.
3201 for (auto *P : Function->parameters())
3202 ParamTypes.push_back(P->getType());
3203
3204 if (FunctionType)
3205 *FunctionType = Function->getType();
3206 return TDK_Success;
3207 }
3208
3209 // Unevaluated SFINAE context.
3210 EnterExpressionEvaluationContext Unevaluated(
3211 *this, Sema::ExpressionEvaluationContext::Unevaluated);
3212 SFINAETrap Trap(*this);
3213
3214 // C++ [temp.arg.explicit]p3:
3215 // Template arguments that are present shall be specified in the
3216 // declaration order of their corresponding template-parameters. The
3217 // template argument list shall not specify more template-arguments than
3218 // there are corresponding template-parameters.
3219 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3220
3221 // Enter a new template instantiation context where we check the
3222 // explicitly-specified template arguments against this function template,
3223 // and then substitute them into the function parameter types.
3224 SmallVector<TemplateArgument, 4> DeducedArgs;
3225 InstantiatingTemplate Inst(
3226 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3227 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
3228 if (Inst.isInvalid())
3229 return TDK_InstantiationDepth;
3230
3231 if (CheckTemplateArgumentList(FunctionTemplate, SourceLocation(),
3232 ExplicitTemplateArgs, true, SugaredBuilder,
3233 CanonicalBuilder,
3234 /*UpdateArgsWithConversions=*/false) ||
3235 Trap.hasErrorOccurred()) {
3236 unsigned Index = SugaredBuilder.size();
3237 if (Index >= TemplateParams->size())
3238 return TDK_SubstitutionFailure;
3239 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
3240 return TDK_InvalidExplicitArguments;
3241 }
3242
3243 // Form the template argument list from the explicitly-specified
3244 // template arguments.
3245 TemplateArgumentList *SugaredExplicitArgumentList =
3246 TemplateArgumentList::CreateCopy(Context, SugaredBuilder);
3247 TemplateArgumentList *CanonicalExplicitArgumentList =
3248 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder);
3249 Info.setExplicitArgs(SugaredExplicitArgumentList,
3250 CanonicalExplicitArgumentList);
3251
3252 // Template argument deduction and the final substitution should be
3253 // done in the context of the templated declaration. Explicit
3254 // argument substitution, on the other hand, needs to happen in the
3255 // calling context.
3256 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3257
3258 // If we deduced template arguments for a template parameter pack,
3259 // note that the template argument pack is partially substituted and record
3260 // the explicit template arguments. They'll be used as part of deduction
3261 // for this template parameter pack.
3262 unsigned PartiallySubstitutedPackIndex = -1u;
3263 if (!CanonicalBuilder.empty()) {
3264 const TemplateArgument &Arg = CanonicalBuilder.back();
3265 if (Arg.getKind() == TemplateArgument::Pack) {
3266 auto *Param = TemplateParams->getParam(CanonicalBuilder.size() - 1);
3267 // If this is a fully-saturated fixed-size pack, it should be
3268 // fully-substituted, not partially-substituted.
3269 std::optional<unsigned> Expansions = getExpandedPackSize(Param);
3270 if (!Expansions || Arg.pack_size() < *Expansions) {
3271 PartiallySubstitutedPackIndex = CanonicalBuilder.size() - 1;
3272 CurrentInstantiationScope->SetPartiallySubstitutedPack(
3273 Param, Arg.pack_begin(), Arg.pack_size());
3274 }
3275 }
3276 }
3277
3278 const FunctionProtoType *Proto
3279 = Function->getType()->getAs<FunctionProtoType>();
3280 assert(Proto && "Function template does not have a prototype?")(static_cast <bool> (Proto && "Function template does not have a prototype?"
) ? void (0) : __assert_fail ("Proto && \"Function template does not have a prototype?\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 3280, __extension__
__PRETTY_FUNCTION__))
;
3281
3282 // Isolate our substituted parameters from our caller.
3283 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
3284
3285 ExtParameterInfoBuilder ExtParamInfos;
3286
3287 MultiLevelTemplateArgumentList MLTAL(FunctionTemplate,
3288 SugaredExplicitArgumentList->asArray(),
3289 /*Final=*/true);
3290
3291 // Instantiate the types of each of the function parameters given the
3292 // explicitly-specified template arguments. If the function has a trailing
3293 // return type, substitute it after the arguments to ensure we substitute
3294 // in lexical order.
3295 if (Proto->hasTrailingReturn()) {
3296 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
3297 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3298 /*params=*/nullptr, ExtParamInfos))
3299 return TDK_SubstitutionFailure;
3300 }
3301
3302 // Instantiate the return type.
3303 QualType ResultType;
3304 {
3305 // C++11 [expr.prim.general]p3:
3306 // If a declaration declares a member function or member function
3307 // template of a class X, the expression this is a prvalue of type
3308 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3309 // and the end of the function-definition, member-declarator, or
3310 // declarator.
3311 Qualifiers ThisTypeQuals;
3312 CXXRecordDecl *ThisContext = nullptr;
3313 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3314 ThisContext = Method->getParent();
3315 ThisTypeQuals = Method->getMethodQualifiers();
3316 }
3317
3318 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
3319 getLangOpts().CPlusPlus11);
3320
3321 ResultType =
3322 SubstType(Proto->getReturnType(), MLTAL,
3323 Function->getTypeSpecStartLoc(), Function->getDeclName());
3324 if (ResultType.isNull() || Trap.hasErrorOccurred())
3325 return TDK_SubstitutionFailure;
3326 // CUDA: Kernel function must have 'void' return type.
3327 if (getLangOpts().CUDA)
3328 if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) {
3329 Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
3330 << Function->getType() << Function->getSourceRange();
3331 return TDK_SubstitutionFailure;
3332 }
3333 }
3334
3335 // Instantiate the types of each of the function parameters given the
3336 // explicitly-specified template arguments if we didn't do so earlier.
3337 if (!Proto->hasTrailingReturn() &&
3338 SubstParmTypes(Function->getLocation(), Function->parameters(),
3339 Proto->getExtParameterInfosOrNull(), MLTAL, ParamTypes,
3340 /*params*/ nullptr, ExtParamInfos))
3341 return TDK_SubstitutionFailure;
3342
3343 if (FunctionType) {
3344 auto EPI = Proto->getExtProtoInfo();
3345 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
3346
3347 // In C++1z onwards, exception specifications are part of the function type,
3348 // so substitution into the type must also substitute into the exception
3349 // specification.
3350 SmallVector<QualType, 4> ExceptionStorage;
3351 if (getLangOpts().CPlusPlus17 &&
3352 SubstExceptionSpec(Function->getLocation(), EPI.ExceptionSpec,
3353 ExceptionStorage, MLTAL))
3354 return TDK_SubstitutionFailure;
3355
3356 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
3357 Function->getLocation(),
3358 Function->getDeclName(),
3359 EPI);
3360 if (FunctionType->isNull() || Trap.hasErrorOccurred())
3361 return TDK_SubstitutionFailure;
3362 }
3363
3364 // C++ [temp.arg.explicit]p2:
3365 // Trailing template arguments that can be deduced (14.8.2) may be
3366 // omitted from the list of explicit template-arguments. If all of the
3367 // template arguments can be deduced, they may all be omitted; in this
3368 // case, the empty template argument list <> itself may also be omitted.
3369 //
3370 // Take all of the explicitly-specified arguments and put them into
3371 // the set of deduced template arguments. The partially-substituted
3372 // parameter pack, however, will be set to NULL since the deduction
3373 // mechanism handles the partially-substituted argument pack directly.
3374 Deduced.reserve(TemplateParams->size());
3375 for (unsigned I = 0, N = SugaredExplicitArgumentList->size(); I != N; ++I) {
3376 const TemplateArgument &Arg = SugaredExplicitArgumentList->get(I);
3377 if (I == PartiallySubstitutedPackIndex)
3378 Deduced.push_back(DeducedTemplateArgument());
3379 else
3380 Deduced.push_back(Arg);
3381 }
3382
3383 return TDK_Success;
3384}
3385
3386/// Check whether the deduced argument type for a call to a function
3387/// template matches the actual argument type per C++ [temp.deduct.call]p4.
3388static Sema::TemplateDeductionResult
3389CheckOriginalCallArgDeduction(Sema &S, TemplateDeductionInfo &Info,
3390 Sema::OriginalCallArg OriginalArg,
3391 QualType DeducedA) {
3392 ASTContext &Context = S.Context;
3393
3394 auto Failed = [&]() -> Sema::TemplateDeductionResult {
3395 Info.FirstArg = TemplateArgument(DeducedA);
3396 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3397 Info.CallArgIndex = OriginalArg.ArgIdx;
3398 return OriginalArg.DecomposedParam ? Sema::TDK_DeducedMismatchNested
3399 : Sema::TDK_DeducedMismatch;
3400 };
3401
3402 QualType A = OriginalArg.OriginalArgType;
3403 QualType OriginalParamType = OriginalArg.OriginalParamType;
3404
3405 // Check for type equality (top-level cv-qualifiers are ignored).
3406 if (Context.hasSameUnqualifiedType(A, DeducedA))
3407 return Sema::TDK_Success;
3408
3409 // Strip off references on the argument types; they aren't needed for
3410 // the following checks.
3411 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
3412 DeducedA = DeducedARef->getPointeeType();
3413 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3414 A = ARef->getPointeeType();
3415
3416 // C++ [temp.deduct.call]p4:
3417 // [...] However, there are three cases that allow a difference:
3418 // - If the original P is a reference type, the deduced A (i.e., the
3419 // type referred to by the reference) can be more cv-qualified than
3420 // the transformed A.
3421 if (const ReferenceType *OriginalParamRef
3422 = OriginalParamType->getAs<ReferenceType>()) {
3423 // We don't want to keep the reference around any more.
3424 OriginalParamType = OriginalParamRef->getPointeeType();
3425
3426 // FIXME: Resolve core issue (no number yet): if the original P is a
3427 // reference type and the transformed A is function type "noexcept F",
3428 // the deduced A can be F.
3429 QualType Tmp;
3430 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
3431 return Sema::TDK_Success;
3432
3433 Qualifiers AQuals = A.getQualifiers();
3434 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
3435
3436 // Under Objective-C++ ARC, the deduced type may have implicitly
3437 // been given strong or (when dealing with a const reference)
3438 // unsafe_unretained lifetime. If so, update the original
3439 // qualifiers to include this lifetime.
3440 if (S.getLangOpts().ObjCAutoRefCount &&
3441 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
3442 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
3443 (DeducedAQuals.hasConst() &&
3444 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
3445 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
3446 }
3447
3448 if (AQuals == DeducedAQuals) {
3449 // Qualifiers match; there's nothing to do.
3450 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
3451 return Failed();
3452 } else {
3453 // Qualifiers are compatible, so have the argument type adopt the
3454 // deduced argument type's qualifiers as if we had performed the
3455 // qualification conversion.
3456 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
3457 }
3458 }
3459
3460 // - The transformed A can be another pointer or pointer to member
3461 // type that can be converted to the deduced A via a function pointer
3462 // conversion and/or a qualification conversion.
3463 //
3464 // Also allow conversions which merely strip __attribute__((noreturn)) from
3465 // function types (recursively).
3466 bool ObjCLifetimeConversion = false;
3467 QualType ResultTy;
3468 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
3469 (S.IsQualificationConversion(A, DeducedA, false,
3470 ObjCLifetimeConversion) ||
3471 S.IsFunctionConversion(A, DeducedA, ResultTy)))
3472 return Sema::TDK_Success;
3473
3474 // - If P is a class and P has the form simple-template-id, then the
3475 // transformed A can be a derived class of the deduced A. [...]
3476 // [...] Likewise, if P is a pointer to a class of the form
3477 // simple-template-id, the transformed A can be a pointer to a
3478 // derived class pointed to by the deduced A.
3479 if (const PointerType *OriginalParamPtr
3480 = OriginalParamType->getAs<PointerType>()) {
3481 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
3482 if (const PointerType *APtr = A->getAs<PointerType>()) {
3483 if (A->getPointeeType()->isRecordType()) {
3484 OriginalParamType = OriginalParamPtr->getPointeeType();
3485 DeducedA = DeducedAPtr->getPointeeType();
3486 A = APtr->getPointeeType();
3487 }
3488 }
3489 }
3490 }
3491
3492 if (Context.hasSameUnqualifiedType(A, DeducedA))
3493 return Sema::TDK_Success;
3494
3495 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
3496 S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
3497 return Sema::TDK_Success;
3498
3499 return Failed();
3500}
3501
3502/// Find the pack index for a particular parameter index in an instantiation of
3503/// a function template with specific arguments.
3504///
3505/// \return The pack index for whichever pack produced this parameter, or -1
3506/// if this was not produced by a parameter. Intended to be used as the
3507/// ArgumentPackSubstitutionIndex for further substitutions.
3508// FIXME: We should track this in OriginalCallArgs so we don't need to
3509// reconstruct it here.
3510static unsigned getPackIndexForParam(Sema &S,
3511 FunctionTemplateDecl *FunctionTemplate,
3512 const MultiLevelTemplateArgumentList &Args,
3513 unsigned ParamIdx) {
3514 unsigned Idx = 0;
3515 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
3516 if (PD->isParameterPack()) {
3517 unsigned NumExpansions =
3518 S.getNumArgumentsInExpansion(PD->getType(), Args).value_or(1);
3519 if (Idx + NumExpansions > ParamIdx)
3520 return ParamIdx - Idx;
3521 Idx += NumExpansions;
3522 } else {
3523 if (Idx == ParamIdx)
3524 return -1; // Not a pack expansion
3525 ++Idx;
3526 }
3527 }
3528
3529 llvm_unreachable("parameter index would not be produced from template")::llvm::llvm_unreachable_internal("parameter index would not be produced from template"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 3529)
;
3530}
3531
3532/// Finish template argument deduction for a function template,
3533/// checking the deduced template arguments for completeness and forming
3534/// the function template specialization.
3535///
3536/// \param OriginalCallArgs If non-NULL, the original call arguments against
3537/// which the deduced argument types should be compared.
3538Sema::TemplateDeductionResult Sema::FinishTemplateArgumentDeduction(
3539 FunctionTemplateDecl *FunctionTemplate,
3540 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3541 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3542 TemplateDeductionInfo &Info,
3543 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3544 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
3545 // Unevaluated SFINAE context.
3546 EnterExpressionEvaluationContext Unevaluated(
3547 *this, Sema::ExpressionEvaluationContext::Unevaluated);
3548 SFINAETrap Trap(*this);
3549
3550 // Enter a new template instantiation context while we instantiate the
3551 // actual function declaration.
3552 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3553 InstantiatingTemplate Inst(
3554 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3555 CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info);
3556 if (Inst.isInvalid())
3557 return TDK_InstantiationDepth;
3558
3559 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3560
3561 // C++ [temp.deduct.type]p2:
3562 // [...] or if any template argument remains neither deduced nor
3563 // explicitly specified, template argument deduction fails.
3564 SmallVector<TemplateArgument, 4> SugaredBuilder, CanonicalBuilder;
3565 if (auto Result = ConvertDeducedTemplateArguments(
3566 *this, FunctionTemplate, /*IsDeduced*/ true, Deduced, Info,
3567 SugaredBuilder, CanonicalBuilder, CurrentInstantiationScope,
3568 NumExplicitlySpecified, PartialOverloading))
3569 return Result;
3570
3571 // C++ [temp.deduct.call]p10: [DR1391]
3572 // If deduction succeeds for all parameters that contain
3573 // template-parameters that participate in template argument deduction,
3574 // and all template arguments are explicitly specified, deduced, or
3575 // obtained from default template arguments, remaining parameters are then
3576 // compared with the corresponding arguments. For each remaining parameter
3577 // P with a type that was non-dependent before substitution of any
3578 // explicitly-specified template arguments, if the corresponding argument
3579 // A cannot be implicitly converted to P, deduction fails.
3580 if (CheckNonDependent())
3581 return TDK_NonDependentConversionFailure;
3582
3583 // Form the template argument list from the deduced template arguments.
3584 TemplateArgumentList *SugaredDeducedArgumentList =
3585 TemplateArgumentList::CreateCopy(Context, SugaredBuilder);
3586 TemplateArgumentList *CanonicalDeducedArgumentList =
3587 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder);
3588 Info.reset(SugaredDeducedArgumentList, CanonicalDeducedArgumentList);
3589
3590 // Substitute the deduced template arguments into the function template
3591 // declaration to produce the function template specialization.
3592 DeclContext *Owner = FunctionTemplate->getDeclContext();
3593 if (FunctionTemplate->getFriendObjectKind())
3594 Owner = FunctionTemplate->getLexicalDeclContext();
3595 MultiLevelTemplateArgumentList SubstArgs(
3596 FunctionTemplate, CanonicalDeducedArgumentList->asArray(),
3597 /*Final=*/false);
3598 Specialization = cast_or_null<FunctionDecl>(
3599 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, SubstArgs));
3600 if (!Specialization || Specialization->isInvalidDecl())
3601 return TDK_SubstitutionFailure;
3602
3603 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==(static_cast <bool> (Specialization->getPrimaryTemplate
()->getCanonicalDecl() == FunctionTemplate->getCanonicalDecl
()) ? void (0) : __assert_fail ("Specialization->getPrimaryTemplate()->getCanonicalDecl() == FunctionTemplate->getCanonicalDecl()"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 3604, __extension__
__PRETTY_FUNCTION__))
3604 FunctionTemplate->getCanonicalDecl())(static_cast <bool> (Specialization->getPrimaryTemplate
()->getCanonicalDecl() == FunctionTemplate->getCanonicalDecl
()) ? void (0) : __assert_fail ("Specialization->getPrimaryTemplate()->getCanonicalDecl() == FunctionTemplate->getCanonicalDecl()"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 3604, __extension__
__PRETTY_FUNCTION__))
;
3605
3606 // If the template argument list is owned by the function template
3607 // specialization, release it.
3608 if (Specialization->getTemplateSpecializationArgs() ==
3609 CanonicalDeducedArgumentList &&
3610 !Trap.hasErrorOccurred())
3611 Info.takeCanonical();
3612
3613 // There may have been an error that did not prevent us from constructing a
3614 // declaration. Mark the declaration invalid and return with a substitution
3615 // failure.
3616 if (Trap.hasErrorOccurred()) {
3617 Specialization->setInvalidDecl(true);
3618 return TDK_SubstitutionFailure;
3619 }
3620
3621 // C++2a [temp.deduct]p5
3622 // [...] When all template arguments have been deduced [...] all uses of
3623 // template parameters [...] are replaced with the corresponding deduced
3624 // or default argument values.
3625 // [...] If the function template has associated constraints
3626 // ([temp.constr.decl]), those constraints are checked for satisfaction
3627 // ([temp.constr.constr]). If the constraints are not satisfied, type
3628 // deduction fails.
3629 if (!PartialOverloading ||
3630 (CanonicalBuilder.size() ==
3631 FunctionTemplate->getTemplateParameters()->size())) {
3632 if (CheckInstantiatedFunctionTemplateConstraints(
3633 Info.getLocation(), Specialization, CanonicalBuilder,
3634 Info.AssociatedConstraintsSatisfaction))
3635 return TDK_MiscellaneousDeductionFailure;
3636
3637 if (!Info.AssociatedConstraintsSatisfaction.IsSatisfied) {
3638 Info.reset(Info.takeSugared(),
3639 TemplateArgumentList::CreateCopy(Context, CanonicalBuilder));
3640 return TDK_ConstraintsNotSatisfied;
3641 }
3642 }
3643
3644 if (OriginalCallArgs) {
3645 // C++ [temp.deduct.call]p4:
3646 // In general, the deduction process attempts to find template argument
3647 // values that will make the deduced A identical to A (after the type A
3648 // is transformed as described above). [...]
3649 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
3650 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
3651 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
3652
3653 auto ParamIdx = OriginalArg.ArgIdx;
3654 if (ParamIdx >= Specialization->getNumParams())
3655 // FIXME: This presumably means a pack ended up smaller than we
3656 // expected while deducing. Should this not result in deduction
3657 // failure? Can it even happen?
3658 continue;
3659
3660 QualType DeducedA;
3661 if (!OriginalArg.DecomposedParam) {
3662 // P is one of the function parameters, just look up its substituted
3663 // type.
3664 DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
3665 } else {
3666 // P is a decomposed element of a parameter corresponding to a
3667 // braced-init-list argument. Substitute back into P to find the
3668 // deduced A.
3669 QualType &CacheEntry =
3670 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
3671 if (CacheEntry.isNull()) {
3672 ArgumentPackSubstitutionIndexRAII PackIndex(
3673 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
3674 ParamIdx));
3675 CacheEntry =
3676 SubstType(OriginalArg.OriginalParamType, SubstArgs,
3677 Specialization->getTypeSpecStartLoc(),
3678 Specialization->getDeclName());
3679 }
3680 DeducedA = CacheEntry;
3681 }
3682
3683 if (auto TDK =
3684 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA))
3685 return TDK;
3686 }
3687 }
3688
3689 // If we suppressed any diagnostics while performing template argument
3690 // deduction, and if we haven't already instantiated this declaration,
3691 // keep track of these diagnostics. They'll be emitted if this specialization
3692 // is actually used.
3693 if (Info.diag_begin() != Info.diag_end()) {
3694 SuppressedDiagnosticsMap::iterator
3695 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
3696 if (Pos == SuppressedDiagnostics.end())
3697 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
3698 .append(Info.diag_begin(), Info.diag_end());
3699 }
3700
3701 return TDK_Success;
3702}
3703
3704/// Gets the type of a function for template-argument-deducton
3705/// purposes when it's considered as part of an overload set.
3706static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
3707 FunctionDecl *Fn) {
3708 // We may need to deduce the return type of the function now.
3709 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
3710 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
3711 return {};
3712
3713 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
3714 if (Method->isInstance()) {
3715 // An instance method that's referenced in a form that doesn't
3716 // look like a member pointer is just invalid.
3717 if (!R.HasFormOfMemberPointer)
3718 return {};
3719
3720 return S.Context.getMemberPointerType(Fn->getType(),
3721 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
3722 }
3723
3724 if (!R.IsAddressOfOperand) return Fn->getType();
3725 return S.Context.getPointerType(Fn->getType());
3726}
3727
3728/// Apply the deduction rules for overload sets.
3729///
3730/// \return the null type if this argument should be treated as an
3731/// undeduced context
3732static QualType
3733ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
3734 Expr *Arg, QualType ParamType,
3735 bool ParamWasReference) {
3736
3737 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
3738
3739 OverloadExpr *Ovl = R.Expression;
3740
3741 // C++0x [temp.deduct.call]p4
3742 unsigned TDF = 0;
3743 if (ParamWasReference)
3744 TDF |= TDF_ParamWithReferenceType;
3745 if (R.IsAddressOfOperand)
3746 TDF |= TDF_IgnoreQualifiers;
3747
3748 // C++0x [temp.deduct.call]p6:
3749 // When P is a function type, pointer to function type, or pointer
3750 // to member function type:
3751
3752 if (!ParamType->isFunctionType() &&
3753 !ParamType->isFunctionPointerType() &&
3754 !ParamType->isMemberFunctionPointerType()) {
3755 if (Ovl->hasExplicitTemplateArgs()) {
3756 // But we can still look for an explicit specialization.
3757 if (FunctionDecl *ExplicitSpec
3758 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
3759 return GetTypeOfFunction(S, R, ExplicitSpec);
3760 }
3761
3762 DeclAccessPair DAP;
3763 if (FunctionDecl *Viable =
3764 S.resolveAddressOfSingleOverloadCandidate(Arg, DAP))
3765 return GetTypeOfFunction(S, R, Viable);
3766
3767 return {};
3768 }
3769
3770 // Gather the explicit template arguments, if any.
3771 TemplateArgumentListInfo ExplicitTemplateArgs;
3772 if (Ovl->hasExplicitTemplateArgs())
3773 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
3774 QualType Match;
3775 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3776 E = Ovl->decls_end(); I != E; ++I) {
3777 NamedDecl *D = (*I)->getUnderlyingDecl();
3778
3779 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3780 // - If the argument is an overload set containing one or more
3781 // function templates, the parameter is treated as a
3782 // non-deduced context.
3783 if (!Ovl->hasExplicitTemplateArgs())
3784 return {};
3785
3786 // Otherwise, see if we can resolve a function type
3787 FunctionDecl *Specialization = nullptr;
3788 TemplateDeductionInfo Info(Ovl->getNameLoc());
3789 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3790 Specialization, Info))
3791 continue;
3792
3793 D = Specialization;
3794 }
3795
3796 FunctionDecl *Fn = cast<FunctionDecl>(D);
3797 QualType ArgType = GetTypeOfFunction(S, R, Fn);
3798 if (ArgType.isNull()) continue;
3799
3800 // Function-to-pointer conversion.
3801 if (!ParamWasReference && ParamType->isPointerType() &&
3802 ArgType->isFunctionType())
3803 ArgType = S.Context.getPointerType(ArgType);
3804
3805 // - If the argument is an overload set (not containing function
3806 // templates), trial argument deduction is attempted using each
3807 // of the members of the set. If deduction succeeds for only one
3808 // of the overload set members, that member is used as the
3809 // argument value for the deduction. If deduction succeeds for
3810 // more than one member of the overload set the parameter is
3811 // treated as a non-deduced context.
3812
3813 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3814 // Type deduction is done independently for each P/A pair, and
3815 // the deduced template argument values are then combined.
3816 // So we do not reject deductions which were made elsewhere.
3817 SmallVector<DeducedTemplateArgument, 8>
3818 Deduced(TemplateParams->size());
3819 TemplateDeductionInfo Info(Ovl->getNameLoc());
3820 Sema::TemplateDeductionResult Result
3821 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3822 ArgType, Info, Deduced, TDF);
3823 if (Result) continue;
3824 if (!Match.isNull())
3825 return {};
3826 Match = ArgType;
3827 }
3828
3829 return Match;
3830}
3831
3832/// Perform the adjustments to the parameter and argument types
3833/// described in C++ [temp.deduct.call].
3834///
3835/// \returns true if the caller should not attempt to perform any template
3836/// argument deduction based on this P/A pair because the argument is an
3837/// overloaded function set that could not be resolved.
3838static bool AdjustFunctionParmAndArgTypesForDeduction(
3839 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3840 QualType &ParamType, QualType &ArgType, Expr *Arg, unsigned &TDF) {
3841 // C++0x [temp.deduct.call]p3:
3842 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
3843 // are ignored for type deduction.
3844 if (ParamType.hasQualifiers())
3845 ParamType = ParamType.getUnqualifiedType();
3846
3847 // [...] If P is a reference type, the type referred to by P is
3848 // used for type deduction.
3849 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
3850 if (ParamRefType)
3851 ParamType = ParamRefType->getPointeeType();
3852
3853 // Overload sets usually make this parameter an undeduced context,
3854 // but there are sometimes special circumstances. Typically
3855 // involving a template-id-expr.
3856 if (ArgType == S.Context.OverloadTy) {
3857 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3858 Arg, ParamType,
3859 ParamRefType != nullptr);
3860 if (ArgType.isNull())
3861 return true;
3862 }
3863
3864 if (ParamRefType) {
3865 // If the argument has incomplete array type, try to complete its type.
3866 if (ArgType->isIncompleteArrayType())
3867 ArgType = S.getCompletedType(Arg);
3868
3869 // C++1z [temp.deduct.call]p3:
3870 // If P is a forwarding reference and the argument is an lvalue, the type
3871 // "lvalue reference to A" is used in place of A for type deduction.
3872 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
3873 Arg->isLValue()) {
3874 if (S.getLangOpts().OpenCL && !ArgType.hasAddressSpace())
3875 ArgType = S.Context.getAddrSpaceQualType(
3876 ArgType, S.Context.getDefaultOpenCLPointeeAddrSpace());
3877 ArgType = S.Context.getLValueReferenceType(ArgType);
3878 }
3879 } else {
3880 // C++ [temp.deduct.call]p2:
3881 // If P is not a reference type:
3882 // - If A is an array type, the pointer type produced by the
3883 // array-to-pointer standard conversion (4.2) is used in place of
3884 // A for type deduction; otherwise,
3885 // - If A is a function type, the pointer type produced by the
3886 // function-to-pointer standard conversion (4.3) is used in place
3887 // of A for type deduction; otherwise,
3888 if (ArgType->canDecayToPointerType())
3889 ArgType = S.Context.getDecayedType(ArgType);
3890 else {
3891 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
3892 // type are ignored for type deduction.
3893 ArgType = ArgType.getUnqualifiedType();
3894 }
3895 }
3896
3897 // C++0x [temp.deduct.call]p4:
3898 // In general, the deduction process attempts to find template argument
3899 // values that will make the deduced A identical to A (after the type A
3900 // is transformed as described above). [...]
3901 TDF = TDF_SkipNonDependent;
3902
3903 // - If the original P is a reference type, the deduced A (i.e., the
3904 // type referred to by the reference) can be more cv-qualified than
3905 // the transformed A.
3906 if (ParamRefType)
3907 TDF |= TDF_ParamWithReferenceType;
3908 // - The transformed A can be another pointer or pointer to member
3909 // type that can be converted to the deduced A via a qualification
3910 // conversion (4.4).
3911 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3912 ArgType->isObjCObjectPointerType())
3913 TDF |= TDF_IgnoreQualifiers;
3914 // - If P is a class and P has the form simple-template-id, then the
3915 // transformed A can be a derived class of the deduced A. Likewise,
3916 // if P is a pointer to a class of the form simple-template-id, the
3917 // transformed A can be a pointer to a derived class pointed to by
3918 // the deduced A.
3919 if (isSimpleTemplateIdType(ParamType) ||
3920 (isa<PointerType>(ParamType) &&
3921 isSimpleTemplateIdType(
3922 ParamType->castAs<PointerType>()->getPointeeType())))
3923 TDF |= TDF_DerivedClass;
3924
3925 return false;
3926}
3927
3928static bool
3929hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3930 QualType T);
3931
3932static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
3933 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3934 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
3935 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3936 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
3937 bool DecomposedParam, unsigned ArgIdx, unsigned TDF);
3938
3939/// Attempt template argument deduction from an initializer list
3940/// deemed to be an argument in a function call.
3941static Sema::TemplateDeductionResult DeduceFromInitializerList(
3942 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
3943 InitListExpr *ILE, TemplateDeductionInfo &Info,
3944 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3945 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
3946 unsigned TDF) {
3947 // C++ [temp.deduct.call]p1: (CWG 1591)
3948 // If removing references and cv-qualifiers from P gives
3949 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
3950 // a non-empty initializer list, then deduction is performed instead for
3951 // each element of the initializer list, taking P0 as a function template
3952 // parameter type and the initializer element as its argument
3953 //
3954 // We've already removed references and cv-qualifiers here.
3955 if (!ILE->getNumInits())
3956 return Sema::TDK_Success;
3957
3958 QualType ElTy;
3959 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
3960 if (ArrTy)
3961 ElTy = ArrTy->getElementType();
3962 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
3963 // Otherwise, an initializer list argument causes the parameter to be
3964 // considered a non-deduced context
3965 return Sema::TDK_Success;
3966 }
3967
3968 // Resolving a core issue: a braced-init-list containing any designators is
3969 // a non-deduced context.
3970 for (Expr *E : ILE->inits())
3971 if (isa<DesignatedInitExpr>(E))
3972 return Sema::TDK_Success;
3973
3974 // Deduction only needs to be done for dependent types.
3975 if (ElTy->isDependentType()) {
3976 for (Expr *E : ILE->inits()) {
3977 if (auto Result = DeduceTemplateArgumentsFromCallArgument(
3978 S, TemplateParams, 0, ElTy, E, Info, Deduced, OriginalCallArgs, true,
3979 ArgIdx, TDF))
3980 return Result;
3981 }
3982 }
3983
3984 // in the P0[N] case, if N is a non-type template parameter, N is deduced
3985 // from the length of the initializer list.
3986 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
3987 // Determine the array bound is something we can deduce.
3988 if (const NonTypeTemplateParmDecl *NTTP =
3989 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
3990 // We can perform template argument deduction for the given non-type
3991 // template parameter.
3992 // C++ [temp.deduct.type]p13:
3993 // The type of N in the type T[N] is std::size_t.
3994 QualType T = S.Context.getSizeType();
3995 llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
3996 if (auto Result = DeduceNonTypeTemplateArgument(
3997 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
3998 /*ArrayBound=*/true, Info, Deduced))
3999 return Result;
4000 }
4001 }
4002
4003 return Sema::TDK_Success;
4004}
4005
4006/// Perform template argument deduction per [temp.deduct.call] for a
4007/// single parameter / argument pair.
4008static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
4009 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
4010 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
4011 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
4012 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
4013 bool DecomposedParam, unsigned ArgIdx, unsigned TDF) {
4014 QualType ArgType = Arg->getType();
4015 QualType OrigParamType = ParamType;
4016
4017 // If P is a reference type [...]
4018 // If P is a cv-qualified type [...]
4019 if (AdjustFunctionParmAndArgTypesForDeduction(
4020 S, TemplateParams, FirstInnerIndex, ParamType, ArgType, Arg, TDF))
4021 return Sema::TDK_Success;
4022
4023 // If [...] the argument is a non-empty initializer list [...]
4024 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg))
4025 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
4026 Deduced, OriginalCallArgs, ArgIdx, TDF);
4027
4028 // [...] the deduction process attempts to find template argument values
4029 // that will make the deduced A identical to A
4030 //
4031 // Keep track of the argument type and corresponding parameter index,
4032 // so we can check for compatibility between the deduced A and A.
4033 OriginalCallArgs.push_back(
4034 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
4035 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
4036 ArgType, Info, Deduced, TDF);
4037}
4038
4039/// Perform template argument deduction from a function call
4040/// (C++ [temp.deduct.call]).
4041///
4042/// \param FunctionTemplate the function template for which we are performing
4043/// template argument deduction.
4044///
4045/// \param ExplicitTemplateArgs the explicit template arguments provided
4046/// for this call.
4047///
4048/// \param Args the function call arguments
4049///
4050/// \param Specialization if template argument deduction was successful,
4051/// this will be set to the function template specialization produced by
4052/// template argument deduction.
4053///
4054/// \param Info the argument will be updated to provide additional information
4055/// about template argument deduction.
4056///
4057/// \param CheckNonDependent A callback to invoke to check conversions for
4058/// non-dependent parameters, between deduction and substitution, per DR1391.
4059/// If this returns true, substitution will be skipped and we return
4060/// TDK_NonDependentConversionFailure. The callback is passed the parameter
4061/// types (after substituting explicit template arguments).
4062///
4063/// \returns the result of template argument deduction.
4064Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
4065 FunctionTemplateDecl *FunctionTemplate,
4066 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
4067 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4068 bool PartialOverloading,
4069 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
4070 if (FunctionTemplate->isInvalidDecl())
4071 return TDK_Invalid;
4072
4073 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4074 unsigned NumParams = Function->getNumParams();
4075
4076 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
4077
4078 // C++ [temp.deduct.call]p1:
4079 // Template argument deduction is done by comparing each function template
4080 // parameter type (call it P) with the type of the corresponding argument
4081 // of the call (call it A) as described below.
4082 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
4083 return TDK_TooFewArguments;
4084 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
4085 const auto *Proto = Function->getType()->castAs<FunctionProtoType>();
4086 if (Proto->isTemplateVariadic())
4087 /* Do nothing */;
4088 else if (!Proto->isVariadic())
4089 return TDK_TooManyArguments;
4090 }
4091
4092 // The types of the parameters from which we will perform template argument
4093 // deduction.
4094 LocalInstantiationScope InstScope(*this);
4095 TemplateParameterList *TemplateParams
4096 = FunctionTemplate->getTemplateParameters();
4097 SmallVector<DeducedTemplateArgument, 4> Deduced;
4098 SmallVector<QualType, 8> ParamTypes;
4099 unsigned NumExplicitlySpecified = 0;
4100 if (ExplicitTemplateArgs) {
4101 TemplateDeductionResult Result;
4102 runWithSufficientStackSpace(Info.getLocation(), [&] {
4103 Result = SubstituteExplicitTemplateArguments(
4104 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, nullptr,
4105 Info);
4106 });
4107 if (Result)
4108 return Result;
4109
4110 NumExplicitlySpecified = Deduced.size();
4111 } else {
4112 // Just fill in the parameter types from the function declaration.
4113 for (unsigned I = 0; I != NumParams; ++I)
4114 ParamTypes.push_back(Function->getParamDecl(I)->getType());
4115 }
4116
4117 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
4118
4119 // Deduce an argument of type ParamType from an expression with index ArgIdx.
4120 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx) {
4121 // C++ [demp.deduct.call]p1: (DR1391)
4122 // Template argument deduction is done by comparing each function template
4123 // parameter that contains template-parameters that participate in
4124 // template argument deduction ...
4125 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
4126 return Sema::TDK_Success;
4127
4128 // ... with the type of the corresponding argument
4129 return DeduceTemplateArgumentsFromCallArgument(
4130 *this, TemplateParams, FirstInnerIndex, ParamType, Args[ArgIdx], Info, Deduced,
4131 OriginalCallArgs, /*Decomposed*/false, ArgIdx, /*TDF*/ 0);
4132 };
4133
4134 // Deduce template arguments from the function parameters.
4135 Deduced.resize(TemplateParams->size());
4136 SmallVector<QualType, 8> ParamTypesForArgChecking;
4137 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
4138 ParamIdx != NumParamTypes; ++ParamIdx) {
4139 QualType ParamType = ParamTypes[ParamIdx];
4140
4141 const PackExpansionType *ParamExpansion =
4142 dyn_cast<PackExpansionType>(ParamType);
4143 if (!ParamExpansion) {
4144 // Simple case: matching a function parameter to a function argument.
4145 if (ArgIdx >= Args.size())
4146 break;
4147
4148 ParamTypesForArgChecking.push_back(ParamType);
4149 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++))
4150 return Result;
4151
4152 continue;
4153 }
4154
4155 QualType ParamPattern = ParamExpansion->getPattern();
4156 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
4157 ParamPattern);
4158
4159 // C++0x [temp.deduct.call]p1:
4160 // For a function parameter pack that occurs at the end of the
4161 // parameter-declaration-list, the type A of each remaining argument of
4162 // the call is compared with the type P of the declarator-id of the
4163 // function parameter pack. Each comparison deduces template arguments
4164 // for subsequent positions in the template parameter packs expanded by
4165 // the function parameter pack. When a function parameter pack appears
4166 // in a non-deduced context [not at the end of the list], the type of
4167 // that parameter pack is never deduced.
4168 //
4169 // FIXME: The above rule allows the size of the parameter pack to change
4170 // after we skip it (in the non-deduced case). That makes no sense, so
4171 // we instead notionally deduce the pack against N arguments, where N is
4172 // the length of the explicitly-specified pack if it's expanded by the
4173 // parameter pack and 0 otherwise, and we treat each deduction as a
4174 // non-deduced context.
4175 if (ParamIdx + 1 == NumParamTypes || PackScope.hasFixedArity()) {
4176 for (; ArgIdx < Args.size() && PackScope.hasNextElement();
4177 PackScope.nextPackElement(), ++ArgIdx) {
4178 ParamTypesForArgChecking.push_back(ParamPattern);
4179 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx))
4180 return Result;
4181 }
4182 } else {
4183 // If the parameter type contains an explicitly-specified pack that we
4184 // could not expand, skip the number of parameters notionally created
4185 // by the expansion.
4186 std::optional<unsigned> NumExpansions =
4187 ParamExpansion->getNumExpansions();
4188 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
4189 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
4190 ++I, ++ArgIdx) {
4191 ParamTypesForArgChecking.push_back(ParamPattern);
4192 // FIXME: Should we add OriginalCallArgs for these? What if the
4193 // corresponding argument is a list?
4194 PackScope.nextPackElement();
4195 }
4196 }
4197 }
4198
4199 // Build argument packs for each of the parameter packs expanded by this
4200 // pack expansion.
4201 if (auto Result = PackScope.finish())
4202 return Result;
4203 }
4204
4205 // Capture the context in which the function call is made. This is the context
4206 // that is needed when the accessibility of template arguments is checked.
4207 DeclContext *CallingCtx = CurContext;
4208
4209 TemplateDeductionResult Result;
4210 runWithSufficientStackSpace(Info.getLocation(), [&] {
4211 Result = FinishTemplateArgumentDeduction(
4212 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
4213 &OriginalCallArgs, PartialOverloading, [&, CallingCtx]() {
4214 ContextRAII SavedContext(*this, CallingCtx);
4215 return CheckNonDependent(ParamTypesForArgChecking);
4216 });
4217 });
4218 return Result;
4219}
4220
4221QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
4222 QualType FunctionType,
4223 bool AdjustExceptionSpec) {
4224 if (ArgFunctionType.isNull())
4225 return ArgFunctionType;
4226
4227 const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>();
4228 const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>();
4229 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
4230 bool Rebuild = false;
4231
4232 CallingConv CC = FunctionTypeP->getCallConv();
4233 if (EPI.ExtInfo.getCC() != CC) {
4234 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
4235 Rebuild = true;
4236 }
4237
4238 bool NoReturn = FunctionTypeP->getNoReturnAttr();
4239 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
4240 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
4241 Rebuild = true;
4242 }
4243
4244 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
4245 ArgFunctionTypeP->hasExceptionSpec())) {
4246 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
4247 Rebuild = true;
4248 }
4249
4250 if (!Rebuild)
4251 return ArgFunctionType;
4252
4253 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
4254 ArgFunctionTypeP->getParamTypes(), EPI);
4255}
4256
4257/// Deduce template arguments when taking the address of a function
4258/// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
4259/// a template.
4260///
4261/// \param FunctionTemplate the function template for which we are performing
4262/// template argument deduction.
4263///
4264/// \param ExplicitTemplateArgs the explicitly-specified template
4265/// arguments.
4266///
4267/// \param ArgFunctionType the function type that will be used as the
4268/// "argument" type (A) when performing template argument deduction from the
4269/// function template's function type. This type may be NULL, if there is no
4270/// argument type to compare against, in C++0x [temp.arg.explicit]p3.
4271///
4272/// \param Specialization if template argument deduction was successful,
4273/// this will be set to the function template specialization produced by
4274/// template argument deduction.
4275///
4276/// \param Info the argument will be updated to provide additional information
4277/// about template argument deduction.
4278///
4279/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4280/// the address of a function template per [temp.deduct.funcaddr] and
4281/// [over.over]. If \c false, we are looking up a function template
4282/// specialization based on its signature, per [temp.deduct.decl].
4283///
4284/// \returns the result of template argument deduction.
4285Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
4286 FunctionTemplateDecl *FunctionTemplate,
4287 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
4288 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4289 bool IsAddressOfFunction) {
4290 if (FunctionTemplate->isInvalidDecl())
4291 return TDK_Invalid;
4292
4293 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
4294 TemplateParameterList *TemplateParams
4295 = FunctionTemplate->getTemplateParameters();
4296 QualType FunctionType = Function->getType();
4297
4298 // Substitute any explicit template arguments.
4299 LocalInstantiationScope InstScope(*this);
4300 SmallVector<DeducedTemplateArgument, 4> Deduced;
4301 unsigned NumExplicitlySpecified = 0;
4302 SmallVector<QualType, 4> ParamTypes;
4303 if (ExplicitTemplateArgs) {
4304 TemplateDeductionResult Result;
4305 runWithSufficientStackSpace(Info.getLocation(), [&] {
4306 Result = SubstituteExplicitTemplateArguments(
4307 FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes,
4308 &FunctionType, Info);
4309 });
4310 if (Result)
4311 return Result;
4312
4313 NumExplicitlySpecified = Deduced.size();
4314 }
4315
4316 // When taking the address of a function, we require convertibility of
4317 // the resulting function type. Otherwise, we allow arbitrary mismatches
4318 // of calling convention and noreturn.
4319 if (!IsAddressOfFunction)
4320 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
4321 /*AdjustExceptionSpec*/false);
4322
4323 // Unevaluated SFINAE context.
4324 EnterExpressionEvaluationContext Unevaluated(
4325 *this, Sema::ExpressionEvaluationContext::Unevaluated);
4326 SFINAETrap Trap(*this);
4327
4328 Deduced.resize(TemplateParams->size());
4329
4330 // If the function has a deduced return type, substitute it for a dependent
4331 // type so that we treat it as a non-deduced context in what follows. If we
4332 // are looking up by signature, the signature type should also have a deduced
4333 // return type, which we instead expect to exactly match.
4334 bool HasDeducedReturnType = false;
4335 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
4336 Function->getReturnType()->getContainedAutoType()) {
4337 FunctionType = SubstAutoTypeDependent(FunctionType);
4338 HasDeducedReturnType = true;
4339 }
4340
4341 if (!ArgFunctionType.isNull() && !FunctionType.isNull()) {
4342 unsigned TDF =
4343 TDF_TopLevelParameterTypeList | TDF_AllowCompatibleFunctionType;
4344 // Deduce template arguments from the function type.
4345 if (TemplateDeductionResult Result
4346 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
4347 FunctionType, ArgFunctionType,
4348 Info, Deduced, TDF))
4349 return Result;
4350 }
4351
4352 TemplateDeductionResult Result;
4353 runWithSufficientStackSpace(Info.getLocation(), [&] {
4354 Result = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
4355 NumExplicitlySpecified,
4356 Specialization, Info);
4357 });
4358 if (Result)
4359 return Result;
4360
4361 // If the function has a deduced return type, deduce it now, so we can check
4362 // that the deduced function type matches the requested type.
4363 if (HasDeducedReturnType &&
4364 Specialization->getReturnType()->isUndeducedType() &&
4365 DeduceReturnType(Specialization, Info.getLocation(), false))
4366 return TDK_MiscellaneousDeductionFailure;
4367
4368 // If the function has a dependent exception specification, resolve it now,
4369 // so we can check that the exception specification matches.
4370 auto *SpecializationFPT =
4371 Specialization->getType()->castAs<FunctionProtoType>();
4372 if (getLangOpts().CPlusPlus17 &&
4373 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
4374 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
4375 return TDK_MiscellaneousDeductionFailure;
4376
4377 // Adjust the exception specification of the argument to match the
4378 // substituted and resolved type we just formed. (Calling convention and
4379 // noreturn can't be dependent, so we don't actually need this for them
4380 // right now.)
4381 QualType SpecializationType = Specialization->getType();
4382 if (!IsAddressOfFunction)
4383 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
4384 /*AdjustExceptionSpec*/true);
4385
4386 // If the requested function type does not match the actual type of the
4387 // specialization with respect to arguments of compatible pointer to function
4388 // types, template argument deduction fails.
4389 if (!ArgFunctionType.isNull()) {
4390 if (IsAddressOfFunction &&
4391 !isSameOrCompatibleFunctionType(
4392 Context.getCanonicalType(SpecializationType),
4393 Context.getCanonicalType(ArgFunctionType)))
4394 return TDK_MiscellaneousDeductionFailure;
4395
4396 if (!IsAddressOfFunction &&
4397 !Context.hasSameType(SpecializationType, ArgFunctionType))
4398 return TDK_MiscellaneousDeductionFailure;
4399 }
4400
4401 return TDK_Success;
4402}
4403
4404/// Deduce template arguments for a templated conversion
4405/// function (C++ [temp.deduct.conv]) and, if successful, produce a
4406/// conversion function template specialization.
4407Sema::TemplateDeductionResult
4408Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
4409 QualType ToType,
4410 CXXConversionDecl *&Specialization,
4411 TemplateDeductionInfo &Info) {
4412 if (ConversionTemplate->isInvalidDecl())
4413 return TDK_Invalid;
4414
4415 CXXConversionDecl *ConversionGeneric
4416 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
4417
4418 QualType FromType = ConversionGeneric->getConversionType();
4419
4420 // Canonicalize the types for deduction.
4421 QualType P = Context.getCanonicalType(FromType);
4422 QualType A = Context.getCanonicalType(ToType);
4423
4424 // C++0x [temp.deduct.conv]p2:
4425 // If P is a reference type, the type referred to by P is used for
4426 // type deduction.
4427 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
4428 P = PRef->getPointeeType();
4429
4430 // C++0x [temp.deduct.conv]p4:
4431 // [...] If A is a reference type, the type referred to by A is used
4432 // for type deduction.
4433 if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
4434 A = ARef->getPointeeType();
4435 // We work around a defect in the standard here: cv-qualifiers are also
4436 // removed from P and A in this case, unless P was a reference type. This
4437 // seems to mostly match what other compilers are doing.
4438 if (!FromType->getAs<ReferenceType>()) {
4439 A = A.getUnqualifiedType();
4440 P = P.getUnqualifiedType();
4441 }
4442
4443 // C++ [temp.deduct.conv]p3:
4444 //
4445 // If A is not a reference type:
4446 } else {
4447 assert(!A->isReferenceType() && "Reference types were handled above")(static_cast <bool> (!A->isReferenceType() &&
"Reference types were handled above") ? void (0) : __assert_fail
("!A->isReferenceType() && \"Reference types were handled above\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 4447, __extension__
__PRETTY_FUNCTION__))
;
4448
4449 // - If P is an array type, the pointer type produced by the
4450 // array-to-pointer standard conversion (4.2) is used in place
4451 // of P for type deduction; otherwise,
4452 if (P->isArrayType())
4453 P = Context.getArrayDecayedType(P);
4454 // - If P is a function type, the pointer type produced by the
4455 // function-to-pointer standard conversion (4.3) is used in
4456 // place of P for type deduction; otherwise,
4457 else if (P->isFunctionType())
4458 P = Context.getPointerType(P);
4459 // - If P is a cv-qualified type, the top level cv-qualifiers of
4460 // P's type are ignored for type deduction.
4461 else
4462 P = P.getUnqualifiedType();
4463
4464 // C++0x [temp.deduct.conv]p4:
4465 // If A is a cv-qualified type, the top level cv-qualifiers of A's
4466 // type are ignored for type deduction. If A is a reference type, the type
4467 // referred to by A is used for type deduction.
4468 A = A.getUnqualifiedType();
4469 }
4470
4471 // Unevaluated SFINAE context.
4472 EnterExpressionEvaluationContext Unevaluated(
4473 *this, Sema::ExpressionEvaluationContext::Unevaluated);
4474 SFINAETrap Trap(*this);
4475
4476 // C++ [temp.deduct.conv]p1:
4477 // Template argument deduction is done by comparing the return
4478 // type of the template conversion function (call it P) with the
4479 // type that is required as the result of the conversion (call it
4480 // A) as described in 14.8.2.4.
4481 TemplateParameterList *TemplateParams
4482 = ConversionTemplate->getTemplateParameters();
4483 SmallVector<DeducedTemplateArgument, 4> Deduced;
4484 Deduced.resize(TemplateParams->size());
4485
4486 // C++0x [temp.deduct.conv]p4:
4487 // In general, the deduction process attempts to find template
4488 // argument values that will make the deduced A identical to
4489 // A. However, there are two cases that allow a difference:
4490 unsigned TDF = 0;
4491 // - If the original A is a reference type, A can be more
4492 // cv-qualified than the deduced A (i.e., the type referred to
4493 // by the reference)
4494 if (ToType->isReferenceType())
4495 TDF |= TDF_ArgWithReferenceType;
4496 // - The deduced A can be another pointer or pointer to member
4497 // type that can be converted to A via a qualification
4498 // conversion.
4499 //
4500 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
4501 // both P and A are pointers or member pointers. In this case, we
4502 // just ignore cv-qualifiers completely).
4503 if ((P->isPointerType() && A->isPointerType()) ||
4504 (P->isMemberPointerType() && A->isMemberPointerType()))
4505 TDF |= TDF_IgnoreQualifiers;
4506 if (TemplateDeductionResult Result
4507 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
4508 P, A, Info, Deduced, TDF))
4509 return Result;
4510
4511 // Create an Instantiation Scope for finalizing the operator.
4512 LocalInstantiationScope InstScope(*this);
4513 // Finish template argument deduction.
4514 FunctionDecl *ConversionSpecialized = nullptr;
4515 TemplateDeductionResult Result;
4516 runWithSufficientStackSpace(Info.getLocation(), [&] {
4517 Result = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
4518 ConversionSpecialized, Info);
4519 });
4520 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
4521 return Result;
4522}
4523
4524/// Deduce template arguments for a function template when there is
4525/// nothing to deduce against (C++0x [temp.arg.explicit]p3).
4526///
4527/// \param FunctionTemplate the function template for which we are performing
4528/// template argument deduction.
4529///
4530/// \param ExplicitTemplateArgs the explicitly-specified template
4531/// arguments.
4532///
4533/// \param Specialization if template argument deduction was successful,
4534/// this will be set to the function template specialization produced by
4535/// template argument deduction.
4536///
4537/// \param Info the argument will be updated to provide additional information
4538/// about template argument deduction.
4539///
4540/// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4541/// the address of a function template in a context where we do not have a
4542/// target type, per [over.over]. If \c false, we are looking up a function
4543/// template specialization based on its signature, which only happens when
4544/// deducing a function parameter type from an argument that is a template-id
4545/// naming a function template specialization.
4546///
4547/// \returns the result of template argument deduction.
4548Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
4549 FunctionTemplateDecl *FunctionTemplate,
4550 TemplateArgumentListInfo *ExplicitTemplateArgs,
4551 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4552 bool IsAddressOfFunction) {
4553 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
4554 QualType(), Specialization, Info,
4555 IsAddressOfFunction);
4556}
4557
4558namespace {
4559 struct DependentAuto { bool IsPack; };
4560
4561 /// Substitute the 'auto' specifier or deduced template specialization type
4562 /// specifier within a type for a given replacement type.
4563 class SubstituteDeducedTypeTransform :
4564 public TreeTransform<SubstituteDeducedTypeTransform> {
4565 QualType Replacement;
4566 bool ReplacementIsPack;
4567 bool UseTypeSugar;
4568
4569 public:
4570 SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
4571 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
4572 ReplacementIsPack(DA.IsPack), UseTypeSugar(true) {}
4573
4574 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
4575 bool UseTypeSugar = true)
4576 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
4577 Replacement(Replacement), ReplacementIsPack(false),
4578 UseTypeSugar(UseTypeSugar) {}
4579
4580 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
4581 assert(isa<TemplateTypeParmType>(Replacement) &&(static_cast <bool> (isa<TemplateTypeParmType>(Replacement
) && "unexpected unsugared replacement kind") ? void (
0) : __assert_fail ("isa<TemplateTypeParmType>(Replacement) && \"unexpected unsugared replacement kind\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 4582, __extension__
__PRETTY_FUNCTION__))
4582 "unexpected unsugared replacement kind")(static_cast <bool> (isa<TemplateTypeParmType>(Replacement
) && "unexpected unsugared replacement kind") ? void (
0) : __assert_fail ("isa<TemplateTypeParmType>(Replacement) && \"unexpected unsugared replacement kind\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 4582, __extension__
__PRETTY_FUNCTION__))
;
4583 QualType Result = Replacement;
4584 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
4585 NewTL.setNameLoc(TL.getNameLoc());
4586 return Result;
4587 }
4588
4589 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
4590 // If we're building the type pattern to deduce against, don't wrap the
4591 // substituted type in an AutoType. Certain template deduction rules
4592 // apply only when a template type parameter appears directly (and not if
4593 // the parameter is found through desugaring). For instance:
4594 // auto &&lref = lvalue;
4595 // must transform into "rvalue reference to T" not "rvalue reference to
4596 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
4597 //
4598 // FIXME: Is this still necessary?
4599 if (!UseTypeSugar)
4600 return TransformDesugared(TLB, TL);
4601
4602 QualType Result = SemaRef.Context.getAutoType(
4603 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull(),
4604 ReplacementIsPack, TL.getTypePtr()->getTypeConstraintConcept(),
4605 TL.getTypePtr()->getTypeConstraintArguments());
4606 auto NewTL = TLB.push<AutoTypeLoc>(Result);
4607 NewTL.copy(TL);
4608 return Result;
4609 }
4610
4611 QualType TransformDeducedTemplateSpecializationType(
4612 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
4613 if (!UseTypeSugar)
4614 return TransformDesugared(TLB, TL);
4615
4616 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
4617 TL.getTypePtr()->getTemplateName(),
4618 Replacement, Replacement.isNull());
4619 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
4620 NewTL.setNameLoc(TL.getNameLoc());
4621 return Result;
4622 }
4623
4624 ExprResult TransformLambdaExpr(LambdaExpr *E) {
4625 // Lambdas never need to be transformed.
4626 return E;
4627 }
4628
4629 QualType Apply(TypeLoc TL) {
4630 // Create some scratch storage for the transformed type locations.
4631 // FIXME: We're just going to throw this information away. Don't build it.
4632 TypeLocBuilder TLB;
4633 TLB.reserve(TL.getFullDataSize());
4634 return TransformType(TLB, TL);
4635 }
4636 };
4637
4638} // namespace
4639
4640static bool CheckDeducedPlaceholderConstraints(Sema &S, const AutoType &Type,
4641 AutoTypeLoc TypeLoc,
4642 QualType Deduced) {
4643 ConstraintSatisfaction Satisfaction;
4644 ConceptDecl *Concept = Type.getTypeConstraintConcept();
4645 TemplateArgumentListInfo TemplateArgs(TypeLoc.getLAngleLoc(),
4646 TypeLoc.getRAngleLoc());
4647 TemplateArgs.addArgument(
4648 TemplateArgumentLoc(TemplateArgument(Deduced),
4649 S.Context.getTrivialTypeSourceInfo(
4650 Deduced, TypeLoc.getNameLoc())));
4651 for (unsigned I = 0, C = TypeLoc.getNumArgs(); I != C; ++I)
4652 TemplateArgs.addArgument(TypeLoc.getArgLoc(I));
4653
4654 llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4655 if (S.CheckTemplateArgumentList(Concept, SourceLocation(), TemplateArgs,
4656 /*PartialTemplateArgs=*/false,
4657 SugaredConverted, CanonicalConverted))
4658 return true;
4659 MultiLevelTemplateArgumentList MLTAL(Concept, CanonicalConverted,
4660 /*Final=*/false);
4661 if (S.CheckConstraintSatisfaction(Concept, {Concept->getConstraintExpr()},
4662 MLTAL, TypeLoc.getLocalSourceRange(),
4663 Satisfaction))
4664 return true;
4665 if (!Satisfaction.IsSatisfied) {
4666 std::string Buf;
4667 llvm::raw_string_ostream OS(Buf);
4668 OS << "'" << Concept->getName();
4669 if (TypeLoc.hasExplicitTemplateArgs()) {
4670 printTemplateArgumentList(
4671 OS, Type.getTypeConstraintArguments(), S.getPrintingPolicy(),
4672 Type.getTypeConstraintConcept()->getTemplateParameters());
4673 }
4674 OS << "'";
4675 OS.flush();
4676 S.Diag(TypeLoc.getConceptNameLoc(),
4677 diag::err_placeholder_constraints_not_satisfied)
4678 << Deduced << Buf << TypeLoc.getLocalSourceRange();
4679 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
4680 return true;
4681 }
4682 return false;
4683}
4684
4685/// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
4686///
4687/// Note that this is done even if the initializer is dependent. (This is
4688/// necessary to support partial ordering of templates using 'auto'.)
4689/// A dependent type will be produced when deducing from a dependent type.
4690///
4691/// \param Type the type pattern using the auto type-specifier.
4692/// \param Init the initializer for the variable whose type is to be deduced.
4693/// \param Result if type deduction was successful, this will be set to the
4694/// deduced type.
4695/// \param Info the argument will be updated to provide additional information
4696/// about template argument deduction.
4697/// \param DependentDeduction Set if we should permit deduction in
4698/// dependent cases. This is necessary for template partial ordering with
4699/// 'auto' template parameters. The template parameter depth to be used
4700/// should be specified in the 'Info' parameter.
4701/// \param IgnoreConstraints Set if we should not fail if the deduced type does
4702/// not satisfy the type-constraint in the auto type.
4703Sema::TemplateDeductionResult Sema::DeduceAutoType(TypeLoc Type, Expr *Init,
4704 QualType &Result,
4705 TemplateDeductionInfo &Info,
4706 bool DependentDeduction,
4707 bool IgnoreConstraints) {
4708 assert(DependentDeduction || Info.getDeducedDepth() == 0)(static_cast <bool> (DependentDeduction || Info.getDeducedDepth
() == 0) ? void (0) : __assert_fail ("DependentDeduction || Info.getDeducedDepth() == 0"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 4708, __extension__
__PRETTY_FUNCTION__))
;
4709 if (Init->containsErrors())
4710 return TDK_AlreadyDiagnosed;
4711
4712 const AutoType *AT = Type.getType()->getContainedAutoType();
4713 assert(AT)(static_cast <bool> (AT) ? void (0) : __assert_fail ("AT"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 4713, __extension__
__PRETTY_FUNCTION__))
;
4714
4715 if (Init->getType()->isNonOverloadPlaceholderType() || AT->isDecltypeAuto()) {
4716 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4717 if (NonPlaceholder.isInvalid())
4718 return TDK_AlreadyDiagnosed;
4719 Init = NonPlaceholder.get();
4720 }
4721
4722 DependentAuto DependentResult = {
4723 /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()};
4724
4725 if (!DependentDeduction &&
4726 (Type.getType()->isDependentType() || Init->isTypeDependent() ||
4727 Init->containsUnexpandedParameterPack())) {
4728 Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
4729 assert(!Result.isNull() && "substituting DependentTy can't fail")(static_cast <bool> (!Result.isNull() && "substituting DependentTy can't fail"
) ? void (0) : __assert_fail ("!Result.isNull() && \"substituting DependentTy can't fail\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 4729, __extension__
__PRETTY_FUNCTION__))
;
4730 return TDK_Success;
4731 }
4732
4733 auto *InitList = dyn_cast<InitListExpr>(Init);
4734 if (!getLangOpts().CPlusPlus && InitList) {
4735 Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c);
4736 return TDK_AlreadyDiagnosed;
4737 }
4738
4739 // Deduce type of TemplParam in Func(Init)
4740 SmallVector<DeducedTemplateArgument, 1> Deduced;
4741 Deduced.resize(1);
4742
4743 // If deduction failed, don't diagnose if the initializer is dependent; it
4744 // might acquire a matching type in the instantiation.
4745 auto DeductionFailed = [&](TemplateDeductionResult TDK) {
4746 if (Init->isTypeDependent()) {
4747 Result =
4748 SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
4749 assert(!Result.isNull() && "substituting DependentTy can't fail")(static_cast <bool> (!Result.isNull() && "substituting DependentTy can't fail"
) ? void (0) : __assert_fail ("!Result.isNull() && \"substituting DependentTy can't fail\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 4749, __extension__
__PRETTY_FUNCTION__))
;
4750 return TDK_Success;
4751 }
4752 return TDK;
4753 };
4754
4755 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
4756
4757 QualType DeducedType;
4758 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4759 if (AT->isDecltypeAuto()) {
4760 if (InitList) {
4761 Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list);
4762 return TDK_AlreadyDiagnosed;
4763 }
4764
4765 DeducedType = getDecltypeForExpr(Init);
4766 assert(!DeducedType.isNull())(static_cast <bool> (!DeducedType.isNull()) ? void (0) :
__assert_fail ("!DeducedType.isNull()", "clang/lib/Sema/SemaTemplateDeduction.cpp"
, 4766, __extension__ __PRETTY_FUNCTION__))
;
4767 } else {
4768 LocalInstantiationScope InstScope(*this);
4769
4770 // Build template<class TemplParam> void Func(FuncParam);
4771 SourceLocation Loc = Init->getExprLoc();
4772 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
4773 Context, nullptr, SourceLocation(), Loc, Info.getDeducedDepth(), 0,
4774 nullptr, false, false, false);
4775 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4776 NamedDecl *TemplParamPtr = TemplParam;
4777 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4778 Context, Loc, Loc, TemplParamPtr, Loc, nullptr);
4779
4780 if (InitList) {
4781 // Notionally, we substitute std::initializer_list<T> for 'auto' and
4782 // deduce against that. Such deduction only succeeds if removing
4783 // cv-qualifiers and references results in std::initializer_list<T>.
4784 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
4785 return TDK_Invalid;
4786
4787 SourceRange DeducedFromInitRange;
4788 for (Expr *Init : InitList->inits()) {
4789 // Resolving a core issue: a braced-init-list containing any designators
4790 // is a non-deduced context.
4791 if (isa<DesignatedInitExpr>(Init))
4792 return TDK_Invalid;
4793 if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
4794 *this, TemplateParamsSt.get(), 0, TemplArg, Init, Info, Deduced,
4795 OriginalCallArgs, /*Decomposed=*/true,
4796 /*ArgIdx=*/0, /*TDF=*/0)) {
4797 if (TDK == TDK_Inconsistent) {
4798 Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction)
4799 << Info.FirstArg << Info.SecondArg << DeducedFromInitRange
4800 << Init->getSourceRange();
4801 return DeductionFailed(TDK_AlreadyDiagnosed);
4802 }
4803 return DeductionFailed(TDK);
4804 }
4805
4806 if (DeducedFromInitRange.isInvalid() &&
4807 Deduced[0].getKind() != TemplateArgument::Null)
4808 DeducedFromInitRange = Init->getSourceRange();
4809 }
4810 } else {
4811 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4812 Diag(Loc, diag::err_auto_bitfield);
4813 return TDK_AlreadyDiagnosed;
4814 }
4815 QualType FuncParam =
4816 SubstituteDeducedTypeTransform(*this, TemplArg).Apply(Type);
4817 assert(!FuncParam.isNull() &&(static_cast <bool> (!FuncParam.isNull() && "substituting template parameter for 'auto' failed"
) ? void (0) : __assert_fail ("!FuncParam.isNull() && \"substituting template parameter for 'auto' failed\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 4818, __extension__
__PRETTY_FUNCTION__))
4818 "substituting template parameter for 'auto' failed")(static_cast <bool> (!FuncParam.isNull() && "substituting template parameter for 'auto' failed"
) ? void (0) : __assert_fail ("!FuncParam.isNull() && \"substituting template parameter for 'auto' failed\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 4818, __extension__
__PRETTY_FUNCTION__))
;
4819 if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
4820 *this, TemplateParamsSt.get(), 0, FuncParam, Init, Info, Deduced,
4821 OriginalCallArgs, /*Decomposed=*/false, /*ArgIdx=*/0, /*TDF=*/0))
4822 return DeductionFailed(TDK);
4823 }
4824
4825 // Could be null if somehow 'auto' appears in a non-deduced context.
4826 if (Deduced[0].getKind() != TemplateArgument::Type)
4827 return DeductionFailed(TDK_Incomplete);
4828 DeducedType = Deduced[0].getAsType();
4829
4830 if (InitList) {
4831 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4832 if (DeducedType.isNull())
4833 return TDK_AlreadyDiagnosed;
4834 }
4835 }
4836
4837 if (!Result.isNull()) {
4838 if (!Context.hasSameType(DeducedType, Result)) {
4839 Info.FirstArg = Result;
4840 Info.SecondArg = DeducedType;
4841 return DeductionFailed(TDK_Inconsistent);
4842 }
4843 DeducedType = Context.getCommonSugaredType(Result, DeducedType);
4844 }
4845
4846 if (AT->isConstrained() && !IgnoreConstraints &&
4847 CheckDeducedPlaceholderConstraints(
4848 *this, *AT, Type.getContainedAutoTypeLoc(), DeducedType))
4849 return TDK_AlreadyDiagnosed;
4850
4851 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
4852 if (Result.isNull())
4853 return TDK_AlreadyDiagnosed;
4854
4855 // Check that the deduced argument type is compatible with the original
4856 // argument type per C++ [temp.deduct.call]p4.
4857 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
4858 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
4859 assert((bool)InitList == OriginalArg.DecomposedParam &&(static_cast <bool> ((bool)InitList == OriginalArg.DecomposedParam
&& "decomposed non-init-list in auto deduction?") ? void
(0) : __assert_fail ("(bool)InitList == OriginalArg.DecomposedParam && \"decomposed non-init-list in auto deduction?\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 4860, __extension__
__PRETTY_FUNCTION__))
4860 "decomposed non-init-list in auto deduction?")(static_cast <bool> ((bool)InitList == OriginalArg.DecomposedParam
&& "decomposed non-init-list in auto deduction?") ? void
(0) : __assert_fail ("(bool)InitList == OriginalArg.DecomposedParam && \"decomposed non-init-list in auto deduction?\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 4860, __extension__
__PRETTY_FUNCTION__))
;
4861 if (auto TDK =
4862 CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA)) {
4863 Result = QualType();
4864 return DeductionFailed(TDK);
4865 }
4866 }
4867
4868 return TDK_Success;
4869}
4870
4871QualType Sema::SubstAutoType(QualType TypeWithAuto,
4872 QualType TypeToReplaceAuto) {
4873 assert(TypeToReplaceAuto != Context.DependentTy)(static_cast <bool> (TypeToReplaceAuto != Context.DependentTy
) ? void (0) : __assert_fail ("TypeToReplaceAuto != Context.DependentTy"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 4873, __extension__
__PRETTY_FUNCTION__))
;
4874 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
4875 .TransformType(TypeWithAuto);
4876}
4877
4878TypeSourceInfo *Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4879 QualType TypeToReplaceAuto) {
4880 assert(TypeToReplaceAuto != Context.DependentTy)(static_cast <bool> (TypeToReplaceAuto != Context.DependentTy
) ? void (0) : __assert_fail ("TypeToReplaceAuto != Context.DependentTy"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 4880, __extension__
__PRETTY_FUNCTION__))
;
4881 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
4882 .TransformType(TypeWithAuto);
4883}
4884
4885QualType Sema::SubstAutoTypeDependent(QualType TypeWithAuto) {
4886 return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
4887 .TransformType(TypeWithAuto);
4888}
4889
4890TypeSourceInfo *
4891Sema::SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto) {
4892 return SubstituteDeducedTypeTransform(*this, DependentAuto{false})
4893 .TransformType(TypeWithAuto);
4894}
4895
4896QualType Sema::ReplaceAutoType(QualType TypeWithAuto,
4897 QualType TypeToReplaceAuto) {
4898 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
4899 /*UseTypeSugar*/ false)
4900 .TransformType(TypeWithAuto);
4901}
4902
4903TypeSourceInfo *Sema::ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4904 QualType TypeToReplaceAuto) {
4905 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
4906 /*UseTypeSugar*/ false)
4907 .TransformType(TypeWithAuto);
4908}
4909
4910void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4911 if (isa<InitListExpr>(Init))
4912 Diag(VDecl->getLocation(),
4913 VDecl->isInitCapture()
4914 ? diag::err_init_capture_deduction_failure_from_init_list
4915 : diag::err_auto_var_deduction_failure_from_init_list)
4916 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4917 else
4918 Diag(VDecl->getLocation(),
4919 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4920 : diag::err_auto_var_deduction_failure)
4921 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4922 << Init->getSourceRange();
4923}
4924
4925bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4926 bool Diagnose) {
4927 assert(FD->getReturnType()->isUndeducedType())(static_cast <bool> (FD->getReturnType()->isUndeducedType
()) ? void (0) : __assert_fail ("FD->getReturnType()->isUndeducedType()"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 4927, __extension__
__PRETTY_FUNCTION__))
;
4928
4929 // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
4930 // within the return type from the call operator's type.
4931 if (isLambdaConversionOperator(FD)) {
4932 CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
4933 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
4934
4935 // For a generic lambda, instantiate the call operator if needed.
4936 if (auto *Args = FD->getTemplateSpecializationArgs()) {
4937 CallOp = InstantiateFunctionDeclaration(
4938 CallOp->getDescribedFunctionTemplate(), Args, Loc);
4939 if (!CallOp || CallOp->isInvalidDecl())
4940 return true;
4941
4942 // We might need to deduce the return type by instantiating the definition
4943 // of the operator() function.
4944 if (CallOp->getReturnType()->isUndeducedType()) {
4945 runWithSufficientStackSpace(Loc, [&] {
4946 InstantiateFunctionDefinition(Loc, CallOp);
4947 });
4948 }
4949 }
4950
4951 if (CallOp->isInvalidDecl())
4952 return true;
4953 assert(!CallOp->getReturnType()->isUndeducedType() &&(static_cast <bool> (!CallOp->getReturnType()->isUndeducedType
() && "failed to deduce lambda return type") ? void (
0) : __assert_fail ("!CallOp->getReturnType()->isUndeducedType() && \"failed to deduce lambda return type\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 4954, __extension__
__PRETTY_FUNCTION__))
4954 "failed to deduce lambda return type")(static_cast <bool> (!CallOp->getReturnType()->isUndeducedType
() && "failed to deduce lambda return type") ? void (
0) : __assert_fail ("!CallOp->getReturnType()->isUndeducedType() && \"failed to deduce lambda return type\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 4954, __extension__
__PRETTY_FUNCTION__))
;
4955
4956 // Build the new return type from scratch.
4957 CallingConv RetTyCC = FD->getReturnType()
4958 ->getPointeeType()
4959 ->castAs<FunctionType>()
4960 ->getCallConv();
4961 QualType RetType = getLambdaConversionFunctionResultType(
4962 CallOp->getType()->castAs<FunctionProtoType>(), RetTyCC);
4963 if (FD->getReturnType()->getAs<PointerType>())
4964 RetType = Context.getPointerType(RetType);
4965 else {
4966 assert(FD->getReturnType()->getAs<BlockPointerType>())(static_cast <bool> (FD->getReturnType()->getAs<
BlockPointerType>()) ? void (0) : __assert_fail ("FD->getReturnType()->getAs<BlockPointerType>()"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 4966, __extension__
__PRETTY_FUNCTION__))
;
4967 RetType = Context.getBlockPointerType(RetType);
4968 }
4969 Context.adjustDeducedFunctionResultType(FD, RetType);
4970 return false;
4971 }
4972
4973 if (FD->getTemplateInstantiationPattern()) {
4974 runWithSufficientStackSpace(Loc, [&] {
4975 InstantiateFunctionDefinition(Loc, FD);
4976 });
4977 }
4978
4979 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
4980 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4981 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4982 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4983 }
4984
4985 return StillUndeduced;
4986}
4987
4988/// If this is a non-static member function,
4989static void
4990AddImplicitObjectParameterType(ASTContext &Context,
4991 CXXMethodDecl *Method,
4992 SmallVectorImpl<QualType> &ArgTypes) {
4993 // C++11 [temp.func.order]p3:
4994 // [...] The new parameter is of type "reference to cv A," where cv are
4995 // the cv-qualifiers of the function template (if any) and A is
4996 // the class of which the function template is a member.
4997 //
4998 // The standard doesn't say explicitly, but we pick the appropriate kind of
4999 // reference type based on [over.match.funcs]p4.
5000 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
5001 ArgTy = Context.getQualifiedType(ArgTy, Method->getMethodQualifiers());
5002 if (Method->getRefQualifier() == RQ_RValue)
5003 ArgTy = Context.getRValueReferenceType(ArgTy);
5004 else
5005 ArgTy = Context.getLValueReferenceType(ArgTy);
5006 ArgTypes.push_back(ArgTy);
5007}
5008
5009/// Determine whether the function template \p FT1 is at least as
5010/// specialized as \p FT2.
5011static bool isAtLeastAsSpecializedAs(Sema &S,
5012 SourceLocation Loc,
5013 FunctionTemplateDecl *FT1,
5014 FunctionTemplateDecl *FT2,
5015 TemplatePartialOrderingContext TPOC,
5016 unsigned NumCallArguments1,
5017 bool Reversed) {
5018 assert(!Reversed || TPOC == TPOC_Call)(static_cast <bool> (!Reversed || TPOC == TPOC_Call) ? void
(0) : __assert_fail ("!Reversed || TPOC == TPOC_Call", "clang/lib/Sema/SemaTemplateDeduction.cpp"
, 5018, __extension__ __PRETTY_FUNCTION__))
;
5019
5020 FunctionDecl *FD1 = FT1->getTemplatedDecl();
5021 FunctionDecl *FD2 = FT2->getTemplatedDecl();
5022 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
5023 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
5024
5025 assert(Proto1 && Proto2 && "Function templates must have prototypes")(static_cast <bool> (Proto1 && Proto2 &&
"Function templates must have prototypes") ? void (0) : __assert_fail
("Proto1 && Proto2 && \"Function templates must have prototypes\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 5025, __extension__
__PRETTY_FUNCTION__))
;
5026 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
5027 SmallVector<DeducedTemplateArgument, 4> Deduced;
5028 Deduced.resize(TemplateParams->size());
5029
5030 // C++0x [temp.deduct.partial]p3:
5031 // The types used to determine the ordering depend on the context in which
5032 // the partial ordering is done:
5033 TemplateDeductionInfo Info(Loc);
5034 SmallVector<QualType, 4> Args2;
5035 switch (TPOC) {
5036 case TPOC_Call: {
5037 // - In the context of a function call, the function parameter types are
5038 // used.
5039 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
5040 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
5041
5042 // C++11 [temp.func.order]p3:
5043 // [...] If only one of the function templates is a non-static
5044 // member, that function template is considered to have a new
5045 // first parameter inserted in its function parameter list. The
5046 // new parameter is of type "reference to cv A," where cv are
5047 // the cv-qualifiers of the function template (if any) and A is
5048 // the class of which the function template is a member.
5049 //
5050 // Note that we interpret this to mean "if one of the function
5051 // templates is a non-static member and the other is a non-member";
5052 // otherwise, the ordering rules for static functions against non-static
5053 // functions don't make any sense.
5054 //
5055 // C++98/03 doesn't have this provision but we've extended DR532 to cover
5056 // it as wording was broken prior to it.
5057 SmallVector<QualType, 4> Args1;
5058
5059 unsigned NumComparedArguments = NumCallArguments1;
5060
5061 if (!Method2 && Method1 && !Method1->isStatic()) {
5062 // Compare 'this' from Method1 against first parameter from Method2.
5063 AddImplicitObjectParameterType(S.Context, Method1, Args1);
5064 ++NumComparedArguments;
5065 } else if (!Method1 && Method2 && !Method2->isStatic()) {
5066 // Compare 'this' from Method2 against first parameter from Method1.
5067 AddImplicitObjectParameterType(S.Context, Method2, Args2);
5068 } else if (Method1 && Method2 && Reversed) {
5069 // Compare 'this' from Method1 against second parameter from Method2
5070 // and 'this' from Method2 against second parameter from Method1.
5071 AddImplicitObjectParameterType(S.Context, Method1, Args1);
5072 AddImplicitObjectParameterType(S.Context, Method2, Args2);
5073 ++NumComparedArguments;
5074 }
5075
5076 Args1.insert(Args1.end(), Proto1->param_type_begin(),
5077 Proto1->param_type_end());
5078 Args2.insert(Args2.end(), Proto2->param_type_begin(),
5079 Proto2->param_type_end());
5080
5081 // C++ [temp.func.order]p5:
5082 // The presence of unused ellipsis and default arguments has no effect on
5083 // the partial ordering of function templates.
5084 if (Args1.size() > NumComparedArguments)
5085 Args1.resize(NumComparedArguments);
5086 if (Args2.size() > NumComparedArguments)
5087 Args2.resize(NumComparedArguments);
5088 if (Reversed)
5089 std::reverse(Args2.begin(), Args2.end());
5090
5091 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
5092 Args1.data(), Args1.size(), Info, Deduced,
5093 TDF_None, /*PartialOrdering=*/true))
5094 return false;
5095
5096 break;
5097 }
5098
5099 case TPOC_Conversion:
5100 // - In the context of a call to a conversion operator, the return types
5101 // of the conversion function templates are used.
5102 if (DeduceTemplateArgumentsByTypeMatch(
5103 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
5104 Info, Deduced, TDF_None,
5105 /*PartialOrdering=*/true))
5106 return false;
5107 break;
5108
5109 case TPOC_Other:
5110 // - In other contexts (14.6.6.2) the function template's function type
5111 // is used.
5112 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
5113 FD2->getType(), FD1->getType(),
5114 Info, Deduced, TDF_None,
5115 /*PartialOrdering=*/true))
5116 return false;
5117 break;
5118 }
5119
5120 // C++0x [temp.deduct.partial]p11:
5121 // In most cases, all template parameters must have values in order for
5122 // deduction to succeed, but for partial ordering purposes a template
5123 // parameter may remain without a value provided it is not used in the
5124 // types being used for partial ordering. [ Note: a template parameter used
5125 // in a non-deduced context is considered used. -end note]
5126 unsigned ArgIdx = 0, NumArgs = Deduced.size();
5127 for (; ArgIdx != NumArgs; ++ArgIdx)
5128 if (Deduced[ArgIdx].isNull())
5129 break;
5130
5131 // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
5132 // to substitute the deduced arguments back into the template and check that
5133 // we get the right type.
5134
5135 if (ArgIdx == NumArgs) {
5136 // All template arguments were deduced. FT1 is at least as specialized
5137 // as FT2.
5138 return true;
5139 }
5140
5141 // Figure out which template parameters were used.
5142 llvm::SmallBitVector UsedParameters(TemplateParams->size());
5143 switch (TPOC) {
5144 case TPOC_Call:
5145 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
5146 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
5147 TemplateParams->getDepth(),
5148 UsedParameters);
5149 break;
5150
5151 case TPOC_Conversion:
5152 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
5153 TemplateParams->getDepth(), UsedParameters);
5154 break;
5155
5156 case TPOC_Other:
5157 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
5158 TemplateParams->getDepth(),
5159 UsedParameters);
5160 break;
5161 }
5162
5163 for (; ArgIdx != NumArgs; ++ArgIdx)
5164 // If this argument had no value deduced but was used in one of the types
5165 // used for partial ordering, then deduction fails.
5166 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
5167 return false;
5168
5169 return true;
5170}
5171
5172/// Returns the more specialized function template according
5173/// to the rules of function template partial ordering (C++ [temp.func.order]).
5174///
5175/// \param FT1 the first function template
5176///
5177/// \param FT2 the second function template
5178///
5179/// \param TPOC the context in which we are performing partial ordering of
5180/// function templates.
5181///
5182/// \param NumCallArguments1 The number of arguments in the call to FT1, used
5183/// only when \c TPOC is \c TPOC_Call.
5184///
5185/// \param NumCallArguments2 The number of arguments in the call to FT2, used
5186/// only when \c TPOC is \c TPOC_Call.
5187///
5188/// \param Reversed If \c true, exactly one of FT1 and FT2 is an overload
5189/// candidate with a reversed parameter order. In this case, the corresponding
5190/// P/A pairs between FT1 and FT2 are reversed.
5191///
5192/// \returns the more specialized function template. If neither
5193/// template is more specialized, returns NULL.
5194FunctionTemplateDecl *Sema::getMoreSpecializedTemplate(
5195 FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
5196 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
5197 unsigned NumCallArguments2, bool Reversed) {
5198
5199 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
5200 NumCallArguments1, Reversed);
5201 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
5202 NumCallArguments2, Reversed);
5203
5204 // C++ [temp.deduct.partial]p10:
5205 // F is more specialized than G if F is at least as specialized as G and G
5206 // is not at least as specialized as F.
5207 if (Better1 != Better2) // We have a clear winner
5208 return Better1 ? FT1 : FT2;
5209
5210 if (!Better1 && !Better2) // Neither is better than the other
5211 return nullptr;
5212
5213 // C++ [temp.deduct.partial]p11:
5214 // ... and if G has a trailing function parameter pack for which F does not
5215 // have a corresponding parameter, and if F does not have a trailing
5216 // function parameter pack, then F is more specialized than G.
5217 FunctionDecl *FD1 = FT1->getTemplatedDecl();
5218 FunctionDecl *FD2 = FT2->getTemplatedDecl();
5219 unsigned NumParams1 = FD1->getNumParams();
5220 unsigned NumParams2 = FD2->getNumParams();
5221 bool Variadic1 = NumParams1 && FD1->parameters().back()->isParameterPack();
5222 bool Variadic2 = NumParams2 && FD2->parameters().back()->isParameterPack();
5223 if (Variadic1 != Variadic2) {
5224 if (Variadic1 && NumParams1 > NumParams2)
5225 return FT2;
5226 if (Variadic2 && NumParams2 > NumParams1)
5227 return FT1;
5228 }
5229
5230 // This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
5231 // there is no wording or even resolution for this issue.
5232 for (int i = 0, e = std::min(NumParams1, NumParams2); i < e; ++i) {
5233 QualType T1 = FD1->getParamDecl(i)->getType().getCanonicalType();
5234 QualType T2 = FD2->getParamDecl(i)->getType().getCanonicalType();
5235 auto *TST1 = dyn_cast<TemplateSpecializationType>(T1);
5236 auto *TST2 = dyn_cast<TemplateSpecializationType>(T2);
5237 if (!TST1 || !TST2)
5238 continue;
5239 const TemplateArgument &TA1 = TST1->template_arguments().back();
5240 if (TA1.getKind() == TemplateArgument::Pack) {
5241 assert(TST1->template_arguments().size() ==(static_cast <bool> (TST1->template_arguments().size
() == TST2->template_arguments().size()) ? void (0) : __assert_fail
("TST1->template_arguments().size() == TST2->template_arguments().size()"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 5242, __extension__
__PRETTY_FUNCTION__))
5242 TST2->template_arguments().size())(static_cast <bool> (TST1->template_arguments().size
() == TST2->template_arguments().size()) ? void (0) : __assert_fail
("TST1->template_arguments().size() == TST2->template_arguments().size()"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 5242, __extension__
__PRETTY_FUNCTION__))
;
5243 const TemplateArgument &TA2 = TST2->template_arguments().back();
5244 assert(TA2.getKind() == TemplateArgument::Pack)(static_cast <bool> (TA2.getKind() == TemplateArgument::
Pack) ? void (0) : __assert_fail ("TA2.getKind() == TemplateArgument::Pack"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 5244, __extension__
__PRETTY_FUNCTION__))
;
5245 unsigned PackSize1 = TA1.pack_size();
5246 unsigned PackSize2 = TA2.pack_size();
5247 bool IsPackExpansion1 =
5248 PackSize1 && TA1.pack_elements().back().isPackExpansion();
5249 bool IsPackExpansion2 =
5250 PackSize2 && TA2.pack_elements().back().isPackExpansion();
5251 if (PackSize1 != PackSize2 && IsPackExpansion1 != IsPackExpansion2) {
5252 if (PackSize1 > PackSize2 && IsPackExpansion1)
5253 return FT2;
5254 if (PackSize1 < PackSize2 && IsPackExpansion2)
5255 return FT1;
5256 }
5257 }
5258 }
5259
5260 if (!Context.getLangOpts().CPlusPlus20)
5261 return nullptr;
5262
5263 // Match GCC on not implementing [temp.func.order]p6.2.1.
5264
5265 // C++20 [temp.func.order]p6:
5266 // If deduction against the other template succeeds for both transformed
5267 // templates, constraints can be considered as follows:
5268
5269 // C++20 [temp.func.order]p6.1:
5270 // If their template-parameter-lists (possibly including template-parameters
5271 // invented for an abbreviated function template ([dcl.fct])) or function
5272 // parameter lists differ in length, neither template is more specialized
5273 // than the other.
5274 TemplateParameterList *TPL1 = FT1->getTemplateParameters();
5275 TemplateParameterList *TPL2 = FT2->getTemplateParameters();
5276 if (TPL1->size() != TPL2->size() || NumParams1 != NumParams2)
5277 return nullptr;
5278
5279 // C++20 [temp.func.order]p6.2.2:
5280 // Otherwise, if the corresponding template-parameters of the
5281 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
5282 // function parameters that positionally correspond between the two
5283 // templates are not of the same type, neither template is more specialized
5284 // than the other.
5285 if (!TemplateParameterListsAreEqual(
5286 TPL1, TPL2, false, Sema::TPL_TemplateMatch, SourceLocation(), true))
5287 return nullptr;
5288
5289 for (unsigned i = 0; i < NumParams1; ++i)
5290 if (!Context.hasSameType(FD1->getParamDecl(i)->getType(),
5291 FD2->getParamDecl(i)->getType()))
5292 return nullptr;
5293
5294 // C++20 [temp.func.order]p6.3:
5295 // Otherwise, if the context in which the partial ordering is done is
5296 // that of a call to a conversion function and the return types of the
5297 // templates are not the same, then neither template is more specialized
5298 // than the other.
5299 if (TPOC == TPOC_Conversion &&
5300 !Context.hasSameType(FD1->getReturnType(), FD2->getReturnType()))
5301 return nullptr;
5302
5303 llvm::SmallVector<const Expr *, 3> AC1, AC2;
5304 FT1->getAssociatedConstraints(AC1);
5305 FT2->getAssociatedConstraints(AC2);
5306 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
5307 if (IsAtLeastAsConstrained(FT1, AC1, FT2, AC2, AtLeastAsConstrained1))
5308 return nullptr;
5309 if (IsAtLeastAsConstrained(FT2, AC2, FT1, AC1, AtLeastAsConstrained2))
5310 return nullptr;
5311 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
5312 return nullptr;
5313 return AtLeastAsConstrained1 ? FT1 : FT2;
5314}
5315
5316/// Determine if the two templates are equivalent.
5317static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
5318 if (T1 == T2)
5319 return true;
5320
5321 if (!T1 || !T2)
5322 return false;
5323
5324 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
5325}
5326
5327/// Retrieve the most specialized of the given function template
5328/// specializations.
5329///
5330/// \param SpecBegin the start iterator of the function template
5331/// specializations that we will be comparing.
5332///
5333/// \param SpecEnd the end iterator of the function template
5334/// specializations, paired with \p SpecBegin.
5335///
5336/// \param Loc the location where the ambiguity or no-specializations
5337/// diagnostic should occur.
5338///
5339/// \param NoneDiag partial diagnostic used to diagnose cases where there are
5340/// no matching candidates.
5341///
5342/// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
5343/// occurs.
5344///
5345/// \param CandidateDiag partial diagnostic used for each function template
5346/// specialization that is a candidate in the ambiguous ordering. One parameter
5347/// in this diagnostic should be unbound, which will correspond to the string
5348/// describing the template arguments for the function template specialization.
5349///
5350/// \returns the most specialized function template specialization, if
5351/// found. Otherwise, returns SpecEnd.
5352UnresolvedSetIterator Sema::getMostSpecialized(
5353 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
5354 TemplateSpecCandidateSet &FailedCandidates,
5355 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
5356 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
5357 bool Complain, QualType TargetType) {
5358 if (SpecBegin == SpecEnd) {
5359 if (Complain) {
5360 Diag(Loc, NoneDiag);
5361 FailedCandidates.NoteCandidates(*this, Loc);
5362 }
5363 return SpecEnd;
5364 }
5365
5366 if (SpecBegin + 1 == SpecEnd)
5367 return SpecBegin;
5368
5369 // Find the function template that is better than all of the templates it
5370 // has been compared to.
5371 UnresolvedSetIterator Best = SpecBegin;
5372 FunctionTemplateDecl *BestTemplate
5373 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
5374 assert(BestTemplate && "Not a function template specialization?")(static_cast <bool> (BestTemplate && "Not a function template specialization?"
) ? void (0) : __assert_fail ("BestTemplate && \"Not a function template specialization?\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 5374, __extension__
__PRETTY_FUNCTION__))
;
5375 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
5376 FunctionTemplateDecl *Challenger
5377 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
5378 assert(Challenger && "Not a function template specialization?")(static_cast <bool> (Challenger && "Not a function template specialization?"
) ? void (0) : __assert_fail ("Challenger && \"Not a function template specialization?\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 5378, __extension__
__PRETTY_FUNCTION__))
;
5379 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
5380 Loc, TPOC_Other, 0, 0),
5381 Challenger)) {
5382 Best = I;
5383 BestTemplate = Challenger;
5384 }
5385 }
5386
5387 // Make sure that the "best" function template is more specialized than all
5388 // of the others.
5389 bool Ambiguous = false;
5390 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
5391 FunctionTemplateDecl *Challenger
5392 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
5393 if (I != Best &&
5394 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
5395 Loc, TPOC_Other, 0, 0),
5396 BestTemplate)) {
5397 Ambiguous = true;
5398 break;
5399 }
5400 }
5401
5402 if (!Ambiguous) {
5403 // We found an answer. Return it.
5404 return Best;
5405 }
5406
5407 // Diagnose the ambiguity.
5408 if (Complain) {
5409 Diag(Loc, AmbigDiag);
5410
5411 // FIXME: Can we order the candidates in some sane way?
5412 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
5413 PartialDiagnostic PD = CandidateDiag;
5414 const auto *FD = cast<FunctionDecl>(*I);
5415 PD << FD << getTemplateArgumentBindingsText(
5416 FD->getPrimaryTemplate()->getTemplateParameters(),
5417 *FD->getTemplateSpecializationArgs());
5418 if (!TargetType.isNull())
5419 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
5420 Diag((*I)->getLocation(), PD);
5421 }
5422 }
5423
5424 return SpecEnd;
5425}
5426
5427/// Determine whether one partial specialization, P1, is at least as
5428/// specialized than another, P2.
5429///
5430/// \tparam TemplateLikeDecl The kind of P2, which must be a
5431/// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
5432/// \param T1 The injected-class-name of P1 (faked for a variable template).
5433/// \param T2 The injected-class-name of P2 (faked for a variable template).
5434template<typename TemplateLikeDecl>
5435static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
5436 TemplateLikeDecl *P2,
5437 TemplateDeductionInfo &Info) {
5438 // C++ [temp.class.order]p1:
5439 // For two class template partial specializations, the first is at least as
5440 // specialized as the second if, given the following rewrite to two
5441 // function templates, the first function template is at least as
5442 // specialized as the second according to the ordering rules for function
5443 // templates (14.6.6.2):
5444 // - the first function template has the same template parameters as the
5445 // first partial specialization and has a single function parameter
5446 // whose type is a class template specialization with the template
5447 // arguments of the first partial specialization, and
5448 // - the second function template has the same template parameters as the
5449 // second partial specialization and has a single function parameter
5450 // whose type is a class template specialization with the template
5451 // arguments of the second partial specialization.
5452 //
5453 // Rather than synthesize function templates, we merely perform the
5454 // equivalent partial ordering by performing deduction directly on
5455 // the template arguments of the class template partial
5456 // specializations. This computation is slightly simpler than the
5457 // general problem of function template partial ordering, because
5458 // class template partial specializations are more constrained. We
5459 // know that every template parameter is deducible from the class
5460 // template partial specialization's template arguments, for
5461 // example.
5462 SmallVector<DeducedTemplateArgument, 4> Deduced;
5463
5464 // Determine whether P1 is at least as specialized as P2.
5465 Deduced.resize(P2->getTemplateParameters()->size());
5466 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
5467 T2, T1, Info, Deduced, TDF_None,
5468 /*PartialOrdering=*/true))
5469 return false;
5470
5471 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
5472 Deduced.end());
5473 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
5474 Info);
5475 if (Inst.isInvalid())
5476 return false;
5477
5478 const auto *TST1 = cast<TemplateSpecializationType>(T1);
5479 bool AtLeastAsSpecialized;
5480 S.runWithSufficientStackSpace(Info.getLocation(), [&] {
5481 AtLeastAsSpecialized = !FinishTemplateArgumentDeduction(
5482 S, P2, /*IsPartialOrdering=*/true,
5483 TemplateArgumentList(TemplateArgumentList::OnStack,
5484 TST1->template_arguments()),
5485 Deduced, Info);
5486 });
5487 return AtLeastAsSpecialized;
5488}
5489
5490namespace {
5491// A dummy class to return nullptr instead of P2 when performing "more
5492// specialized than primary" check.
5493struct GetP2 {
5494 template <typename T1, typename T2,
5495 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
5496 T2 *operator()(T1 *, T2 *P2) {
5497 return P2;
5498 }
5499 template <typename T1, typename T2,
5500 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
5501 T1 *operator()(T1 *, T2 *) {
5502 return nullptr;
5503 }
5504};
5505
5506// The assumption is that two template argument lists have the same size.
5507struct TemplateArgumentListAreEqual {
5508 ASTContext &Ctx;
5509 TemplateArgumentListAreEqual(ASTContext &Ctx) : Ctx(Ctx) {}
5510
5511 template <typename T1, typename T2,
5512 std::enable_if_t<std::is_same_v<T1, T2>, bool> = true>
5513 bool operator()(T1 *PS1, T2 *PS2) {
5514 ArrayRef<TemplateArgument> Args1 = PS1->getTemplateArgs().asArray(),
5515 Args2 = PS2->getTemplateArgs().asArray();
5516
5517 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
5518 // We use profile, instead of structural comparison of the arguments,
5519 // because canonicalization can't do the right thing for dependent
5520 // expressions.
5521 llvm::FoldingSetNodeID IDA, IDB;
5522 Args1[I].Profile(IDA, Ctx);
5523 Args2[I].Profile(IDB, Ctx);
5524 if (IDA != IDB)
5525 return false;
5526 }
5527 return true;
5528 }
5529
5530 template <typename T1, typename T2,
5531 std::enable_if_t<!std::is_same_v<T1, T2>, bool> = true>
5532 bool operator()(T1 *Spec, T2 *Primary) {
5533 ArrayRef<TemplateArgument> Args1 = Spec->getTemplateArgs().asArray(),
5534 Args2 = Primary->getInjectedTemplateArgs();
5535
5536 for (unsigned I = 0, E = Args1.size(); I < E; ++I) {
5537 // We use profile, instead of structural comparison of the arguments,
5538 // because canonicalization can't do the right thing for dependent
5539 // expressions.
5540 llvm::FoldingSetNodeID IDA, IDB;
5541 Args1[I].Profile(IDA, Ctx);
5542 // Unlike the specialization arguments, the injected arguments are not
5543 // always canonical.
5544 Ctx.getCanonicalTemplateArgument(Args2[I]).Profile(IDB, Ctx);
5545 if (IDA != IDB)
5546 return false;
5547 }
5548 return true;
5549 }
5550};
5551} // namespace
5552
5553/// Returns the more specialized template specialization between T1/P1 and
5554/// T2/P2.
5555/// - If IsMoreSpecialThanPrimaryCheck is true, T1/P1 is the partial
5556/// specialization and T2/P2 is the primary template.
5557/// - otherwise, both T1/P1 and T2/P2 are the partial specialization.
5558///
5559/// \param T1 the type of the first template partial specialization
5560///
5561/// \param T2 if IsMoreSpecialThanPrimaryCheck is true, the type of the second
5562/// template partial specialization; otherwise, the type of the
5563/// primary template.
5564///
5565/// \param P1 the first template partial specialization
5566///
5567/// \param P2 if IsMoreSpecialThanPrimaryCheck is true, the second template
5568/// partial specialization; otherwise, the primary template.
5569///
5570/// \returns - If IsMoreSpecialThanPrimaryCheck is true, returns P1 if P1 is
5571/// more specialized, returns nullptr if P1 is not more specialized.
5572/// - otherwise, returns the more specialized template partial
5573/// specialization. If neither partial specialization is more
5574/// specialized, returns NULL.
5575template <typename TemplateLikeDecl, typename PrimaryDel>
5576static TemplateLikeDecl *
5577getMoreSpecialized(Sema &S, QualType T1, QualType T2, TemplateLikeDecl *P1,
5578 PrimaryDel *P2, TemplateDeductionInfo &Info) {
5579 constexpr bool IsMoreSpecialThanPrimaryCheck =
5580 !std::is_same_v<TemplateLikeDecl, PrimaryDel>;
5581
5582 bool Better1 = isAtLeastAsSpecializedAs(S, T1, T2, P2, Info);
5583 if (IsMoreSpecialThanPrimaryCheck && !Better1)
5584 return nullptr;
5585
5586 bool Better2 = isAtLeastAsSpecializedAs(S, T2, T1, P1, Info);
5587 if (IsMoreSpecialThanPrimaryCheck && !Better2)
5588 return P1;
5589
5590 // C++ [temp.deduct.partial]p10:
5591 // F is more specialized than G if F is at least as specialized as G and G
5592 // is not at least as specialized as F.
5593 if (Better1 != Better2) // We have a clear winner
5594 return Better1 ? P1 : GetP2()(P1, P2);
5595
5596 if (!Better1 && !Better2)
5597 return nullptr;
5598
5599 // This a speculative fix for CWG1432 (Similar to the fix for CWG1395) that
5600 // there is no wording or even resolution for this issue.
5601 auto *TST1 = cast<TemplateSpecializationType>(T1);
5602 auto *TST2 = cast<TemplateSpecializationType>(T2);
5603 const TemplateArgument &TA1 = TST1->template_arguments().back();
5604 if (TA1.getKind() == TemplateArgument::Pack) {
5605 assert(TST1->template_arguments().size() ==(static_cast <bool> (TST1->template_arguments().size
() == TST2->template_arguments().size()) ? void (0) : __assert_fail
("TST1->template_arguments().size() == TST2->template_arguments().size()"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 5606, __extension__
__PRETTY_FUNCTION__))
5606 TST2->template_arguments().size())(static_cast <bool> (TST1->template_arguments().size
() == TST2->template_arguments().size()) ? void (0) : __assert_fail
("TST1->template_arguments().size() == TST2->template_arguments().size()"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 5606, __extension__
__PRETTY_FUNCTION__))
;
5607 const TemplateArgument &TA2 = TST2->template_arguments().back();
5608 assert(TA2.getKind() == TemplateArgument::Pack)(static_cast <bool> (TA2.getKind() == TemplateArgument::
Pack) ? void (0) : __assert_fail ("TA2.getKind() == TemplateArgument::Pack"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 5608, __extension__
__PRETTY_FUNCTION__))
;
5609 unsigned PackSize1 = TA1.pack_size();
5610 unsigned PackSize2 = TA2.pack_size();
5611 bool IsPackExpansion1 =
5612 PackSize1 && TA1.pack_elements().back().isPackExpansion();
5613 bool IsPackExpansion2 =
5614 PackSize2 && TA2.pack_elements().back().isPackExpansion();
5615 if (PackSize1 != PackSize2 && IsPackExpansion1 != IsPackExpansion2) {
5616 if (PackSize1 > PackSize2 && IsPackExpansion1)
5617 return GetP2()(P1, P2);
5618 if (PackSize1 < PackSize2 && IsPackExpansion2)
5619 return P1;
5620 }
5621 }
5622
5623 if (!S.Context.getLangOpts().CPlusPlus20)
5624 return nullptr;
5625
5626 // Match GCC on not implementing [temp.func.order]p6.2.1.
5627
5628 // C++20 [temp.func.order]p6:
5629 // If deduction against the other template succeeds for both transformed
5630 // templates, constraints can be considered as follows:
5631
5632 TemplateParameterList *TPL1 = P1->getTemplateParameters();
5633 TemplateParameterList *TPL2 = P2->getTemplateParameters();
5634 if (TPL1->size() != TPL2->size())
5635 return nullptr;
5636
5637 // C++20 [temp.func.order]p6.2.2:
5638 // Otherwise, if the corresponding template-parameters of the
5639 // template-parameter-lists are not equivalent ([temp.over.link]) or if the
5640 // function parameters that positionally correspond between the two
5641 // templates are not of the same type, neither template is more specialized
5642 // than the other.
5643 if (!S.TemplateParameterListsAreEqual(
5644 TPL1, TPL2, false, Sema::TPL_TemplateMatch, SourceLocation(), true))
5645 return nullptr;
5646
5647 if (!TemplateArgumentListAreEqual(S.getASTContext())(P1, P2))
5648 return nullptr;
5649
5650 llvm::SmallVector<const Expr *, 3> AC1, AC2;
5651 P1->getAssociatedConstraints(AC1);
5652 P2->getAssociatedConstraints(AC2);
5653 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
5654 if (S.IsAtLeastAsConstrained(P1, AC1, P2, AC2, AtLeastAsConstrained1) ||
5655 (IsMoreSpecialThanPrimaryCheck && !AtLeastAsConstrained1))
5656 return nullptr;
5657 if (S.IsAtLeastAsConstrained(P2, AC2, P1, AC1, AtLeastAsConstrained2))
5658 return nullptr;
5659 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
5660 return nullptr;
5661 return AtLeastAsConstrained1 ? P1 : GetP2()(P1, P2);
5662}
5663
5664/// Returns the more specialized class template partial specialization
5665/// according to the rules of partial ordering of class template partial
5666/// specializations (C++ [temp.class.order]).
5667///
5668/// \param PS1 the first class template partial specialization
5669///
5670/// \param PS2 the second class template partial specialization
5671///
5672/// \returns the more specialized class template partial specialization. If
5673/// neither partial specialization is more specialized, returns NULL.
5674ClassTemplatePartialSpecializationDecl *
5675Sema::getMoreSpecializedPartialSpecialization(
5676 ClassTemplatePartialSpecializationDecl *PS1,
5677 ClassTemplatePartialSpecializationDecl *PS2,
5678 SourceLocation Loc) {
5679 QualType PT1 = PS1->getInjectedSpecializationType();
5680 QualType PT2 = PS2->getInjectedSpecializationType();
5681
5682 TemplateDeductionInfo Info(Loc);
5683 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
5684}
5685
5686bool Sema::isMoreSpecializedThanPrimary(
5687 ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
5688 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
5689 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
5690 QualType PartialT = Spec->getInjectedSpecializationType();
5691
5692 ClassTemplatePartialSpecializationDecl *MaybeSpec =
5693 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
5694 if (MaybeSpec)
5695 Info.clearSFINAEDiagnostic();
5696 return MaybeSpec;
5697}
5698
5699VarTemplatePartialSpecializationDecl *
5700Sema::getMoreSpecializedPartialSpecialization(
5701 VarTemplatePartialSpecializationDecl *PS1,
5702 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
5703 // Pretend the variable template specializations are class template
5704 // specializations and form a fake injected class name type for comparison.
5705 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&(static_cast <bool> (PS1->getSpecializedTemplate() ==
PS2->getSpecializedTemplate() && "the partial specializations being compared should specialize"
" the same template.") ? void (0) : __assert_fail ("PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() && \"the partial specializations being compared should specialize\" \" the same template.\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 5707, __extension__
__PRETTY_FUNCTION__))
5706 "the partial specializations being compared should specialize"(static_cast <bool> (PS1->getSpecializedTemplate() ==
PS2->getSpecializedTemplate() && "the partial specializations being compared should specialize"
" the same template.") ? void (0) : __assert_fail ("PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() && \"the partial specializations being compared should specialize\" \" the same template.\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 5707, __extension__
__PRETTY_FUNCTION__))
5707 " the same template.")(static_cast <bool> (PS1->getSpecializedTemplate() ==
PS2->getSpecializedTemplate() && "the partial specializations being compared should specialize"
" the same template.") ? void (0) : __assert_fail ("PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() && \"the partial specializations being compared should specialize\" \" the same template.\""
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 5707, __extension__
__PRETTY_FUNCTION__))
;
5708 TemplateName Name(PS1->getSpecializedTemplate());
5709 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
5710 QualType PT1 = Context.getTemplateSpecializationType(
5711 CanonTemplate, PS1->getTemplateArgs().asArray());
5712 QualType PT2 = Context.getTemplateSpecializationType(
5713 CanonTemplate, PS2->getTemplateArgs().asArray());
5714
5715 TemplateDeductionInfo Info(Loc);
5716 return getMoreSpecialized(*this, PT1, PT2, PS1, PS2, Info);
5717}
5718
5719bool Sema::isMoreSpecializedThanPrimary(
5720 VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
5721 VarTemplateDecl *Primary = Spec->getSpecializedTemplate();
5722 TemplateName CanonTemplate =
5723 Context.getCanonicalTemplateName(TemplateName(Primary));
5724 QualType PrimaryT = Context.getTemplateSpecializationType(
5725 CanonTemplate, Primary->getInjectedTemplateArgs());
5726 QualType PartialT = Context.getTemplateSpecializationType(
5727 CanonTemplate, Spec->getTemplateArgs().asArray());
5728
5729 VarTemplatePartialSpecializationDecl *MaybeSpec =
5730 getMoreSpecialized(*this, PartialT, PrimaryT, Spec, Primary, Info);
5731 if (MaybeSpec)
5732 Info.clearSFINAEDiagnostic();
5733 return MaybeSpec;
5734}
5735
5736bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
5737 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) {
5738 // C++1z [temp.arg.template]p4: (DR 150)
5739 // A template template-parameter P is at least as specialized as a
5740 // template template-argument A if, given the following rewrite to two
5741 // function templates...
5742
5743 // Rather than synthesize function templates, we merely perform the
5744 // equivalent partial ordering by performing deduction directly on
5745 // the template parameter lists of the template template parameters.
5746 //
5747 // Given an invented class template X with the template parameter list of
5748 // A (including default arguments):
5749 TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg));
5750 TemplateParameterList *A = AArg->getTemplateParameters();
5751
5752 // - Each function template has a single function parameter whose type is
5753 // a specialization of X with template arguments corresponding to the
5754 // template parameters from the respective function template
5755 SmallVector<TemplateArgument, 8> AArgs;
5756 Context.getInjectedTemplateArgs(A, AArgs);
5757
5758 // Check P's arguments against A's parameter list. This will fill in default
5759 // template arguments as needed. AArgs are already correct by construction.
5760 // We can't just use CheckTemplateIdType because that will expand alias
5761 // templates.
5762 SmallVector<TemplateArgument, 4> PArgs;
5763 {
5764 SFINAETrap Trap(*this);
5765
5766 Context.getInjectedTemplateArgs(P, PArgs);
5767 TemplateArgumentListInfo PArgList(P->getLAngleLoc(),
5768 P->getRAngleLoc());
5769 for (unsigned I = 0, N = P->size(); I != N; ++I) {
5770 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
5771 // expansions, to form an "as written" argument list.
5772 TemplateArgument Arg = PArgs[I];
5773 if (Arg.getKind() == TemplateArgument::Pack) {
5774 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion())(static_cast <bool> (Arg.pack_size() == 1 && Arg
.pack_begin()->isPackExpansion()) ? void (0) : __assert_fail
("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion()"
, "clang/lib/Sema/SemaTemplateDeduction.cpp", 5774, __extension__
__PRETTY_FUNCTION__))
;
5775 Arg = *Arg.pack_begin();
5776 }
5777 PArgList.addArgument(getTrivialTemplateArgumentLoc(
5778 Arg, QualType(), P->getParam(I)->getLocation()));
5779 }
5780 PArgs.clear();
5781
5782 // C++1z [temp.arg.template]p3:
5783 // If the rewrite produces an invalid type, then P is not at least as
5784 // specialized as A.
5785 SmallVector<TemplateArgument, 4> SugaredPArgs;
5786 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, SugaredPArgs,
5787 PArgs) ||
5788 Trap.hasErrorOccurred())
5789 return false;
5790 }
5791
5792 QualType AType = Context.getCanonicalTemplateSpecializationType(X, AArgs);
5793 QualType PType = Context.getCanonicalTemplateSpecializationType(X, PArgs);
5794
5795 // ... the function template corresponding to P is at least as specialized
5796 // as the function template corresponding to A according to the partial
5797 // ordering rules for function templates.
5798 TemplateDeductionInfo Info(Loc, A->getDepth());
5799 return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info);
5800}
5801
5802namespace {
5803struct MarkUsedTemplateParameterVisitor :
5804 RecursiveASTVisitor<MarkUsedTemplateParameterVisitor> {
5805 llvm::SmallBitVector &Used;
5806 unsigned Depth;
5807
5808 MarkUsedTemplateParameterVisitor(llvm::SmallBitVector &Used,
5809 unsigned Depth)
5810 : Used(Used), Depth(Depth) { }
5811
5812 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
5813 if (T->getDepth() == Depth)
5814 Used[T->getIndex()] = true;
5815 return true;
5816 }
5817
5818 bool TraverseTemplateName(TemplateName Template) {
5819 if (auto *TTP = llvm::dyn_cast_or_null<TemplateTemplateParmDecl>(
5820 Template.getAsTemplateDecl()))
5821 if (TTP->getDepth() == Depth)
5822 Used[TTP->getIndex()] = true;
5823 RecursiveASTVisitor<MarkUsedTemplateParameterVisitor>::
5824 TraverseTemplateName(Template);
5825 return true;
5826 }
5827
5828 bool VisitDeclRefExpr(DeclRefExpr *E) {
5829 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
5830 if (NTTP->getDepth() == Depth)
5831 Used[NTTP->getIndex()] = true;
5832 return true;
5833 }
5834};
5835}
5836
5837/// Mark the template parameters that are used by the given
5838/// expression.
5839static void
5840MarkUsedTemplateParameters(ASTContext &Ctx,
5841 const Expr *E,
5842 bool OnlyDeduced,
5843 unsigned Depth,
5844 llvm::SmallBitVector &Used) {
5845 if (!OnlyDeduced) {
5846 MarkUsedTemplateParameterVisitor(Used, Depth)
5847 .TraverseStmt(const_cast<Expr *>(E));
5848 return;
5849 }
5850
5851 // We can deduce from a pack expansion.
5852 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
5853 E = Expansion->getPattern();
5854
5855 const NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(E, Depth);
5856 if (!NTTP)
5857 return;
5858
5859 if (NTTP->getDepth() == Depth)
5860 Used[NTTP->getIndex()] = true;
5861
5862 // In C++17 mode, additional arguments may be deduced from the type of a
5863 // non-type argument.
5864 if (Ctx.getLangOpts().CPlusPlus17)
5865 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
5866}
5867
5868/// Mark the template parameters that are used by the given
5869/// nested name specifier.
5870static void
5871MarkUsedTemplateParameters(ASTContext &Ctx,
5872 NestedNameSpecifier *NNS,
5873 bool OnlyDeduced,
5874 unsigned Depth,
5875 llvm::SmallBitVector &Used) {
5876 if (!NNS)
5877 return;
5878
5879 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
5880 Used);
5881 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
5882 OnlyDeduced, Depth, Used);
5883}
5884
5885/// Mark the template parameters that are used by the given
5886/// template name.
5887static void
5888MarkUsedTemplateParameters(ASTContext &Ctx,
5889 TemplateName Name,
5890 bool OnlyDeduced,
5891 unsigned Depth,
5892 llvm::SmallBitVector &Used) {
5893 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
5894 if (TemplateTemplateParmDecl *TTP
5895 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
5896 if (TTP->getDepth() == Depth)
5897 Used[TTP->getIndex()] = true;
5898 }
5899 return;
5900 }
5901
5902 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
5903 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
5904 Depth, Used);
5905 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
5906 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
5907 Depth, Used);
5908}
5909
5910/// Mark the template parameters that are used by the given
5911/// type.
5912static void
5913MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
5914 bool OnlyDeduced,
5915 unsigned Depth,
5916 llvm::SmallBitVector &Used) {
5917 if (T.isNull())
5918 return;
5919
5920 // Non-dependent types have nothing deducible
5921 if (!T->isDependentType())
5922 return;
5923
5924 T = Ctx.getCanonicalType(T);
5925 switch (T->getTypeClass()) {
5926 case Type::Pointer:
5927 MarkUsedTemplateParameters(Ctx,
5928 cast<PointerType>(T)->getPointeeType(),
5929 OnlyDeduced,
5930 Depth,
5931 Used);
5932 break;
5933
5934 case Type::BlockPointer:
5935 MarkUsedTemplateParameters(Ctx,
5936 cast<BlockPointerType>(T)->getPointeeType(),
5937 OnlyDeduced,
5938 Depth,
5939 Used);
5940 break;
5941
5942 case Type::LValueReference:
5943 case Type::RValueReference:
5944 MarkUsedTemplateParameters(Ctx,
5945 cast<ReferenceType>(T)->getPointeeType(),
5946 OnlyDeduced,
5947 Depth,
5948 Used);
5949 break;
5950
5951 case Type::MemberPointer: {
5952 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
5953 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
5954 Depth, Used);
5955 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
5956 OnlyDeduced, Depth, Used);
5957 break;
5958 }
5959
5960 case Type::DependentSizedArray:
5961 MarkUsedTemplateParameters(Ctx,
5962 cast<DependentSizedArrayType>(T)->getSizeExpr(),
5963 OnlyDeduced, Depth, Used);
5964 // Fall through to check the element type
5965 [[fallthrough]];
5966
5967 case Type::ConstantArray:
5968 case Type::IncompleteArray:
5969 MarkUsedTemplateParameters(Ctx,
5970 cast<ArrayType>(T)->getElementType(),
5971 OnlyDeduced, Depth, Used);
5972 break;
5973
5974 case Type::Vector:
5975 case Type::ExtVector:
5976 MarkUsedTemplateParameters(Ctx,
5977 cast<VectorType>(T)->getElementType(),
5978 OnlyDeduced, Depth, Used);
5979 break;
5980
5981 case Type::DependentVector: {
5982 const auto *VecType = cast<DependentVectorType>(T);
5983 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
5984 Depth, Used);
5985 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth,
5986 Used);
5987 break;
5988 }
5989 case Type::DependentSizedExtVector: {
5990 const DependentSizedExtVectorType *VecType
5991 = cast<DependentSizedExtVectorType>(T);
5992 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
5993 Depth, Used);
5994 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
5995 Depth, Used);
5996 break;
5997 }
5998
5999 case Type::DependentAddressSpace: {
6000 const DependentAddressSpaceType *DependentASType =
6001 cast<DependentAddressSpaceType>(T);
6002 MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
6003 OnlyDeduced, Depth, Used);
6004 MarkUsedTemplateParameters(Ctx,
6005 DependentASType->getAddrSpaceExpr(),
6006 OnlyDeduced, Depth, Used);
6007 break;
6008 }
6009
6010 case Type::ConstantMatrix: {
6011 const ConstantMatrixType *MatType = cast<ConstantMatrixType>(T);
6012 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
6013 Depth, Used);
6014 break;
6015 }
6016
6017 case Type::DependentSizedMatrix: {
6018 const DependentSizedMatrixType *MatType = cast<DependentSizedMatrixType>(T);
6019 MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
6020 Depth, Used);
6021 MarkUsedTemplateParameters(Ctx, MatType->getRowExpr(), OnlyDeduced, Depth,
6022 Used);
6023 MarkUsedTemplateParameters(Ctx, MatType->getColumnExpr(), OnlyDeduced,
6024 Depth, Used);
6025 break;
6026 }
6027
6028 case Type::FunctionProto: {
6029 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
6030 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
6031 Used);
6032 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
6033 // C++17 [temp.deduct.type]p5:
6034 // The non-deduced contexts are: [...]
6035 // -- A function parameter pack that does not occur at the end of the
6036 // parameter-declaration-list.
6037 if (!OnlyDeduced || I + 1 == N ||
6038 !Proto->getParamType(I)->getAs<PackExpansionType>()) {
6039 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
6040 Depth, Used);
6041 } else {
6042 // FIXME: C++17 [temp.deduct.call]p1:
6043 // When a function parameter pack appears in a non-deduced context,
6044 // the type of that pack is never deduced.
6045 //
6046 // We should also track a set of "never deduced" parameters, and
6047 // subtract that from the list of deduced parameters after marking.
6048 }
6049 }
6050 if (auto *E = Proto->getNoexceptExpr())
6051 MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
6052 break;
6053 }
6054
6055 case Type::TemplateTypeParm: {
6056 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
6057 if (TTP->getDepth() == Depth)
6058 Used[TTP->getIndex()] = true;
6059 break;
6060 }
6061
6062 case Type::SubstTemplateTypeParmPack: {
6063 const SubstTemplateTypeParmPackType *Subst
6064 = cast<SubstTemplateTypeParmPackType>(T);
6065 if (Subst->getReplacedParameter()->getDepth() == Depth)
6066 Used[Subst->getIndex()] = true;
6067 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
6068 OnlyDeduced, Depth, Used);
6069 break;
6070 }
6071
6072 case Type::InjectedClassName:
6073 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
6074 [[fallthrough]];
6075
6076 case Type::TemplateSpecialization: {
6077 const TemplateSpecializationType *Spec
6078 = cast<TemplateSpecializationType>(T);
6079 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
6080 Depth, Used);
6081
6082 // C++0x [temp.deduct.type]p9:
6083 // If the template argument list of P contains a pack expansion that is
6084 // not the last template argument, the entire template argument list is a
6085 // non-deduced context.
6086 if (OnlyDeduced &&
6087 hasPackExpansionBeforeEnd(Spec->template_arguments()))
6088 break;
6089
6090 for (const auto &Arg : Spec->template_arguments())
6091 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
6092 break;
6093 }
6094
6095 case Type::Complex:
6096 if (!OnlyDeduced)
6097 MarkUsedTemplateParameters(Ctx,
6098 cast<ComplexType>(T)->getElementType(),
6099 OnlyDeduced, Depth, Used);
6100 break;
6101
6102 case Type::Atomic:
6103 if (!OnlyDeduced)
6104 MarkUsedTemplateParameters(Ctx,
6105 cast<AtomicType>(T)->getValueType(),
6106 OnlyDeduced, Depth, Used);
6107 break;
6108
6109 case Type::DependentName:
6110 if (!OnlyDeduced)
6111 MarkUsedTemplateParameters(Ctx,
6112 cast<DependentNameType>(T)->getQualifier(),
6113 OnlyDeduced, Depth, Used);
6114 break;
6115
6116 case Type::DependentTemplateSpecialization: {
6117 // C++14 [temp.deduct.type]p5:
6118 // The non-deduced contexts are:
6119 // -- The nested-name-specifier of a type that was specified using a
6120 // qualified-id
6121 //
6122 // C++14 [temp.deduct.type]p6:
6123 // When a type name is specified in a way that includes a non-deduced
6124 // context, all of the types that comprise that type name are also
6125 // non-deduced.
6126 if (OnlyDeduced)
6127 break;
6128
6129 const DependentTemplateSpecializationType *Spec
6130 = cast<DependentTemplateSpecializationType>(T);
6131
6132 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
6133 OnlyDeduced, Depth, Used);
6134
6135 for (const auto &Arg : Spec->template_arguments())
6136 MarkUsedTemplateParameters(Ctx, Arg, OnlyDeduced, Depth, Used);
6137 break;
6138 }
6139
6140 case Type::TypeOf:
6141 if (!OnlyDeduced)
6142 MarkUsedTemplateParameters(Ctx, cast<TypeOfType>(T)->getUnmodifiedType(),
6143 OnlyDeduced, Depth, Used);
6144 break;
6145
6146 case Type::TypeOfExpr:
6147 if (!OnlyDeduced)
6148 MarkUsedTemplateParameters(Ctx,
6149 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
6150 OnlyDeduced, Depth, Used);
6151 break;
6152
6153 case Type::Decltype:
6154 if (!OnlyDeduced)
6155 MarkUsedTemplateParameters(Ctx,
6156 cast<DecltypeType>(T)->getUnderlyingExpr(),
6157 OnlyDeduced, Depth, Used);
6158 break;
6159
6160 case Type::UnaryTransform:
6161 if (!OnlyDeduced)
6162 MarkUsedTemplateParameters(Ctx,
6163 cast<UnaryTransformType>(T)->getUnderlyingType(),
6164 OnlyDeduced, Depth, Used);
6165 break;
6166
6167 case Type::PackExpansion:
6168 MarkUsedTemplateParameters(Ctx,
6169 cast<PackExpansionType>(T)->getPattern(),
6170 OnlyDeduced, Depth, Used);
6171 break;
6172
6173 case Type::Auto:
6174 case Type::DeducedTemplateSpecialization:
6175 MarkUsedTemplateParameters(Ctx,
6176 cast<DeducedType>(T)->getDeducedType(),
6177 OnlyDeduced, Depth, Used);
6178 break;
6179 case Type::DependentBitInt:
6180 MarkUsedTemplateParameters(Ctx,
6181 cast<DependentBitIntType>(T)->getNumBitsExpr(),
6182 OnlyDeduced, Depth, Used);
6183 break;
6184
6185 // None of these types have any template parameters in them.
6186 case Type::Builtin:
6187 case Type::VariableArray:
6188 case Type::FunctionNoProto:
6189 case Type::Record:
6190 case Type::Enum:
6191 case Type::ObjCInterface:
6192 case Type::ObjCObject:
6193 case Type::ObjCObjectPointer:
6194 case Type::UnresolvedUsing:
6195 case Type::Pipe:
6196 case Type::BitInt:
6197#define TYPE(Class, Base)
6198#define ABSTRACT_TYPE(Class, Base)
6199#define DEPENDENT_TYPE(Class, Base)
6200#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6201#include "clang/AST/TypeNodes.inc"
6202 break;
6203 }
6204}
6205
6206/// Mark the template parameters that are used by this
6207/// template argument.
6208static void
6209MarkUsedTemplateParameters(ASTContext &Ctx,
6210 const TemplateArgument &TemplateArg,
6211 bool OnlyDeduced,
6212 unsigned Depth,
6213 llvm::SmallBitVector &Used) {
6214 switch (TemplateArg.getKind()) {
6215 case TemplateArgument::Null:
6216 case TemplateArgument::Integral:
6217 case TemplateArgument::Declaration:
6218 break;
6219
6220 case TemplateArgument::NullPtr:
6221 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
6222 Depth, Used);
6223 break;
6224
6225 case TemplateArgument::Type:
6226 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
6227 Depth, Used);
6228 break;
6229
6230 case TemplateArgument::Template:
6231 case TemplateArgument::TemplateExpansion:
6232 MarkUsedTemplateParameters(Ctx,
6233 TemplateArg.getAsTemplateOrTemplatePattern(),
6234 OnlyDeduced, Depth, Used);
6235 break;
6236
6237 case TemplateArgument::Expression:
6238 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
6239 Depth, Used);
6240 break;
6241
6242 case TemplateArgument::Pack:
6243 for (const auto &P : TemplateArg.pack_elements())
6244 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
6245 break;
6246 }
6247}
6248
6249/// Mark which template parameters are used in a given expression.
6250///
6251/// \param E the expression from which template parameters will be deduced.
6252///
6253/// \param Used a bit vector whose elements will be set to \c true
6254/// to indicate when the corresponding template parameter will be
6255/// deduced.
6256void
6257Sema::MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
6258 unsigned Depth,
6259 llvm::SmallBitVector &Used) {
6260 ::MarkUsedTemplateParameters(Context, E, OnlyDeduced, Depth, Used);
6261}
6262
6263/// Mark which template parameters can be deduced from a given
6264/// template argument list.
6265///
6266/// \param TemplateArgs the template argument list from which template
6267/// parameters will be deduced.
6268///
6269/// \param Used a bit vector whose elements will be set to \c true
6270/// to indicate when the corresponding template parameter will be
6271/// deduced.
6272void
6273Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
6274 bool OnlyDeduced, unsigned Depth,
6275 llvm::SmallBitVector &Used) {
6276 // C++0x [temp.deduct.type]p9:
6277 // If the template argument list of P contains a pack expansion that is not
6278 // the last template argument, the entire template argument list is a
6279 // non-deduced context.
6280 if (OnlyDeduced &&
6281 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
6282 return;
6283
6284 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6285 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
6286 Depth, Used);
6287}
6288
6289/// Marks all of the template parameters that will be deduced by a
6290/// call to the given function template.
6291void Sema::MarkDeducedTemplateParameters(
6292 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
6293 llvm::SmallBitVector &Deduced) {
6294 TemplateParameterList *TemplateParams
6295 = FunctionTemplate->getTemplateParameters();
6296 Deduced.clear();
6297 Deduced.resize(TemplateParams->size());
6298
6299 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
6300 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
6301 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
6302 true, TemplateParams->getDepth(), Deduced);
6303}
6304
6305bool hasDeducibleTemplateParameters(Sema &S,
6306 FunctionTemplateDecl *FunctionTemplate,
6307 QualType T) {
6308 if (!T->isDependentType())
6309 return false;
6310
6311 TemplateParameterList *TemplateParams
6312 = FunctionTemplate->getTemplateParameters();
6313 llvm::SmallBitVector Deduced(TemplateParams->size());
6314 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
6315 Deduced);
6316
6317 return Deduced.any();
6318}