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