1 //===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===/
9 // This file implements C++ template argument deduction.
11 //===----------------------------------------------------------------------===/
13 #include "clang/Sema/TemplateDeduction.h"
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/StmtVisitor.h"
22 #include "clang/AST/TypeOrdering.h"
23 #include "clang/Sema/DeclSpec.h"
24 #include "clang/Sema/Sema.h"
25 #include "clang/Sema/Template.h"
26 #include "llvm/ADT/SmallBitVector.h"
31 /// \brief Various flags that control template argument deduction.
33 /// These flags can be bitwise-OR'd together.
34 enum TemplateDeductionFlags {
35 /// \brief No template argument deduction flags, which indicates the
36 /// strictest results for template argument deduction (as used for, e.g.,
37 /// matching class template partial specializations).
39 /// \brief Within template argument deduction from a function call, we are
40 /// matching with a parameter type for which the original parameter was
42 TDF_ParamWithReferenceType = 0x1,
43 /// \brief Within template argument deduction from a function call, we
44 /// are matching in a case where we ignore cv-qualifiers.
45 TDF_IgnoreQualifiers = 0x02,
46 /// \brief Within template argument deduction from a function call,
47 /// we are matching in a case where we can perform template argument
48 /// deduction from a template-id of a derived class of the argument type.
49 TDF_DerivedClass = 0x04,
50 /// \brief Allow non-dependent types to differ, e.g., when performing
51 /// template argument deduction from a function call where conversions
53 TDF_SkipNonDependent = 0x08,
54 /// \brief Whether we are performing template argument deduction for
55 /// parameters and arguments in a top-level template argument
56 TDF_TopLevelParameterTypeList = 0x10,
57 /// \brief Within template argument deduction from overload resolution per
58 /// C++ [over.over] allow matching function types that are compatible in
59 /// terms of noreturn and default calling convention adjustments.
60 TDF_InOverloadResolution = 0x20
64 using namespace clang;
66 /// \brief Compare two APSInts, extending and switching the sign as
67 /// necessary to compare their values regardless of underlying type.
68 static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
69 if (Y.getBitWidth() > X.getBitWidth())
70 X = X.extend(Y.getBitWidth());
71 else if (Y.getBitWidth() < X.getBitWidth())
72 Y = Y.extend(X.getBitWidth());
74 // If there is a signedness mismatch, correct it.
75 if (X.isSigned() != Y.isSigned()) {
76 // If the signed value is negative, then the values cannot be the same.
77 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
87 static Sema::TemplateDeductionResult
88 DeduceTemplateArguments(Sema &S,
89 TemplateParameterList *TemplateParams,
90 const TemplateArgument &Param,
92 TemplateDeductionInfo &Info,
93 SmallVectorImpl<DeducedTemplateArgument> &Deduced);
95 static Sema::TemplateDeductionResult
96 DeduceTemplateArgumentsByTypeMatch(Sema &S,
97 TemplateParameterList *TemplateParams,
100 TemplateDeductionInfo &Info,
101 SmallVectorImpl<DeducedTemplateArgument> &
104 bool PartialOrdering = false,
105 bool DeducedFromArrayBound = false);
107 static Sema::TemplateDeductionResult
108 DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
109 ArrayRef<TemplateArgument> Params,
110 ArrayRef<TemplateArgument> Args,
111 TemplateDeductionInfo &Info,
112 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
113 bool NumberOfArgumentsMustMatch);
115 /// \brief If the given expression is of a form that permits the deduction
116 /// of a non-type template parameter, return the declaration of that
117 /// non-type template parameter.
118 static NonTypeTemplateParmDecl *
119 getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) {
120 // If we are within an alias template, the expression may have undergone
121 // any number of parameter substitutions already.
123 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
124 E = IC->getSubExpr();
125 else if (SubstNonTypeTemplateParmExpr *Subst =
126 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
127 E = Subst->getReplacement();
132 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
133 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
134 if (NTTP->getDepth() == Info.getDeducedDepth())
140 /// \brief Determine whether two declaration pointers refer to the same
142 static bool isSameDeclaration(Decl *X, Decl *Y) {
143 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
144 X = NX->getUnderlyingDecl();
145 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
146 Y = NY->getUnderlyingDecl();
148 return X->getCanonicalDecl() == Y->getCanonicalDecl();
151 /// \brief Verify that the given, deduced template arguments are compatible.
153 /// \returns The deduced template argument, or a NULL template argument if
154 /// the deduced template arguments were incompatible.
155 static DeducedTemplateArgument
156 checkDeducedTemplateArguments(ASTContext &Context,
157 const DeducedTemplateArgument &X,
158 const DeducedTemplateArgument &Y) {
159 // We have no deduction for one or both of the arguments; they're compatible.
165 // If we have two non-type template argument values deduced for the same
166 // parameter, they must both match the type of the parameter, and thus must
167 // match each other's type. As we're only keeping one of them, we must check
168 // for that now. The exception is that if either was deduced from an array
169 // bound, the type is permitted to differ.
170 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
171 QualType XType = X.getNonTypeTemplateArgumentType();
172 if (!XType.isNull()) {
173 QualType YType = Y.getNonTypeTemplateArgumentType();
174 if (YType.isNull() || !Context.hasSameType(XType, YType))
175 return DeducedTemplateArgument();
179 switch (X.getKind()) {
180 case TemplateArgument::Null:
181 llvm_unreachable("Non-deduced template arguments handled above");
183 case TemplateArgument::Type:
184 // If two template type arguments have the same type, they're compatible.
185 if (Y.getKind() == TemplateArgument::Type &&
186 Context.hasSameType(X.getAsType(), Y.getAsType()))
189 // If one of the two arguments was deduced from an array bound, the other
191 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
192 return X.wasDeducedFromArrayBound() ? Y : X;
194 // The arguments are not compatible.
195 return DeducedTemplateArgument();
197 case TemplateArgument::Integral:
198 // If we deduced a constant in one case and either a dependent expression or
199 // declaration in another case, keep the integral constant.
200 // If both are integral constants with the same value, keep that value.
201 if (Y.getKind() == TemplateArgument::Expression ||
202 Y.getKind() == TemplateArgument::Declaration ||
203 (Y.getKind() == TemplateArgument::Integral &&
204 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
205 return X.wasDeducedFromArrayBound() ? Y : X;
207 // All other combinations are incompatible.
208 return DeducedTemplateArgument();
210 case TemplateArgument::Template:
211 if (Y.getKind() == TemplateArgument::Template &&
212 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
215 // All other combinations are incompatible.
216 return DeducedTemplateArgument();
218 case TemplateArgument::TemplateExpansion:
219 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
220 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
221 Y.getAsTemplateOrTemplatePattern()))
224 // All other combinations are incompatible.
225 return DeducedTemplateArgument();
227 case TemplateArgument::Expression: {
228 if (Y.getKind() != TemplateArgument::Expression)
229 return checkDeducedTemplateArguments(Context, Y, X);
231 // Compare the expressions for equality
232 llvm::FoldingSetNodeID ID1, ID2;
233 X.getAsExpr()->Profile(ID1, Context, true);
234 Y.getAsExpr()->Profile(ID2, Context, true);
236 return X.wasDeducedFromArrayBound() ? Y : X;
238 // Differing dependent expressions are incompatible.
239 return DeducedTemplateArgument();
242 case TemplateArgument::Declaration:
243 assert(!X.wasDeducedFromArrayBound());
245 // If we deduced a declaration and a dependent expression, keep the
247 if (Y.getKind() == TemplateArgument::Expression)
250 // If we deduced a declaration and an integral constant, keep the
251 // integral constant and whichever type did not come from an array
253 if (Y.getKind() == TemplateArgument::Integral) {
254 if (Y.wasDeducedFromArrayBound())
255 return TemplateArgument(Context, Y.getAsIntegral(),
256 X.getParamTypeForDecl());
260 // If we deduced two declarations, make sure they they refer to the
262 if (Y.getKind() == TemplateArgument::Declaration &&
263 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
266 // All other combinations are incompatible.
267 return DeducedTemplateArgument();
269 case TemplateArgument::NullPtr:
270 // If we deduced a null pointer and a dependent expression, keep the
272 if (Y.getKind() == TemplateArgument::Expression)
275 // If we deduced a null pointer and an integral constant, keep the
276 // integral constant.
277 if (Y.getKind() == TemplateArgument::Integral)
280 // If we deduced two null pointers, they are the same.
281 if (Y.getKind() == TemplateArgument::NullPtr)
284 // All other combinations are incompatible.
285 return DeducedTemplateArgument();
287 case TemplateArgument::Pack:
288 if (Y.getKind() != TemplateArgument::Pack ||
289 X.pack_size() != Y.pack_size())
290 return DeducedTemplateArgument();
292 llvm::SmallVector<TemplateArgument, 8> NewPack;
293 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
294 XAEnd = X.pack_end(),
296 XA != XAEnd; ++XA, ++YA) {
297 TemplateArgument Merged = checkDeducedTemplateArguments(
298 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
299 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()));
301 return DeducedTemplateArgument();
302 NewPack.push_back(Merged);
305 return DeducedTemplateArgument(
306 TemplateArgument::CreatePackCopy(Context, NewPack),
307 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
310 llvm_unreachable("Invalid TemplateArgument Kind!");
313 /// \brief Deduce the value of the given non-type template parameter
314 /// as the given deduced template argument. All non-type template parameter
315 /// deduction is funneled through here.
316 static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
317 Sema &S, TemplateParameterList *TemplateParams,
318 NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced,
319 QualType ValueType, TemplateDeductionInfo &Info,
320 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
321 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
322 "deducing non-type template argument with wrong depth");
324 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
325 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
326 if (Result.isNull()) {
328 Info.FirstArg = Deduced[NTTP->getIndex()];
329 Info.SecondArg = NewDeduced;
330 return Sema::TDK_Inconsistent;
333 Deduced[NTTP->getIndex()] = Result;
334 if (!S.getLangOpts().CPlusPlus1z)
335 return Sema::TDK_Success;
337 // FIXME: It's not clear how deduction of a parameter of reference
338 // type from an argument (of non-reference type) should be performed.
339 // For now, we just remove reference types from both sides and let
340 // the final check for matching types sort out the mess.
341 return DeduceTemplateArgumentsByTypeMatch(
342 S, TemplateParams, NTTP->getType().getNonReferenceType(),
343 ValueType.getNonReferenceType(), Info, Deduced, TDF_SkipNonDependent,
344 /*PartialOrdering=*/false,
345 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound());
348 /// \brief Deduce the value of the given non-type template parameter
349 /// from the given integral constant.
350 static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
351 Sema &S, TemplateParameterList *TemplateParams,
352 NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
353 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
354 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
355 return DeduceNonTypeTemplateArgument(
356 S, TemplateParams, NTTP,
357 DeducedTemplateArgument(S.Context, Value, ValueType,
358 DeducedFromArrayBound),
359 ValueType, Info, Deduced);
362 /// \brief Deduce the value of the given non-type template parameter
363 /// from the given null pointer template argument type.
364 static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
365 Sema &S, TemplateParameterList *TemplateParams,
366 NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
367 TemplateDeductionInfo &Info,
368 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
370 S.ImpCastExprToType(new (S.Context) CXXNullPtrLiteralExpr(
371 S.Context.NullPtrTy, NTTP->getLocation()),
372 NullPtrType, CK_NullToPointer)
374 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
375 DeducedTemplateArgument(Value),
376 Value->getType(), Info, Deduced);
379 /// \brief Deduce the value of the given non-type template parameter
380 /// from the given type- or value-dependent expression.
382 /// \returns true if deduction succeeded, false otherwise.
383 static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
384 Sema &S, TemplateParameterList *TemplateParams,
385 NonTypeTemplateParmDecl *NTTP, Expr *Value, TemplateDeductionInfo &Info,
386 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
387 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
388 DeducedTemplateArgument(Value),
389 Value->getType(), Info, Deduced);
392 /// \brief Deduce the value of the given non-type template parameter
393 /// from the given declaration.
395 /// \returns true if deduction succeeded, false otherwise.
396 static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
397 Sema &S, TemplateParameterList *TemplateParams,
398 NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
399 TemplateDeductionInfo &Info,
400 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
401 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
402 TemplateArgument New(D, T);
403 return DeduceNonTypeTemplateArgument(
404 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
407 static Sema::TemplateDeductionResult
408 DeduceTemplateArguments(Sema &S,
409 TemplateParameterList *TemplateParams,
412 TemplateDeductionInfo &Info,
413 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
414 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
416 // The parameter type is dependent and is not a template template parameter,
417 // so there is nothing that we can deduce.
418 return Sema::TDK_Success;
421 if (TemplateTemplateParmDecl *TempParam
422 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
423 // If we're not deducing at this depth, there's nothing to deduce.
424 if (TempParam->getDepth() != Info.getDeducedDepth())
425 return Sema::TDK_Success;
427 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
428 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
429 Deduced[TempParam->getIndex()],
431 if (Result.isNull()) {
432 Info.Param = TempParam;
433 Info.FirstArg = Deduced[TempParam->getIndex()];
434 Info.SecondArg = NewDeduced;
435 return Sema::TDK_Inconsistent;
438 Deduced[TempParam->getIndex()] = Result;
439 return Sema::TDK_Success;
442 // Verify that the two template names are equivalent.
443 if (S.Context.hasSameTemplateName(Param, Arg))
444 return Sema::TDK_Success;
446 // Mismatch of non-dependent template parameter to argument.
447 Info.FirstArg = TemplateArgument(Param);
448 Info.SecondArg = TemplateArgument(Arg);
449 return Sema::TDK_NonDeducedMismatch;
452 /// \brief Deduce the template arguments by comparing the template parameter
453 /// type (which is a template-id) with the template argument type.
455 /// \param S the Sema
457 /// \param TemplateParams the template parameters that we are deducing
459 /// \param Param the parameter type
461 /// \param Arg the argument type
463 /// \param Info information about the template argument deduction itself
465 /// \param Deduced the deduced template arguments
467 /// \returns the result of template argument deduction so far. Note that a
468 /// "success" result means that template argument deduction has not yet failed,
469 /// but it may still fail, later, for other reasons.
470 static Sema::TemplateDeductionResult
471 DeduceTemplateArguments(Sema &S,
472 TemplateParameterList *TemplateParams,
473 const TemplateSpecializationType *Param,
475 TemplateDeductionInfo &Info,
476 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
477 assert(Arg.isCanonical() && "Argument type must be canonical");
479 // Check whether the template argument is a dependent template-id.
480 if (const TemplateSpecializationType *SpecArg
481 = dyn_cast<TemplateSpecializationType>(Arg)) {
482 // Perform template argument deduction for the template name.
483 if (Sema::TemplateDeductionResult Result
484 = DeduceTemplateArguments(S, TemplateParams,
485 Param->getTemplateName(),
486 SpecArg->getTemplateName(),
491 // Perform template argument deduction on each template
492 // argument. Ignore any missing/extra arguments, since they could be
493 // filled in by default arguments.
494 return DeduceTemplateArguments(S, TemplateParams,
495 Param->template_arguments(),
496 SpecArg->template_arguments(), Info, Deduced,
497 /*NumberOfArgumentsMustMatch=*/false);
500 // If the argument type is a class template specialization, we
501 // perform template argument deduction using its template
503 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
505 Info.FirstArg = TemplateArgument(QualType(Param, 0));
506 Info.SecondArg = TemplateArgument(Arg);
507 return Sema::TDK_NonDeducedMismatch;
510 ClassTemplateSpecializationDecl *SpecArg
511 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
513 Info.FirstArg = TemplateArgument(QualType(Param, 0));
514 Info.SecondArg = TemplateArgument(Arg);
515 return Sema::TDK_NonDeducedMismatch;
518 // Perform template argument deduction for the template name.
519 if (Sema::TemplateDeductionResult Result
520 = DeduceTemplateArguments(S,
522 Param->getTemplateName(),
523 TemplateName(SpecArg->getSpecializedTemplate()),
527 // Perform template argument deduction for the template arguments.
528 return DeduceTemplateArguments(S, TemplateParams, Param->template_arguments(),
529 SpecArg->getTemplateArgs().asArray(), Info,
530 Deduced, /*NumberOfArgumentsMustMatch=*/true);
533 /// \brief Determines whether the given type is an opaque type that
534 /// might be more qualified when instantiated.
535 static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
536 switch (T->getTypeClass()) {
537 case Type::TypeOfExpr:
539 case Type::DependentName:
541 case Type::UnresolvedUsing:
542 case Type::TemplateTypeParm:
545 case Type::ConstantArray:
546 case Type::IncompleteArray:
547 case Type::VariableArray:
548 case Type::DependentSizedArray:
549 return IsPossiblyOpaquelyQualifiedType(
550 cast<ArrayType>(T)->getElementType());
557 /// \brief Retrieve the depth and index of a template parameter.
558 static std::pair<unsigned, unsigned>
559 getDepthAndIndex(NamedDecl *ND) {
560 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
561 return std::make_pair(TTP->getDepth(), TTP->getIndex());
563 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
564 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
566 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
567 return std::make_pair(TTP->getDepth(), TTP->getIndex());
570 /// \brief Retrieve the depth and index of an unexpanded parameter pack.
571 static std::pair<unsigned, unsigned>
572 getDepthAndIndex(UnexpandedParameterPack UPP) {
573 if (const TemplateTypeParmType *TTP
574 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
575 return std::make_pair(TTP->getDepth(), TTP->getIndex());
577 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
580 /// \brief Helper function to build a TemplateParameter when we don't
581 /// know its type statically.
582 static TemplateParameter makeTemplateParameter(Decl *D) {
583 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
584 return TemplateParameter(TTP);
585 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
586 return TemplateParameter(NTTP);
588 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
591 /// A pack that we're currently deducing.
592 struct clang::DeducedPack {
593 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
595 // The index of the pack.
598 // The old value of the pack before we started deducing it.
599 DeducedTemplateArgument Saved;
601 // A deferred value of this pack from an inner deduction, that couldn't be
602 // deduced because this deduction hadn't happened yet.
603 DeducedTemplateArgument DeferredDeduction;
605 // The new value of the pack.
606 SmallVector<DeducedTemplateArgument, 4> New;
608 // The outer deduction for this pack, if any.
613 /// A scope in which we're performing pack deduction.
614 class PackDeductionScope {
616 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
617 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
618 TemplateDeductionInfo &Info, TemplateArgument Pattern)
619 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
620 // Compute the set of template parameter indices that correspond to
621 // parameter packs expanded by the pack expansion.
623 llvm::SmallBitVector SawIndices(TemplateParams->size());
624 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
625 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
626 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
627 unsigned Depth, Index;
628 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
629 if (Depth == Info.getDeducedDepth() && !SawIndices[Index]) {
630 SawIndices[Index] = true;
632 // Save the deduced template argument for the parameter pack expanded
633 // by this pack expansion, then clear out the deduction.
634 DeducedPack Pack(Index);
635 Pack.Saved = Deduced[Index];
636 Deduced[Index] = TemplateArgument();
638 Packs.push_back(Pack);
642 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
644 for (auto &Pack : Packs) {
645 if (Info.PendingDeducedPacks.size() > Pack.Index)
646 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
648 Info.PendingDeducedPacks.resize(Pack.Index + 1);
649 Info.PendingDeducedPacks[Pack.Index] = &Pack;
651 if (S.CurrentInstantiationScope) {
652 // If the template argument pack was explicitly specified, add that to
653 // the set of deduced arguments.
654 const TemplateArgument *ExplicitArgs;
655 unsigned NumExplicitArgs;
656 NamedDecl *PartiallySubstitutedPack =
657 S.CurrentInstantiationScope->getPartiallySubstitutedPack(
658 &ExplicitArgs, &NumExplicitArgs);
659 if (PartiallySubstitutedPack &&
660 getDepthAndIndex(PartiallySubstitutedPack) ==
661 std::make_pair(Info.getDeducedDepth(), Pack.Index))
662 Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs);
667 ~PackDeductionScope() {
668 for (auto &Pack : Packs)
669 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
672 /// Move to deducing the next element in each pack that is being deduced.
673 void nextPackElement() {
674 // Capture the deduced template arguments for each parameter pack expanded
675 // by this pack expansion, add them to the list of arguments we've deduced
676 // for that pack, then clear out the deduced argument.
677 for (auto &Pack : Packs) {
678 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
679 if (!Pack.New.empty() || !DeducedArg.isNull()) {
680 while (Pack.New.size() < PackElements)
681 Pack.New.push_back(DeducedTemplateArgument());
682 Pack.New.push_back(DeducedArg);
683 DeducedArg = DeducedTemplateArgument();
689 /// \brief Finish template argument deduction for a set of argument packs,
690 /// producing the argument packs and checking for consistency with prior
692 Sema::TemplateDeductionResult finish() {
693 // Build argument packs for each of the parameter packs expanded by this
695 for (auto &Pack : Packs) {
696 // Put back the old value for this pack.
697 Deduced[Pack.Index] = Pack.Saved;
699 // Build or find a new value for this pack.
700 DeducedTemplateArgument NewPack;
701 if (PackElements && Pack.New.empty()) {
702 if (Pack.DeferredDeduction.isNull()) {
703 // We were not able to deduce anything for this parameter pack
704 // (because it only appeared in non-deduced contexts), so just
705 // restore the saved argument pack.
709 NewPack = Pack.DeferredDeduction;
710 Pack.DeferredDeduction = TemplateArgument();
711 } else if (Pack.New.empty()) {
712 // If we deduced an empty argument pack, create it now.
713 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
715 TemplateArgument *ArgumentPack =
716 new (S.Context) TemplateArgument[Pack.New.size()];
717 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
718 NewPack = DeducedTemplateArgument(
719 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
720 Pack.New[0].wasDeducedFromArrayBound());
723 // Pick where we're going to put the merged pack.
724 DeducedTemplateArgument *Loc;
726 if (Pack.Outer->DeferredDeduction.isNull()) {
727 // Defer checking this pack until we have a complete pack to compare
729 Pack.Outer->DeferredDeduction = NewPack;
732 Loc = &Pack.Outer->DeferredDeduction;
734 Loc = &Deduced[Pack.Index];
737 // Check the new pack matches any previous value.
738 DeducedTemplateArgument OldPack = *Loc;
739 DeducedTemplateArgument Result =
740 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
742 // If we deferred a deduction of this pack, check that one now too.
743 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
745 NewPack = Pack.DeferredDeduction;
746 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
749 if (Result.isNull()) {
751 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
752 Info.FirstArg = OldPack;
753 Info.SecondArg = NewPack;
754 return Sema::TDK_Inconsistent;
760 return Sema::TDK_Success;
765 TemplateParameterList *TemplateParams;
766 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
767 TemplateDeductionInfo &Info;
768 unsigned PackElements = 0;
770 SmallVector<DeducedPack, 2> Packs;
774 /// \brief Deduce the template arguments by comparing the list of parameter
775 /// types to the list of argument types, as in the parameter-type-lists of
776 /// function types (C++ [temp.deduct.type]p10).
778 /// \param S The semantic analysis object within which we are deducing
780 /// \param TemplateParams The template parameters that we are deducing
782 /// \param Params The list of parameter types
784 /// \param NumParams The number of types in \c Params
786 /// \param Args The list of argument types
788 /// \param NumArgs The number of types in \c Args
790 /// \param Info information about the template argument deduction itself
792 /// \param Deduced the deduced template arguments
794 /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
795 /// how template argument deduction is performed.
797 /// \param PartialOrdering If true, we are performing template argument
798 /// deduction for during partial ordering for a call
799 /// (C++0x [temp.deduct.partial]).
801 /// \returns the result of template argument deduction so far. Note that a
802 /// "success" result means that template argument deduction has not yet failed,
803 /// but it may still fail, later, for other reasons.
804 static Sema::TemplateDeductionResult
805 DeduceTemplateArguments(Sema &S,
806 TemplateParameterList *TemplateParams,
807 const QualType *Params, unsigned NumParams,
808 const QualType *Args, unsigned NumArgs,
809 TemplateDeductionInfo &Info,
810 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
812 bool PartialOrdering = false) {
813 // Fast-path check to see if we have too many/too few arguments.
814 if (NumParams != NumArgs &&
815 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
816 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
817 return Sema::TDK_MiscellaneousDeductionFailure;
819 // C++0x [temp.deduct.type]p10:
820 // Similarly, if P has a form that contains (T), then each parameter type
821 // Pi of the respective parameter-type- list of P is compared with the
822 // corresponding parameter type Ai of the corresponding parameter-type-list
824 unsigned ArgIdx = 0, ParamIdx = 0;
825 for (; ParamIdx != NumParams; ++ParamIdx) {
826 // Check argument types.
827 const PackExpansionType *Expansion
828 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
830 // Simple case: compare the parameter and argument types at this point.
832 // Make sure we have an argument.
833 if (ArgIdx >= NumArgs)
834 return Sema::TDK_MiscellaneousDeductionFailure;
836 if (isa<PackExpansionType>(Args[ArgIdx])) {
837 // C++0x [temp.deduct.type]p22:
838 // If the original function parameter associated with A is a function
839 // parameter pack and the function parameter associated with P is not
840 // a function parameter pack, then template argument deduction fails.
841 return Sema::TDK_MiscellaneousDeductionFailure;
844 if (Sema::TemplateDeductionResult Result
845 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
846 Params[ParamIdx], Args[ArgIdx],
855 // C++0x [temp.deduct.type]p5:
856 // The non-deduced contexts are:
857 // - A function parameter pack that does not occur at the end of the
858 // parameter-declaration-clause.
859 if (ParamIdx + 1 < NumParams)
860 return Sema::TDK_Success;
862 // C++0x [temp.deduct.type]p10:
863 // If the parameter-declaration corresponding to Pi is a function
864 // parameter pack, then the type of its declarator- id is compared with
865 // each remaining parameter type in the parameter-type-list of A. Each
866 // comparison deduces template arguments for subsequent positions in the
867 // template parameter packs expanded by the function parameter pack.
869 QualType Pattern = Expansion->getPattern();
870 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
872 for (; ArgIdx < NumArgs; ++ArgIdx) {
873 // Deduce template arguments from the pattern.
874 if (Sema::TemplateDeductionResult Result
875 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
876 Args[ArgIdx], Info, Deduced,
877 TDF, PartialOrdering))
880 PackScope.nextPackElement();
883 // Build argument packs for each of the parameter packs expanded by this
885 if (auto Result = PackScope.finish())
889 // Make sure we don't have any extra arguments.
890 if (ArgIdx < NumArgs)
891 return Sema::TDK_MiscellaneousDeductionFailure;
893 return Sema::TDK_Success;
896 /// \brief Determine whether the parameter has qualifiers that are either
897 /// inconsistent with or a superset of the argument's qualifiers.
898 static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
900 Qualifiers ParamQs = ParamType.getQualifiers();
901 Qualifiers ArgQs = ArgType.getQualifiers();
903 if (ParamQs == ArgQs)
906 // Mismatched (but not missing) Objective-C GC attributes.
907 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
908 ParamQs.hasObjCGCAttr())
911 // Mismatched (but not missing) address spaces.
912 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
913 ParamQs.hasAddressSpace())
916 // Mismatched (but not missing) Objective-C lifetime qualifiers.
917 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
918 ParamQs.hasObjCLifetime())
921 // CVR qualifier superset.
922 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
923 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
924 == ParamQs.getCVRQualifiers());
927 /// \brief Compare types for equality with respect to possibly compatible
928 /// function types (noreturn adjustment, implicit calling conventions). If any
929 /// of parameter and argument is not a function, just perform type comparison.
931 /// \param Param the template parameter type.
933 /// \param Arg the argument type.
934 bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
936 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
937 *ArgFunction = Arg->getAs<FunctionType>();
939 // Just compare if not functions.
940 if (!ParamFunction || !ArgFunction)
943 // Noreturn and noexcept adjustment.
944 QualType AdjustedParam;
945 if (IsFunctionConversion(Param, Arg, AdjustedParam))
946 return Arg == Context.getCanonicalType(AdjustedParam);
948 // FIXME: Compatible calling conventions.
953 /// \brief Deduce the template arguments by comparing the parameter type and
954 /// the argument type (C++ [temp.deduct.type]).
956 /// \param S the semantic analysis object within which we are deducing
958 /// \param TemplateParams the template parameters that we are deducing
960 /// \param ParamIn the parameter type
962 /// \param ArgIn the argument type
964 /// \param Info information about the template argument deduction itself
966 /// \param Deduced the deduced template arguments
968 /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
969 /// how template argument deduction is performed.
971 /// \param PartialOrdering Whether we're performing template argument deduction
972 /// in the context of partial ordering (C++0x [temp.deduct.partial]).
974 /// \returns the result of template argument deduction so far. Note that a
975 /// "success" result means that template argument deduction has not yet failed,
976 /// but it may still fail, later, for other reasons.
977 static Sema::TemplateDeductionResult
978 DeduceTemplateArgumentsByTypeMatch(Sema &S,
979 TemplateParameterList *TemplateParams,
980 QualType ParamIn, QualType ArgIn,
981 TemplateDeductionInfo &Info,
982 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
984 bool PartialOrdering,
985 bool DeducedFromArrayBound) {
986 // We only want to look at the canonical types, since typedefs and
987 // sugar are not part of template argument deduction.
988 QualType Param = S.Context.getCanonicalType(ParamIn);
989 QualType Arg = S.Context.getCanonicalType(ArgIn);
991 // If the argument type is a pack expansion, look at its pattern.
992 // This isn't explicitly called out
993 if (const PackExpansionType *ArgExpansion
994 = dyn_cast<PackExpansionType>(Arg))
995 Arg = ArgExpansion->getPattern();
997 if (PartialOrdering) {
998 // C++11 [temp.deduct.partial]p5:
999 // Before the partial ordering is done, certain transformations are
1000 // performed on the types used for partial ordering:
1001 // - If P is a reference type, P is replaced by the type referred to.
1002 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1004 Param = ParamRef->getPointeeType();
1006 // - If A is a reference type, A is replaced by the type referred to.
1007 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1009 Arg = ArgRef->getPointeeType();
1011 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1012 // C++11 [temp.deduct.partial]p9:
1013 // If, for a given type, deduction succeeds in both directions (i.e.,
1014 // the types are identical after the transformations above) and both
1015 // P and A were reference types [...]:
1016 // - if [one type] was an lvalue reference and [the other type] was
1017 // not, [the other type] is not considered to be at least as
1018 // specialized as [the first type]
1019 // - if [one type] is more cv-qualified than [the other type],
1020 // [the other type] is not considered to be at least as specialized
1021 // as [the first type]
1022 // Objective-C ARC adds:
1023 // - [one type] has non-trivial lifetime, [the other type] has
1024 // __unsafe_unretained lifetime, and the types are otherwise
1027 // A is "considered to be at least as specialized" as P iff deduction
1028 // succeeds, so we model this as a deduction failure. Note that
1029 // [the first type] is P and [the other type] is A here; the standard
1030 // gets this backwards.
1031 Qualifiers ParamQuals = Param.getQualifiers();
1032 Qualifiers ArgQuals = Arg.getQualifiers();
1033 if ((ParamRef->isLValueReferenceType() &&
1034 !ArgRef->isLValueReferenceType()) ||
1035 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1036 (ParamQuals.hasNonTrivialObjCLifetime() &&
1037 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1038 ParamQuals.withoutObjCLifetime() ==
1039 ArgQuals.withoutObjCLifetime())) {
1040 Info.FirstArg = TemplateArgument(ParamIn);
1041 Info.SecondArg = TemplateArgument(ArgIn);
1042 return Sema::TDK_NonDeducedMismatch;
1046 // C++11 [temp.deduct.partial]p7:
1047 // Remove any top-level cv-qualifiers:
1048 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
1050 Param = Param.getUnqualifiedType();
1051 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
1053 Arg = Arg.getUnqualifiedType();
1055 // C++0x [temp.deduct.call]p4 bullet 1:
1056 // - If the original P is a reference type, the deduced A (i.e., the type
1057 // referred to by the reference) can be more cv-qualified than the
1059 if (TDF & TDF_ParamWithReferenceType) {
1061 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1062 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
1063 Arg.getCVRQualifiers());
1064 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1067 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1068 // C++0x [temp.deduct.type]p10:
1069 // If P and A are function types that originated from deduction when
1070 // taking the address of a function template (14.8.2.2) or when deducing
1071 // template arguments from a function declaration (14.8.2.6) and Pi and
1072 // Ai are parameters of the top-level parameter-type-list of P and A,
1073 // respectively, Pi is adjusted if it is an rvalue reference to a
1074 // cv-unqualified template parameter and Ai is an lvalue reference, in
1075 // which case the type of Pi is changed to be the template parameter
1076 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1077 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
1078 // deduced as X&. - end note ]
1079 TDF &= ~TDF_TopLevelParameterTypeList;
1081 if (const RValueReferenceType *ParamRef
1082 = Param->getAs<RValueReferenceType>()) {
1083 if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
1084 !ParamRef->getPointeeType().getQualifiers())
1085 if (Arg->isLValueReferenceType())
1086 Param = ParamRef->getPointeeType();
1091 // C++ [temp.deduct.type]p9:
1092 // A template type argument T, a template template argument TT or a
1093 // template non-type argument i can be deduced if P and A have one of
1094 // the following forms:
1098 if (const TemplateTypeParmType *TemplateTypeParm
1099 = Param->getAs<TemplateTypeParmType>()) {
1100 // Just skip any attempts to deduce from a placeholder type or a parameter
1101 // at a different depth.
1102 if (Arg->isPlaceholderType() ||
1103 Info.getDeducedDepth() != TemplateTypeParm->getDepth())
1104 return Sema::TDK_Success;
1106 unsigned Index = TemplateTypeParm->getIndex();
1107 bool RecanonicalizeArg = false;
1109 // If the argument type is an array type, move the qualifiers up to the
1110 // top level, so they can be matched with the qualifiers on the parameter.
1111 if (isa<ArrayType>(Arg)) {
1113 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
1115 Arg = S.Context.getQualifiedType(Arg, Quals);
1116 RecanonicalizeArg = true;
1120 // The argument type can not be less qualified than the parameter
1122 if (!(TDF & TDF_IgnoreQualifiers) &&
1123 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
1124 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1125 Info.FirstArg = TemplateArgument(Param);
1126 Info.SecondArg = TemplateArgument(Arg);
1127 return Sema::TDK_Underqualified;
1130 assert(TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&
1131 "saw template type parameter with wrong depth");
1132 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
1133 QualType DeducedType = Arg;
1135 // Remove any qualifiers on the parameter from the deduced type.
1136 // We checked the qualifiers for consistency above.
1137 Qualifiers DeducedQs = DeducedType.getQualifiers();
1138 Qualifiers ParamQs = Param.getQualifiers();
1139 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1140 if (ParamQs.hasObjCGCAttr())
1141 DeducedQs.removeObjCGCAttr();
1142 if (ParamQs.hasAddressSpace())
1143 DeducedQs.removeAddressSpace();
1144 if (ParamQs.hasObjCLifetime())
1145 DeducedQs.removeObjCLifetime();
1148 // If template deduction would produce a lifetime qualifier on a type
1149 // that is not a lifetime type, template argument deduction fails.
1150 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1151 !DeducedType->isDependentType()) {
1152 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1153 Info.FirstArg = TemplateArgument(Param);
1154 Info.SecondArg = TemplateArgument(Arg);
1155 return Sema::TDK_Underqualified;
1159 // If template deduction would produce an argument type with lifetime type
1160 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1161 if (S.getLangOpts().ObjCAutoRefCount &&
1162 DeducedType->isObjCLifetimeType() &&
1163 !DeducedQs.hasObjCLifetime())
1164 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
1166 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1169 if (RecanonicalizeArg)
1170 DeducedType = S.Context.getCanonicalType(DeducedType);
1172 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
1173 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
1176 if (Result.isNull()) {
1177 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1178 Info.FirstArg = Deduced[Index];
1179 Info.SecondArg = NewDeduced;
1180 return Sema::TDK_Inconsistent;
1183 Deduced[Index] = Result;
1184 return Sema::TDK_Success;
1187 // Set up the template argument deduction information for a failure.
1188 Info.FirstArg = TemplateArgument(ParamIn);
1189 Info.SecondArg = TemplateArgument(ArgIn);
1191 // If the parameter is an already-substituted template parameter
1192 // pack, do nothing: we don't know which of its arguments to look
1193 // at, so we have to wait until all of the parameter packs in this
1194 // expansion have arguments.
1195 if (isa<SubstTemplateTypeParmPackType>(Param))
1196 return Sema::TDK_Success;
1198 // Check the cv-qualifiers on the parameter and argument types.
1199 CanQualType CanParam = S.Context.getCanonicalType(Param);
1200 CanQualType CanArg = S.Context.getCanonicalType(Arg);
1201 if (!(TDF & TDF_IgnoreQualifiers)) {
1202 if (TDF & TDF_ParamWithReferenceType) {
1203 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
1204 return Sema::TDK_NonDeducedMismatch;
1205 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
1206 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
1207 return Sema::TDK_NonDeducedMismatch;
1210 // If the parameter type is not dependent, there is nothing to deduce.
1211 if (!Param->isDependentType()) {
1212 if (!(TDF & TDF_SkipNonDependent)) {
1213 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1214 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1217 return Sema::TDK_NonDeducedMismatch;
1220 return Sema::TDK_Success;
1222 } else if (!Param->isDependentType()) {
1223 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1224 ArgUnqualType = CanArg.getUnqualifiedType();
1225 bool Success = (TDF & TDF_InOverloadResolution)?
1226 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1228 ParamUnqualType == ArgUnqualType;
1230 return Sema::TDK_Success;
1233 switch (Param->getTypeClass()) {
1234 // Non-canonical types cannot appear here.
1235 #define NON_CANONICAL_TYPE(Class, Base) \
1236 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1237 #define TYPE(Class, Base)
1238 #include "clang/AST/TypeNodes.def"
1240 case Type::TemplateTypeParm:
1241 case Type::SubstTemplateTypeParmPack:
1242 llvm_unreachable("Type nodes handled above");
1244 // These types cannot be dependent, so simply check whether the types are
1247 case Type::VariableArray:
1249 case Type::FunctionNoProto:
1252 case Type::ObjCObject:
1253 case Type::ObjCInterface:
1254 case Type::ObjCObjectPointer: {
1255 if (TDF & TDF_SkipNonDependent)
1256 return Sema::TDK_Success;
1258 if (TDF & TDF_IgnoreQualifiers) {
1259 Param = Param.getUnqualifiedType();
1260 Arg = Arg.getUnqualifiedType();
1263 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1266 // _Complex T [placeholder extension]
1268 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
1269 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1270 cast<ComplexType>(Param)->getElementType(),
1271 ComplexArg->getElementType(),
1272 Info, Deduced, TDF);
1274 return Sema::TDK_NonDeducedMismatch;
1276 // _Atomic T [extension]
1278 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
1279 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1280 cast<AtomicType>(Param)->getValueType(),
1281 AtomicArg->getValueType(),
1282 Info, Deduced, TDF);
1284 return Sema::TDK_NonDeducedMismatch;
1287 case Type::Pointer: {
1288 QualType PointeeType;
1289 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1290 PointeeType = PointerArg->getPointeeType();
1291 } else if (const ObjCObjectPointerType *PointerArg
1292 = Arg->getAs<ObjCObjectPointerType>()) {
1293 PointeeType = PointerArg->getPointeeType();
1295 return Sema::TDK_NonDeducedMismatch;
1298 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
1299 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1300 cast<PointerType>(Param)->getPointeeType(),
1302 Info, Deduced, SubTDF);
1306 case Type::LValueReference: {
1307 const LValueReferenceType *ReferenceArg =
1308 Arg->getAs<LValueReferenceType>();
1310 return Sema::TDK_NonDeducedMismatch;
1312 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1313 cast<LValueReferenceType>(Param)->getPointeeType(),
1314 ReferenceArg->getPointeeType(), Info, Deduced, 0);
1318 case Type::RValueReference: {
1319 const RValueReferenceType *ReferenceArg =
1320 Arg->getAs<RValueReferenceType>();
1322 return Sema::TDK_NonDeducedMismatch;
1324 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1325 cast<RValueReferenceType>(Param)->getPointeeType(),
1326 ReferenceArg->getPointeeType(),
1330 // T [] (implied, but not stated explicitly)
1331 case Type::IncompleteArray: {
1332 const IncompleteArrayType *IncompleteArrayArg =
1333 S.Context.getAsIncompleteArrayType(Arg);
1334 if (!IncompleteArrayArg)
1335 return Sema::TDK_NonDeducedMismatch;
1337 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1338 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1339 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1340 IncompleteArrayArg->getElementType(),
1341 Info, Deduced, SubTDF);
1344 // T [integer-constant]
1345 case Type::ConstantArray: {
1346 const ConstantArrayType *ConstantArrayArg =
1347 S.Context.getAsConstantArrayType(Arg);
1348 if (!ConstantArrayArg)
1349 return Sema::TDK_NonDeducedMismatch;
1351 const ConstantArrayType *ConstantArrayParm =
1352 S.Context.getAsConstantArrayType(Param);
1353 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
1354 return Sema::TDK_NonDeducedMismatch;
1356 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1357 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1358 ConstantArrayParm->getElementType(),
1359 ConstantArrayArg->getElementType(),
1360 Info, Deduced, SubTDF);
1364 case Type::DependentSizedArray: {
1365 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
1367 return Sema::TDK_NonDeducedMismatch;
1369 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1371 // Check the element type of the arrays
1372 const DependentSizedArrayType *DependentArrayParm
1373 = S.Context.getAsDependentSizedArrayType(Param);
1374 if (Sema::TemplateDeductionResult Result
1375 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1376 DependentArrayParm->getElementType(),
1377 ArrayArg->getElementType(),
1378 Info, Deduced, SubTDF))
1381 // Determine the array bound is something we can deduce.
1382 NonTypeTemplateParmDecl *NTTP
1383 = getDeducedParameterFromExpr(Info, DependentArrayParm->getSizeExpr());
1385 return Sema::TDK_Success;
1387 // We can perform template argument deduction for the given non-type
1388 // template parameter.
1389 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1390 "saw non-type template parameter with wrong depth");
1391 if (const ConstantArrayType *ConstantArrayArg
1392 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1393 llvm::APSInt Size(ConstantArrayArg->getSize());
1394 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
1395 S.Context.getSizeType(),
1396 /*ArrayBound=*/true,
1399 if (const DependentSizedArrayType *DependentArrayArg
1400 = dyn_cast<DependentSizedArrayType>(ArrayArg))
1401 if (DependentArrayArg->getSizeExpr())
1402 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1403 DependentArrayArg->getSizeExpr(),
1406 // Incomplete type does not match a dependently-sized array type
1407 return Sema::TDK_NonDeducedMismatch;
1413 case Type::FunctionProto: {
1414 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
1415 const FunctionProtoType *FunctionProtoArg =
1416 dyn_cast<FunctionProtoType>(Arg);
1417 if (!FunctionProtoArg)
1418 return Sema::TDK_NonDeducedMismatch;
1420 const FunctionProtoType *FunctionProtoParam =
1421 cast<FunctionProtoType>(Param);
1423 if (FunctionProtoParam->getTypeQuals()
1424 != FunctionProtoArg->getTypeQuals() ||
1425 FunctionProtoParam->getRefQualifier()
1426 != FunctionProtoArg->getRefQualifier() ||
1427 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
1428 return Sema::TDK_NonDeducedMismatch;
1430 // Check return types.
1431 if (Sema::TemplateDeductionResult Result =
1432 DeduceTemplateArgumentsByTypeMatch(
1433 S, TemplateParams, FunctionProtoParam->getReturnType(),
1434 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
1437 return DeduceTemplateArguments(
1438 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1439 FunctionProtoParam->getNumParams(),
1440 FunctionProtoArg->param_type_begin(),
1441 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
1444 case Type::InjectedClassName: {
1445 // Treat a template's injected-class-name as if the template
1446 // specialization type had been used.
1447 Param = cast<InjectedClassNameType>(Param)
1448 ->getInjectedSpecializationType();
1449 assert(isa<TemplateSpecializationType>(Param) &&
1450 "injected class name is not a template specialization type");
1454 // template-name<T> (where template-name refers to a class template)
1459 case Type::TemplateSpecialization: {
1460 const TemplateSpecializationType *SpecParam =
1461 cast<TemplateSpecializationType>(Param);
1463 // When Arg cannot be a derived class, we can just try to deduce template
1464 // arguments from the template-id.
1465 const RecordType *RecordT = Arg->getAs<RecordType>();
1466 if (!(TDF & TDF_DerivedClass) || !RecordT)
1467 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1470 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1473 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1474 S, TemplateParams, SpecParam, Arg, Info, Deduced);
1476 if (Result == Sema::TDK_Success)
1479 // We cannot inspect base classes as part of deduction when the type
1480 // is incomplete, so either instantiate any templates necessary to
1481 // complete the type, or skip over it if it cannot be completed.
1482 if (!S.isCompleteType(Info.getLocation(), Arg))
1485 // C++14 [temp.deduct.call] p4b3:
1486 // If P is a class and P has the form simple-template-id, then the
1487 // transformed A can be a derived class of the deduced A. Likewise if
1488 // P is a pointer to a class of the form simple-template-id, the
1489 // transformed A can be a pointer to a derived class pointed to by the
1492 // These alternatives are considered only if type deduction would
1493 // otherwise fail. If they yield more than one possible deduced A, the
1494 // type deduction fails.
1496 // Reset the incorrectly deduced argument from above.
1497 Deduced = DeducedOrig;
1499 // Use data recursion to crawl through the list of base classes.
1500 // Visited contains the set of nodes we have already visited, while
1501 // ToVisit is our stack of records that we still need to visit.
1502 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1503 SmallVector<const RecordType *, 8> ToVisit;
1504 ToVisit.push_back(RecordT);
1505 bool Successful = false;
1506 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
1507 while (!ToVisit.empty()) {
1508 // Retrieve the next class in the inheritance hierarchy.
1509 const RecordType *NextT = ToVisit.pop_back_val();
1511 // If we have already seen this type, skip it.
1512 if (!Visited.insert(NextT).second)
1515 // If this is a base class, try to perform template argument
1516 // deduction from it.
1517 if (NextT != RecordT) {
1518 TemplateDeductionInfo BaseInfo(Info.getLocation());
1519 Sema::TemplateDeductionResult BaseResult =
1520 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1521 QualType(NextT, 0), BaseInfo, Deduced);
1523 // If template argument deduction for this base was successful,
1524 // note that we had some success. Otherwise, ignore any deductions
1525 // from this base class.
1526 if (BaseResult == Sema::TDK_Success) {
1527 // If we've already seen some success, then deduction fails due to
1528 // an ambiguity (temp.deduct.call p5).
1530 return Sema::TDK_MiscellaneousDeductionFailure;
1533 std::swap(SuccessfulDeduced, Deduced);
1535 Info.Param = BaseInfo.Param;
1536 Info.FirstArg = BaseInfo.FirstArg;
1537 Info.SecondArg = BaseInfo.SecondArg;
1540 Deduced = DeducedOrig;
1543 // Visit base classes
1544 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1545 for (const auto &Base : Next->bases()) {
1546 assert(Base.getType()->isRecordType() &&
1547 "Base class that isn't a record?");
1548 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1553 std::swap(SuccessfulDeduced, Deduced);
1554 return Sema::TDK_Success;
1564 // type (type::*)(T)
1569 case Type::MemberPointer: {
1570 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1571 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1573 return Sema::TDK_NonDeducedMismatch;
1575 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1576 if (ParamPointeeType->isFunctionType())
1577 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1578 /*IsCtorOrDtor=*/false, Info.getLocation());
1579 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1580 if (ArgPointeeType->isFunctionType())
1581 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1582 /*IsCtorOrDtor=*/false, Info.getLocation());
1584 if (Sema::TemplateDeductionResult Result
1585 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1589 TDF & TDF_IgnoreQualifiers))
1592 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1593 QualType(MemPtrParam->getClass(), 0),
1594 QualType(MemPtrArg->getClass(), 0),
1596 TDF & TDF_IgnoreQualifiers);
1599 // (clang extension)
1604 case Type::BlockPointer: {
1605 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1606 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
1609 return Sema::TDK_NonDeducedMismatch;
1611 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1612 BlockPtrParam->getPointeeType(),
1613 BlockPtrArg->getPointeeType(),
1617 // (clang extension)
1619 // T __attribute__(((ext_vector_type(<integral constant>))))
1620 case Type::ExtVector: {
1621 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1622 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1623 // Make sure that the vectors have the same number of elements.
1624 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1625 return Sema::TDK_NonDeducedMismatch;
1627 // Perform deduction on the element types.
1628 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1629 VectorParam->getElementType(),
1630 VectorArg->getElementType(),
1631 Info, Deduced, TDF);
1634 if (const DependentSizedExtVectorType *VectorArg
1635 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1636 // We can't check the number of elements, since the argument has a
1637 // dependent number of elements. This can only occur during partial
1640 // Perform deduction on the element types.
1641 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1642 VectorParam->getElementType(),
1643 VectorArg->getElementType(),
1644 Info, Deduced, TDF);
1647 return Sema::TDK_NonDeducedMismatch;
1650 // (clang extension)
1652 // T __attribute__(((ext_vector_type(N))))
1653 case Type::DependentSizedExtVector: {
1654 const DependentSizedExtVectorType *VectorParam
1655 = cast<DependentSizedExtVectorType>(Param);
1657 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1658 // Perform deduction on the element types.
1659 if (Sema::TemplateDeductionResult Result
1660 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1661 VectorParam->getElementType(),
1662 VectorArg->getElementType(),
1663 Info, Deduced, TDF))
1666 // Perform deduction on the vector size, if we can.
1667 NonTypeTemplateParmDecl *NTTP
1668 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
1670 return Sema::TDK_Success;
1672 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1673 ArgSize = VectorArg->getNumElements();
1674 // Note that we use the "array bound" rules here; just like in that
1675 // case, we don't have any particular type for the vector size, but
1676 // we can provide one if necessary.
1677 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
1678 S.Context.IntTy, true, Info,
1682 if (const DependentSizedExtVectorType *VectorArg
1683 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1684 // Perform deduction on the element types.
1685 if (Sema::TemplateDeductionResult Result
1686 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1687 VectorParam->getElementType(),
1688 VectorArg->getElementType(),
1689 Info, Deduced, TDF))
1692 // Perform deduction on the vector size, if we can.
1693 NonTypeTemplateParmDecl *NTTP
1694 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
1696 return Sema::TDK_Success;
1698 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1699 VectorArg->getSizeExpr(),
1703 return Sema::TDK_NonDeducedMismatch;
1706 case Type::TypeOfExpr:
1708 case Type::DependentName:
1709 case Type::UnresolvedUsing:
1710 case Type::Decltype:
1711 case Type::UnaryTransform:
1713 case Type::DependentTemplateSpecialization:
1714 case Type::PackExpansion:
1716 // No template argument deduction for these types
1717 return Sema::TDK_Success;
1720 llvm_unreachable("Invalid Type Class!");
1723 static Sema::TemplateDeductionResult
1724 DeduceTemplateArguments(Sema &S,
1725 TemplateParameterList *TemplateParams,
1726 const TemplateArgument &Param,
1727 TemplateArgument Arg,
1728 TemplateDeductionInfo &Info,
1729 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
1730 // If the template argument is a pack expansion, perform template argument
1731 // deduction against the pattern of that expansion. This only occurs during
1732 // partial ordering.
1733 if (Arg.isPackExpansion())
1734 Arg = Arg.getPackExpansionPattern();
1736 switch (Param.getKind()) {
1737 case TemplateArgument::Null:
1738 llvm_unreachable("Null template argument in parameter list");
1740 case TemplateArgument::Type:
1741 if (Arg.getKind() == TemplateArgument::Type)
1742 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1746 Info.FirstArg = Param;
1747 Info.SecondArg = Arg;
1748 return Sema::TDK_NonDeducedMismatch;
1750 case TemplateArgument::Template:
1751 if (Arg.getKind() == TemplateArgument::Template)
1752 return DeduceTemplateArguments(S, TemplateParams,
1753 Param.getAsTemplate(),
1754 Arg.getAsTemplate(), Info, Deduced);
1755 Info.FirstArg = Param;
1756 Info.SecondArg = Arg;
1757 return Sema::TDK_NonDeducedMismatch;
1759 case TemplateArgument::TemplateExpansion:
1760 llvm_unreachable("caller should handle pack expansions");
1762 case TemplateArgument::Declaration:
1763 if (Arg.getKind() == TemplateArgument::Declaration &&
1764 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
1765 return Sema::TDK_Success;
1767 Info.FirstArg = Param;
1768 Info.SecondArg = Arg;
1769 return Sema::TDK_NonDeducedMismatch;
1771 case TemplateArgument::NullPtr:
1772 if (Arg.getKind() == TemplateArgument::NullPtr &&
1773 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
1774 return Sema::TDK_Success;
1776 Info.FirstArg = Param;
1777 Info.SecondArg = Arg;
1778 return Sema::TDK_NonDeducedMismatch;
1780 case TemplateArgument::Integral:
1781 if (Arg.getKind() == TemplateArgument::Integral) {
1782 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
1783 return Sema::TDK_Success;
1785 Info.FirstArg = Param;
1786 Info.SecondArg = Arg;
1787 return Sema::TDK_NonDeducedMismatch;
1790 if (Arg.getKind() == TemplateArgument::Expression) {
1791 Info.FirstArg = Param;
1792 Info.SecondArg = Arg;
1793 return Sema::TDK_NonDeducedMismatch;
1796 Info.FirstArg = Param;
1797 Info.SecondArg = Arg;
1798 return Sema::TDK_NonDeducedMismatch;
1800 case TemplateArgument::Expression: {
1801 if (NonTypeTemplateParmDecl *NTTP
1802 = getDeducedParameterFromExpr(Info, Param.getAsExpr())) {
1803 if (Arg.getKind() == TemplateArgument::Integral)
1804 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1805 Arg.getAsIntegral(),
1806 Arg.getIntegralType(),
1807 /*ArrayBound=*/false,
1809 if (Arg.getKind() == TemplateArgument::NullPtr)
1810 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
1811 Arg.getNullPtrType(),
1813 if (Arg.getKind() == TemplateArgument::Expression)
1814 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1815 Arg.getAsExpr(), Info, Deduced);
1816 if (Arg.getKind() == TemplateArgument::Declaration)
1817 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1819 Arg.getParamTypeForDecl(),
1822 Info.FirstArg = Param;
1823 Info.SecondArg = Arg;
1824 return Sema::TDK_NonDeducedMismatch;
1827 // Can't deduce anything, but that's okay.
1828 return Sema::TDK_Success;
1830 case TemplateArgument::Pack:
1831 llvm_unreachable("Argument packs should be expanded by the caller!");
1834 llvm_unreachable("Invalid TemplateArgument Kind!");
1837 /// \brief Determine whether there is a template argument to be used for
1840 /// This routine "expands" argument packs in-place, overriding its input
1841 /// parameters so that \c Args[ArgIdx] will be the available template argument.
1843 /// \returns true if there is another template argument (which will be at
1844 /// \c Args[ArgIdx]), false otherwise.
1845 static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
1847 if (ArgIdx == Args.size())
1850 const TemplateArgument &Arg = Args[ArgIdx];
1851 if (Arg.getKind() != TemplateArgument::Pack)
1854 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
1855 Args = Arg.pack_elements();
1857 return ArgIdx < Args.size();
1860 /// \brief Determine whether the given set of template arguments has a pack
1861 /// expansion that is not the last template argument.
1862 static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
1863 bool FoundPackExpansion = false;
1864 for (const auto &A : Args) {
1865 if (FoundPackExpansion)
1868 if (A.getKind() == TemplateArgument::Pack)
1869 return hasPackExpansionBeforeEnd(A.pack_elements());
1871 if (A.isPackExpansion())
1872 FoundPackExpansion = true;
1878 static Sema::TemplateDeductionResult
1879 DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
1880 ArrayRef<TemplateArgument> Params,
1881 ArrayRef<TemplateArgument> Args,
1882 TemplateDeductionInfo &Info,
1883 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1884 bool NumberOfArgumentsMustMatch) {
1885 // C++0x [temp.deduct.type]p9:
1886 // If the template argument list of P contains a pack expansion that is not
1887 // the last template argument, the entire template argument list is a
1888 // non-deduced context.
1889 if (hasPackExpansionBeforeEnd(Params))
1890 return Sema::TDK_Success;
1892 // C++0x [temp.deduct.type]p9:
1893 // If P has a form that contains <T> or <i>, then each argument Pi of the
1894 // respective template argument list P is compared with the corresponding
1895 // argument Ai of the corresponding template argument list of A.
1896 unsigned ArgIdx = 0, ParamIdx = 0;
1897 for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) {
1898 if (!Params[ParamIdx].isPackExpansion()) {
1899 // The simple case: deduce template arguments by matching Pi and Ai.
1901 // Check whether we have enough arguments.
1902 if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
1903 return NumberOfArgumentsMustMatch
1904 ? Sema::TDK_MiscellaneousDeductionFailure
1905 : Sema::TDK_Success;
1907 // C++1z [temp.deduct.type]p9:
1908 // During partial ordering, if Ai was originally a pack expansion [and]
1909 // Pi is not a pack expansion, template argument deduction fails.
1910 if (Args[ArgIdx].isPackExpansion())
1911 return Sema::TDK_MiscellaneousDeductionFailure;
1913 // Perform deduction for this Pi/Ai pair.
1914 if (Sema::TemplateDeductionResult Result
1915 = DeduceTemplateArguments(S, TemplateParams,
1916 Params[ParamIdx], Args[ArgIdx],
1920 // Move to the next argument.
1925 // The parameter is a pack expansion.
1927 // C++0x [temp.deduct.type]p9:
1928 // If Pi is a pack expansion, then the pattern of Pi is compared with
1929 // each remaining argument in the template argument list of A. Each
1930 // comparison deduces template arguments for subsequent positions in the
1931 // template parameter packs expanded by Pi.
1932 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
1934 // FIXME: If there are no remaining arguments, we can bail out early
1935 // and set any deduced parameter packs to an empty argument pack.
1936 // The latter part of this is a (minor) correctness issue.
1938 // Prepare to deduce the packs within the pattern.
1939 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
1941 // Keep track of the deduced template arguments for each parameter pack
1942 // expanded by this pack expansion (the outer index) and for each
1943 // template argument (the inner SmallVectors).
1944 for (; hasTemplateArgumentForDeduction(Args, ArgIdx); ++ArgIdx) {
1945 // Deduce template arguments from the pattern.
1946 if (Sema::TemplateDeductionResult Result
1947 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1951 PackScope.nextPackElement();
1954 // Build argument packs for each of the parameter packs expanded by this
1956 if (auto Result = PackScope.finish())
1960 return Sema::TDK_Success;
1963 static Sema::TemplateDeductionResult
1964 DeduceTemplateArguments(Sema &S,
1965 TemplateParameterList *TemplateParams,
1966 const TemplateArgumentList &ParamList,
1967 const TemplateArgumentList &ArgList,
1968 TemplateDeductionInfo &Info,
1969 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
1970 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
1971 ArgList.asArray(), Info, Deduced,
1972 /*NumberOfArgumentsMustMatch*/false);
1975 /// \brief Determine whether two template arguments are the same.
1976 static bool isSameTemplateArg(ASTContext &Context,
1978 const TemplateArgument &Y,
1979 bool PackExpansionMatchesPack = false) {
1980 // If we're checking deduced arguments (X) against original arguments (Y),
1981 // we will have flattened packs to non-expansions in X.
1982 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
1983 X = X.getPackExpansionPattern();
1985 if (X.getKind() != Y.getKind())
1988 switch (X.getKind()) {
1989 case TemplateArgument::Null:
1990 llvm_unreachable("Comparing NULL template argument");
1992 case TemplateArgument::Type:
1993 return Context.getCanonicalType(X.getAsType()) ==
1994 Context.getCanonicalType(Y.getAsType());
1996 case TemplateArgument::Declaration:
1997 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
1999 case TemplateArgument::NullPtr:
2000 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
2002 case TemplateArgument::Template:
2003 case TemplateArgument::TemplateExpansion:
2004 return Context.getCanonicalTemplateName(
2005 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2006 Context.getCanonicalTemplateName(
2007 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
2009 case TemplateArgument::Integral:
2010 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
2012 case TemplateArgument::Expression: {
2013 llvm::FoldingSetNodeID XID, YID;
2014 X.getAsExpr()->Profile(XID, Context, true);
2015 Y.getAsExpr()->Profile(YID, Context, true);
2019 case TemplateArgument::Pack:
2020 if (X.pack_size() != Y.pack_size())
2023 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2024 XPEnd = X.pack_end(),
2025 YP = Y.pack_begin();
2026 XP != XPEnd; ++XP, ++YP)
2027 if (!isSameTemplateArg(Context, *XP, *YP, PackExpansionMatchesPack))
2033 llvm_unreachable("Invalid TemplateArgument Kind!");
2036 /// \brief Allocate a TemplateArgumentLoc where all locations have
2037 /// been initialized to the given location.
2039 /// \param Arg The template argument we are producing template argument
2040 /// location information for.
2042 /// \param NTTPType For a declaration template argument, the type of
2043 /// the non-type template parameter that corresponds to this template
2044 /// argument. Can be null if no type sugar is available to add to the
2045 /// type from the template argument.
2047 /// \param Loc The source location to use for the resulting template
2050 Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2051 QualType NTTPType, SourceLocation Loc) {
2052 switch (Arg.getKind()) {
2053 case TemplateArgument::Null:
2054 llvm_unreachable("Can't get a NULL template argument here");
2056 case TemplateArgument::Type:
2057 return TemplateArgumentLoc(
2058 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
2060 case TemplateArgument::Declaration: {
2061 if (NTTPType.isNull())
2062 NTTPType = Arg.getParamTypeForDecl();
2063 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2065 return TemplateArgumentLoc(TemplateArgument(E), E);
2068 case TemplateArgument::NullPtr: {
2069 if (NTTPType.isNull())
2070 NTTPType = Arg.getNullPtrType();
2071 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2073 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2077 case TemplateArgument::Integral: {
2079 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
2080 return TemplateArgumentLoc(TemplateArgument(E), E);
2083 case TemplateArgument::Template:
2084 case TemplateArgument::TemplateExpansion: {
2085 NestedNameSpecifierLocBuilder Builder;
2086 TemplateName Template = Arg.getAsTemplate();
2087 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
2088 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
2089 else if (QualifiedTemplateName *QTN =
2090 Template.getAsQualifiedTemplateName())
2091 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
2093 if (Arg.getKind() == TemplateArgument::Template)
2094 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
2097 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
2101 case TemplateArgument::Expression:
2102 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2104 case TemplateArgument::Pack:
2105 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2108 llvm_unreachable("Invalid TemplateArgument Kind!");
2112 /// \brief Convert the given deduced template argument and add it to the set of
2113 /// fully-converted template arguments.
2115 ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2116 DeducedTemplateArgument Arg,
2117 NamedDecl *Template,
2118 TemplateDeductionInfo &Info,
2120 SmallVectorImpl<TemplateArgument> &Output) {
2121 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2122 unsigned ArgumentPackIndex) {
2123 // Convert the deduced template argument into a template
2124 // argument that we can check, almost as if the user had written
2125 // the template argument explicitly.
2126 TemplateArgumentLoc ArgLoc =
2127 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
2129 // Check the template argument, converting it as necessary.
2130 return S.CheckTemplateArgument(
2131 Param, ArgLoc, Template, Template->getLocation(),
2132 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
2134 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2135 : Sema::CTAK_Deduced)
2136 : Sema::CTAK_Specified);
2139 if (Arg.getKind() == TemplateArgument::Pack) {
2140 // This is a template argument pack, so check each of its arguments against
2141 // the template parameter.
2142 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
2143 for (const auto &P : Arg.pack_elements()) {
2144 // When converting the deduced template argument, append it to the
2145 // general output list. We need to do this so that the template argument
2146 // checking logic has all of the prior template arguments available.
2147 DeducedTemplateArgument InnerArg(P);
2148 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
2149 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2150 "deduced nested pack");
2152 // We deduced arguments for some elements of this pack, but not for
2153 // all of them. This happens if we get a conditionally-non-deduced
2154 // context in a pack expansion (such as an overload set in one of the
2156 S.Diag(Param->getLocation(),
2157 diag::err_template_arg_deduced_incomplete_pack)
2161 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
2164 // Move the converted template argument into our argument pack.
2165 PackedArgsBuilder.push_back(Output.pop_back_val());
2168 // If the pack is empty, we still need to substitute into the parameter
2169 // itself, in case that substitution fails.
2170 if (PackedArgsBuilder.empty()) {
2171 LocalInstantiationScope Scope(S);
2172 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
2173 MultiLevelTemplateArgumentList Args(TemplateArgs);
2175 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2176 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2178 Template->getSourceRange());
2179 if (Inst.isInvalid() ||
2180 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2181 NTTP->getDeclName()).isNull())
2183 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2184 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2186 Template->getSourceRange());
2187 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2190 // For type parameters, no substitution is ever required.
2193 // Create the resulting argument pack.
2195 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
2199 return ConvertArg(Arg, 0);
2202 // FIXME: This should not be a template, but
2203 // ClassTemplatePartialSpecializationDecl sadly does not derive from
2205 template<typename TemplateDeclT>
2206 static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
2207 Sema &S, TemplateDeclT *Template, bool IsDeduced,
2208 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2209 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2210 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
2211 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2212 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2214 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2215 NamedDecl *Param = TemplateParams->getParam(I);
2217 if (!Deduced[I].isNull()) {
2218 if (I < NumAlreadyConverted) {
2219 // We may have had explicitly-specified template arguments for a
2220 // template parameter pack (that may or may not have been extended
2221 // via additional deduced arguments).
2222 if (Param->isParameterPack() && CurrentInstantiationScope &&
2223 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2224 // Forget the partially-substituted pack; its substitution is now
2226 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2227 // We still need to check the argument in case it was extended by
2230 // We have already fully type-checked and converted this
2231 // argument, because it was explicitly-specified. Just record the
2232 // presence of this argument.
2233 Builder.push_back(Deduced[I]);
2238 // We may have deduced this argument, so it still needs to be
2239 // checked and converted.
2240 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
2241 IsDeduced, Builder)) {
2242 Info.Param = makeTemplateParameter(Param);
2243 // FIXME: These template arguments are temporary. Free them!
2244 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2245 return Sema::TDK_SubstitutionFailure;
2251 // C++0x [temp.arg.explicit]p3:
2252 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2253 // be deduced to an empty sequence of template arguments.
2254 // FIXME: Where did the word "trailing" come from?
2255 if (Param->isTemplateParameterPack()) {
2256 // We may have had explicitly-specified template arguments for this
2257 // template parameter pack. If so, our empty deduction extends the
2258 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2259 const TemplateArgument *ExplicitArgs;
2260 unsigned NumExplicitArgs;
2261 if (CurrentInstantiationScope &&
2262 CurrentInstantiationScope->getPartiallySubstitutedPack(
2263 &ExplicitArgs, &NumExplicitArgs) == Param) {
2264 Builder.push_back(TemplateArgument(
2265 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
2267 // Forget the partially-substituted pack; its substitution is now
2269 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2271 // Go through the motions of checking the empty argument pack against
2272 // the parameter pack.
2273 DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
2274 if (ConvertDeducedTemplateArgument(S, Param, DeducedPack, Template,
2275 Info, IsDeduced, Builder)) {
2276 Info.Param = makeTemplateParameter(Param);
2277 // FIXME: These template arguments are temporary. Free them!
2278 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2279 return Sema::TDK_SubstitutionFailure;
2285 // Substitute into the default template argument, if available.
2286 bool HasDefaultArg = false;
2287 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2289 assert(isa<ClassTemplatePartialSpecializationDecl>(Template));
2290 return Sema::TDK_Incomplete;
2293 TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2294 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2297 // If there was no default argument, deduction is incomplete.
2298 if (DefArg.getArgument().isNull()) {
2299 Info.Param = makeTemplateParameter(
2300 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2301 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2302 if (PartialOverloading) break;
2304 return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2305 : Sema::TDK_Incomplete;
2308 // Check whether we can actually use the default argument.
2309 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2310 TD->getSourceRange().getEnd(), 0, Builder,
2311 Sema::CTAK_Specified)) {
2312 Info.Param = makeTemplateParameter(
2313 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2314 // FIXME: These template arguments are temporary. Free them!
2315 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2316 return Sema::TDK_SubstitutionFailure;
2319 // If we get here, we successfully used the default template argument.
2322 return Sema::TDK_Success;
2325 DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
2326 if (auto *DC = dyn_cast<DeclContext>(D))
2328 return D->getDeclContext();
2331 template<typename T> struct IsPartialSpecialization {
2332 static constexpr bool value = false;
2335 struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
2336 static constexpr bool value = true;
2339 struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
2340 static constexpr bool value = true;
2343 /// Complete template argument deduction for a partial specialization.
2344 template <typename T>
2345 static typename std::enable_if<IsPartialSpecialization<T>::value,
2346 Sema::TemplateDeductionResult>::type
2347 FinishTemplateArgumentDeduction(
2348 Sema &S, T *Partial, bool IsPartialOrdering,
2349 const TemplateArgumentList &TemplateArgs,
2350 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2351 TemplateDeductionInfo &Info) {
2352 // Unevaluated SFINAE context.
2353 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2354 Sema::SFINAETrap Trap(S);
2356 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
2358 // C++ [temp.deduct.type]p2:
2359 // [...] or if any template argument remains neither deduced nor
2360 // explicitly specified, template argument deduction fails.
2361 SmallVector<TemplateArgument, 4> Builder;
2362 if (auto Result = ConvertDeducedTemplateArguments(
2363 S, Partial, IsPartialOrdering, Deduced, Info, Builder))
2366 // Form the template argument list from the deduced template arguments.
2367 TemplateArgumentList *DeducedArgumentList
2368 = TemplateArgumentList::CreateCopy(S.Context, Builder);
2370 Info.reset(DeducedArgumentList);
2372 // Substitute the deduced template arguments into the template
2373 // arguments of the class template partial specialization, and
2374 // verify that the instantiated template arguments are both valid
2375 // and are equivalent to the template arguments originally provided
2376 // to the class template.
2377 LocalInstantiationScope InstScope(S);
2378 auto *Template = Partial->getSpecializedTemplate();
2379 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2380 Partial->getTemplateArgsAsWritten();
2381 const TemplateArgumentLoc *PartialTemplateArgs =
2382 PartialTemplArgInfo->getTemplateArgs();
2384 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2385 PartialTemplArgInfo->RAngleLoc);
2387 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
2388 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2389 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2390 if (ParamIdx >= Partial->getTemplateParameters()->size())
2391 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2393 Decl *Param = const_cast<NamedDecl *>(
2394 Partial->getTemplateParameters()->getParam(ParamIdx));
2395 Info.Param = makeTemplateParameter(Param);
2396 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2397 return Sema::TDK_SubstitutionFailure;
2400 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2401 if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2402 false, ConvertedInstArgs))
2403 return Sema::TDK_SubstitutionFailure;
2405 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2406 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2407 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2408 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2409 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2410 Info.FirstArg = TemplateArgs[I];
2411 Info.SecondArg = InstArg;
2412 return Sema::TDK_NonDeducedMismatch;
2416 if (Trap.hasErrorOccurred())
2417 return Sema::TDK_SubstitutionFailure;
2419 return Sema::TDK_Success;
2422 /// Complete template argument deduction for a class or variable template,
2423 /// when partial ordering against a partial specialization.
2424 // FIXME: Factor out duplication with partial specialization version above.
2425 Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2426 Sema &S, TemplateDecl *Template, bool PartialOrdering,
2427 const TemplateArgumentList &TemplateArgs,
2428 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2429 TemplateDeductionInfo &Info) {
2430 // Unevaluated SFINAE context.
2431 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
2432 Sema::SFINAETrap Trap(S);
2434 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
2436 // C++ [temp.deduct.type]p2:
2437 // [...] or if any template argument remains neither deduced nor
2438 // explicitly specified, template argument deduction fails.
2439 SmallVector<TemplateArgument, 4> Builder;
2440 if (auto Result = ConvertDeducedTemplateArguments(
2441 S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder))
2444 // Check that we produced the correct argument list.
2445 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2446 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2447 TemplateArgument InstArg = Builder[I];
2448 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
2449 /*PackExpansionMatchesPack*/true)) {
2450 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2451 Info.FirstArg = TemplateArgs[I];
2452 Info.SecondArg = InstArg;
2453 return Sema::TDK_NonDeducedMismatch;
2457 if (Trap.hasErrorOccurred())
2458 return Sema::TDK_SubstitutionFailure;
2460 return Sema::TDK_Success;
2464 /// \brief Perform template argument deduction to determine whether
2465 /// the given template arguments match the given class template
2466 /// partial specialization per C++ [temp.class.spec.match].
2467 Sema::TemplateDeductionResult
2468 Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
2469 const TemplateArgumentList &TemplateArgs,
2470 TemplateDeductionInfo &Info) {
2471 if (Partial->isInvalidDecl())
2474 // C++ [temp.class.spec.match]p2:
2475 // A partial specialization matches a given actual template
2476 // argument list if the template arguments of the partial
2477 // specialization can be deduced from the actual template argument
2480 // Unevaluated SFINAE context.
2481 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2482 SFINAETrap Trap(*this);
2484 SmallVector<DeducedTemplateArgument, 4> Deduced;
2485 Deduced.resize(Partial->getTemplateParameters()->size());
2486 if (TemplateDeductionResult Result
2487 = ::DeduceTemplateArguments(*this,
2488 Partial->getTemplateParameters(),
2489 Partial->getTemplateArgs(),
2490 TemplateArgs, Info, Deduced))
2493 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2494 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2496 if (Inst.isInvalid())
2497 return TDK_InstantiationDepth;
2499 if (Trap.hasErrorOccurred())
2500 return Sema::TDK_SubstitutionFailure;
2502 return ::FinishTemplateArgumentDeduction(
2503 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
2506 /// \brief Perform template argument deduction to determine whether
2507 /// the given template arguments match the given variable template
2508 /// partial specialization per C++ [temp.class.spec.match].
2509 Sema::TemplateDeductionResult
2510 Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2511 const TemplateArgumentList &TemplateArgs,
2512 TemplateDeductionInfo &Info) {
2513 if (Partial->isInvalidDecl())
2516 // C++ [temp.class.spec.match]p2:
2517 // A partial specialization matches a given actual template
2518 // argument list if the template arguments of the partial
2519 // specialization can be deduced from the actual template argument
2522 // Unevaluated SFINAE context.
2523 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2524 SFINAETrap Trap(*this);
2526 SmallVector<DeducedTemplateArgument, 4> Deduced;
2527 Deduced.resize(Partial->getTemplateParameters()->size());
2528 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2529 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2530 TemplateArgs, Info, Deduced))
2533 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2534 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2536 if (Inst.isInvalid())
2537 return TDK_InstantiationDepth;
2539 if (Trap.hasErrorOccurred())
2540 return Sema::TDK_SubstitutionFailure;
2542 return ::FinishTemplateArgumentDeduction(
2543 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
2546 /// \brief Determine whether the given type T is a simple-template-id type.
2547 static bool isSimpleTemplateIdType(QualType T) {
2548 if (const TemplateSpecializationType *Spec
2549 = T->getAs<TemplateSpecializationType>())
2550 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
2555 /// \brief Substitute the explicitly-provided template arguments into the
2556 /// given function template according to C++ [temp.arg.explicit].
2558 /// \param FunctionTemplate the function template into which the explicit
2559 /// template arguments will be substituted.
2561 /// \param ExplicitTemplateArgs the explicitly-specified template
2564 /// \param Deduced the deduced template arguments, which will be populated
2565 /// with the converted and checked explicit template arguments.
2567 /// \param ParamTypes will be populated with the instantiated function
2570 /// \param FunctionType if non-NULL, the result type of the function template
2571 /// will also be instantiated and the pointed-to value will be updated with
2572 /// the instantiated function type.
2574 /// \param Info if substitution fails for any reason, this object will be
2575 /// populated with more information about the failure.
2577 /// \returns TDK_Success if substitution was successful, or some failure
2579 Sema::TemplateDeductionResult
2580 Sema::SubstituteExplicitTemplateArguments(
2581 FunctionTemplateDecl *FunctionTemplate,
2582 TemplateArgumentListInfo &ExplicitTemplateArgs,
2583 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2584 SmallVectorImpl<QualType> &ParamTypes,
2585 QualType *FunctionType,
2586 TemplateDeductionInfo &Info) {
2587 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2588 TemplateParameterList *TemplateParams
2589 = FunctionTemplate->getTemplateParameters();
2591 if (ExplicitTemplateArgs.size() == 0) {
2592 // No arguments to substitute; just copy over the parameter types and
2593 // fill in the function type.
2594 for (auto P : Function->parameters())
2595 ParamTypes.push_back(P->getType());
2598 *FunctionType = Function->getType();
2602 // Unevaluated SFINAE context.
2603 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2604 SFINAETrap Trap(*this);
2606 // C++ [temp.arg.explicit]p3:
2607 // Template arguments that are present shall be specified in the
2608 // declaration order of their corresponding template-parameters. The
2609 // template argument list shall not specify more template-arguments than
2610 // there are corresponding template-parameters.
2611 SmallVector<TemplateArgument, 4> Builder;
2613 // Enter a new template instantiation context where we check the
2614 // explicitly-specified template arguments against this function template,
2615 // and then substitute them into the function parameter types.
2616 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2617 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2619 ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution,
2621 if (Inst.isInvalid())
2622 return TDK_InstantiationDepth;
2624 if (CheckTemplateArgumentList(FunctionTemplate,
2626 ExplicitTemplateArgs,
2628 Builder) || Trap.hasErrorOccurred()) {
2629 unsigned Index = Builder.size();
2630 if (Index >= TemplateParams->size())
2631 Index = TemplateParams->size() - 1;
2632 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
2633 return TDK_InvalidExplicitArguments;
2636 // Form the template argument list from the explicitly-specified
2637 // template arguments.
2638 TemplateArgumentList *ExplicitArgumentList
2639 = TemplateArgumentList::CreateCopy(Context, Builder);
2640 Info.reset(ExplicitArgumentList);
2642 // Template argument deduction and the final substitution should be
2643 // done in the context of the templated declaration. Explicit
2644 // argument substitution, on the other hand, needs to happen in the
2646 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2648 // If we deduced template arguments for a template parameter pack,
2649 // note that the template argument pack is partially substituted and record
2650 // the explicit template arguments. They'll be used as part of deduction
2651 // for this template parameter pack.
2652 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2653 const TemplateArgument &Arg = Builder[I];
2654 if (Arg.getKind() == TemplateArgument::Pack) {
2655 CurrentInstantiationScope->SetPartiallySubstitutedPack(
2656 TemplateParams->getParam(I),
2663 const FunctionProtoType *Proto
2664 = Function->getType()->getAs<FunctionProtoType>();
2665 assert(Proto && "Function template does not have a prototype?");
2667 // Isolate our substituted parameters from our caller.
2668 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2670 ExtParameterInfoBuilder ExtParamInfos;
2672 // Instantiate the types of each of the function parameters given the
2673 // explicitly-specified template arguments. If the function has a trailing
2674 // return type, substitute it after the arguments to ensure we substitute
2675 // in lexical order.
2676 if (Proto->hasTrailingReturn()) {
2677 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
2678 Proto->getExtParameterInfosOrNull(),
2679 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2680 ParamTypes, /*params*/ nullptr, ExtParamInfos))
2681 return TDK_SubstitutionFailure;
2684 // Instantiate the return type.
2685 QualType ResultType;
2687 // C++11 [expr.prim.general]p3:
2688 // If a declaration declares a member function or member function
2689 // template of a class X, the expression this is a prvalue of type
2690 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2691 // and the end of the function-definition, member-declarator, or
2693 unsigned ThisTypeQuals = 0;
2694 CXXRecordDecl *ThisContext = nullptr;
2695 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2696 ThisContext = Method->getParent();
2697 ThisTypeQuals = Method->getTypeQualifiers();
2700 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
2701 getLangOpts().CPlusPlus11);
2704 SubstType(Proto->getReturnType(),
2705 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2706 Function->getTypeSpecStartLoc(), Function->getDeclName());
2707 if (ResultType.isNull() || Trap.hasErrorOccurred())
2708 return TDK_SubstitutionFailure;
2711 // Instantiate the types of each of the function parameters given the
2712 // explicitly-specified template arguments if we didn't do so earlier.
2713 if (!Proto->hasTrailingReturn() &&
2714 SubstParmTypes(Function->getLocation(), Function->parameters(),
2715 Proto->getExtParameterInfosOrNull(),
2716 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2717 ParamTypes, /*params*/ nullptr, ExtParamInfos))
2718 return TDK_SubstitutionFailure;
2721 auto EPI = Proto->getExtProtoInfo();
2722 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
2723 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
2724 Function->getLocation(),
2725 Function->getDeclName(),
2727 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2728 return TDK_SubstitutionFailure;
2731 // C++ [temp.arg.explicit]p2:
2732 // Trailing template arguments that can be deduced (14.8.2) may be
2733 // omitted from the list of explicit template-arguments. If all of the
2734 // template arguments can be deduced, they may all be omitted; in this
2735 // case, the empty template argument list <> itself may also be omitted.
2737 // Take all of the explicitly-specified arguments and put them into
2738 // the set of deduced template arguments. Explicitly-specified
2739 // parameter packs, however, will be set to NULL since the deduction
2740 // mechanisms handle explicitly-specified argument packs directly.
2741 Deduced.reserve(TemplateParams->size());
2742 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2743 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2744 if (Arg.getKind() == TemplateArgument::Pack)
2745 Deduced.push_back(DeducedTemplateArgument());
2747 Deduced.push_back(Arg);
2753 /// \brief Check whether the deduced argument type for a call to a function
2754 /// template matches the actual argument type per C++ [temp.deduct.call]p4.
2756 CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
2757 QualType DeducedA) {
2758 ASTContext &Context = S.Context;
2760 QualType A = OriginalArg.OriginalArgType;
2761 QualType OriginalParamType = OriginalArg.OriginalParamType;
2763 // Check for type equality (top-level cv-qualifiers are ignored).
2764 if (Context.hasSameUnqualifiedType(A, DeducedA))
2767 // Strip off references on the argument types; they aren't needed for
2768 // the following checks.
2769 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2770 DeducedA = DeducedARef->getPointeeType();
2771 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2772 A = ARef->getPointeeType();
2774 // C++ [temp.deduct.call]p4:
2775 // [...] However, there are three cases that allow a difference:
2776 // - If the original P is a reference type, the deduced A (i.e., the
2777 // type referred to by the reference) can be more cv-qualified than
2778 // the transformed A.
2779 if (const ReferenceType *OriginalParamRef
2780 = OriginalParamType->getAs<ReferenceType>()) {
2781 // We don't want to keep the reference around any more.
2782 OriginalParamType = OriginalParamRef->getPointeeType();
2784 // FIXME: Resolve core issue (no number yet): if the original P is a
2785 // reference type and the transformed A is function type "noexcept F",
2786 // the deduced A can be F.
2788 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
2791 Qualifiers AQuals = A.getQualifiers();
2792 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
2794 // Under Objective-C++ ARC, the deduced type may have implicitly
2795 // been given strong or (when dealing with a const reference)
2796 // unsafe_unretained lifetime. If so, update the original
2797 // qualifiers to include this lifetime.
2798 if (S.getLangOpts().ObjCAutoRefCount &&
2799 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2800 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2801 (DeducedAQuals.hasConst() &&
2802 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2803 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
2806 if (AQuals == DeducedAQuals) {
2807 // Qualifiers match; there's nothing to do.
2808 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
2811 // Qualifiers are compatible, so have the argument type adopt the
2812 // deduced argument type's qualifiers as if we had performed the
2813 // qualification conversion.
2814 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2818 // - The transformed A can be another pointer or pointer to member
2819 // type that can be converted to the deduced A via a function pointer
2820 // conversion and/or a qualification conversion.
2822 // Also allow conversions which merely strip __attribute__((noreturn)) from
2823 // function types (recursively).
2824 bool ObjCLifetimeConversion = false;
2826 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
2827 (S.IsQualificationConversion(A, DeducedA, false,
2828 ObjCLifetimeConversion) ||
2829 S.IsFunctionConversion(A, DeducedA, ResultTy)))
2832 // - If P is a class and P has the form simple-template-id, then the
2833 // transformed A can be a derived class of the deduced A. [...]
2834 // [...] Likewise, if P is a pointer to a class of the form
2835 // simple-template-id, the transformed A can be a pointer to a
2836 // derived class pointed to by the deduced A.
2837 if (const PointerType *OriginalParamPtr
2838 = OriginalParamType->getAs<PointerType>()) {
2839 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2840 if (const PointerType *APtr = A->getAs<PointerType>()) {
2841 if (A->getPointeeType()->isRecordType()) {
2842 OriginalParamType = OriginalParamPtr->getPointeeType();
2843 DeducedA = DeducedAPtr->getPointeeType();
2844 A = APtr->getPointeeType();
2850 if (Context.hasSameUnqualifiedType(A, DeducedA))
2853 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
2854 S.IsDerivedFrom(SourceLocation(), A, DeducedA))
2860 /// Find the pack index for a particular parameter index in an instantiation of
2861 /// a function template with specific arguments.
2863 /// \return The pack index for whichever pack produced this parameter, or -1
2864 /// if this was not produced by a parameter. Intended to be used as the
2865 /// ArgumentPackSubstitutionIndex for further substitutions.
2866 // FIXME: We should track this in OriginalCallArgs so we don't need to
2867 // reconstruct it here.
2868 static unsigned getPackIndexForParam(Sema &S,
2869 FunctionTemplateDecl *FunctionTemplate,
2870 const MultiLevelTemplateArgumentList &Args,
2871 unsigned ParamIdx) {
2873 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
2874 if (PD->isParameterPack()) {
2875 unsigned NumExpansions =
2876 S.getNumArgumentsInExpansion(PD->getType(), Args).getValueOr(1);
2877 if (Idx + NumExpansions > ParamIdx)
2878 return ParamIdx - Idx;
2879 Idx += NumExpansions;
2881 if (Idx == ParamIdx)
2882 return -1; // Not a pack expansion
2887 llvm_unreachable("parameter index would not be produced from template");
2890 /// \brief Finish template argument deduction for a function template,
2891 /// checking the deduced template arguments for completeness and forming
2892 /// the function template specialization.
2894 /// \param OriginalCallArgs If non-NULL, the original call arguments against
2895 /// which the deduced argument types should be compared.
2896 Sema::TemplateDeductionResult
2897 Sema::FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
2898 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2899 unsigned NumExplicitlySpecified,
2900 FunctionDecl *&Specialization,
2901 TemplateDeductionInfo &Info,
2902 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2903 bool PartialOverloading) {
2904 // Unevaluated SFINAE context.
2905 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
2906 SFINAETrap Trap(*this);
2908 // Enter a new template instantiation context while we instantiate the
2909 // actual function declaration.
2910 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2911 InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2913 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
2915 if (Inst.isInvalid())
2916 return TDK_InstantiationDepth;
2918 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2920 // C++ [temp.deduct.type]p2:
2921 // [...] or if any template argument remains neither deduced nor
2922 // explicitly specified, template argument deduction fails.
2923 SmallVector<TemplateArgument, 4> Builder;
2924 if (auto Result = ConvertDeducedTemplateArguments(
2925 *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder,
2926 CurrentInstantiationScope, NumExplicitlySpecified,
2927 PartialOverloading))
2930 // Form the template argument list from the deduced template arguments.
2931 TemplateArgumentList *DeducedArgumentList
2932 = TemplateArgumentList::CreateCopy(Context, Builder);
2933 Info.reset(DeducedArgumentList);
2935 // Substitute the deduced template arguments into the function template
2936 // declaration to produce the function template specialization.
2937 DeclContext *Owner = FunctionTemplate->getDeclContext();
2938 if (FunctionTemplate->getFriendObjectKind())
2939 Owner = FunctionTemplate->getLexicalDeclContext();
2940 MultiLevelTemplateArgumentList SubstArgs(*DeducedArgumentList);
2941 Specialization = cast_or_null<FunctionDecl>(
2942 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, SubstArgs));
2943 if (!Specialization || Specialization->isInvalidDecl())
2944 return TDK_SubstitutionFailure;
2946 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
2947 FunctionTemplate->getCanonicalDecl());
2949 // If the template argument list is owned by the function template
2950 // specialization, release it.
2951 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2952 !Trap.hasErrorOccurred())
2955 // There may have been an error that did not prevent us from constructing a
2956 // declaration. Mark the declaration invalid and return with a substitution
2958 if (Trap.hasErrorOccurred()) {
2959 Specialization->setInvalidDecl(true);
2960 return TDK_SubstitutionFailure;
2963 if (OriginalCallArgs) {
2964 // C++ [temp.deduct.call]p4:
2965 // In general, the deduction process attempts to find template argument
2966 // values that will make the deduced A identical to A (after the type A
2967 // is transformed as described above). [...]
2968 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
2969 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2970 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
2972 auto ParamIdx = OriginalArg.ArgIdx;
2973 if (ParamIdx >= Specialization->getNumParams())
2974 // FIXME: This presumably means a pack ended up smaller than we
2975 // expected while deducing. Should this not result in deduction
2976 // failure? Can it even happen?
2980 if (!OriginalArg.DecomposedParam) {
2981 // P is one of the function parameters, just look up its substituted
2983 DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
2985 // P is a decomposed element of a parameter corresponding to a
2986 // braced-init-list argument. Substitute back into P to find the
2988 QualType &CacheEntry =
2989 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
2990 if (CacheEntry.isNull()) {
2991 ArgumentPackSubstitutionIndexRAII PackIndex(
2992 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
2995 SubstType(OriginalArg.OriginalParamType, SubstArgs,
2996 Specialization->getTypeSpecStartLoc(),
2997 Specialization->getDeclName());
2999 DeducedA = CacheEntry;
3002 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
3003 Info.FirstArg = TemplateArgument(DeducedA);
3004 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3005 Info.CallArgIndex = OriginalArg.ArgIdx;
3006 return OriginalArg.DecomposedParam ? TDK_DeducedMismatchNested
3007 : TDK_DeducedMismatch;
3012 // If we suppressed any diagnostics while performing template argument
3013 // deduction, and if we haven't already instantiated this declaration,
3014 // keep track of these diagnostics. They'll be emitted if this specialization
3015 // is actually used.
3016 if (Info.diag_begin() != Info.diag_end()) {
3017 SuppressedDiagnosticsMap::iterator
3018 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
3019 if (Pos == SuppressedDiagnostics.end())
3020 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
3021 .append(Info.diag_begin(), Info.diag_end());
3027 /// Gets the type of a function for template-argument-deducton
3028 /// purposes when it's considered as part of an overload set.
3029 static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
3031 // We may need to deduce the return type of the function now.
3032 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
3033 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
3036 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
3037 if (Method->isInstance()) {
3038 // An instance method that's referenced in a form that doesn't
3039 // look like a member pointer is just invalid.
3040 if (!R.HasFormOfMemberPointer) return QualType();
3042 return S.Context.getMemberPointerType(Fn->getType(),
3043 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
3046 if (!R.IsAddressOfOperand) return Fn->getType();
3047 return S.Context.getPointerType(Fn->getType());
3050 /// Apply the deduction rules for overload sets.
3052 /// \return the null type if this argument should be treated as an
3053 /// undeduced context
3055 ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
3056 Expr *Arg, QualType ParamType,
3057 bool ParamWasReference) {
3059 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
3061 OverloadExpr *Ovl = R.Expression;
3063 // C++0x [temp.deduct.call]p4
3065 if (ParamWasReference)
3066 TDF |= TDF_ParamWithReferenceType;
3067 if (R.IsAddressOfOperand)
3068 TDF |= TDF_IgnoreQualifiers;
3070 // C++0x [temp.deduct.call]p6:
3071 // When P is a function type, pointer to function type, or pointer
3072 // to member function type:
3074 if (!ParamType->isFunctionType() &&
3075 !ParamType->isFunctionPointerType() &&
3076 !ParamType->isMemberFunctionPointerType()) {
3077 if (Ovl->hasExplicitTemplateArgs()) {
3078 // But we can still look for an explicit specialization.
3079 if (FunctionDecl *ExplicitSpec
3080 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
3081 return GetTypeOfFunction(S, R, ExplicitSpec);
3085 if (FunctionDecl *Viable =
3086 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3087 return GetTypeOfFunction(S, R, Viable);
3092 // Gather the explicit template arguments, if any.
3093 TemplateArgumentListInfo ExplicitTemplateArgs;
3094 if (Ovl->hasExplicitTemplateArgs())
3095 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
3097 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3098 E = Ovl->decls_end(); I != E; ++I) {
3099 NamedDecl *D = (*I)->getUnderlyingDecl();
3101 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3102 // - If the argument is an overload set containing one or more
3103 // function templates, the parameter is treated as a
3104 // non-deduced context.
3105 if (!Ovl->hasExplicitTemplateArgs())
3108 // Otherwise, see if we can resolve a function type
3109 FunctionDecl *Specialization = nullptr;
3110 TemplateDeductionInfo Info(Ovl->getNameLoc());
3111 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3112 Specialization, Info))
3118 FunctionDecl *Fn = cast<FunctionDecl>(D);
3119 QualType ArgType = GetTypeOfFunction(S, R, Fn);
3120 if (ArgType.isNull()) continue;
3122 // Function-to-pointer conversion.
3123 if (!ParamWasReference && ParamType->isPointerType() &&
3124 ArgType->isFunctionType())
3125 ArgType = S.Context.getPointerType(ArgType);
3127 // - If the argument is an overload set (not containing function
3128 // templates), trial argument deduction is attempted using each
3129 // of the members of the set. If deduction succeeds for only one
3130 // of the overload set members, that member is used as the
3131 // argument value for the deduction. If deduction succeeds for
3132 // more than one member of the overload set the parameter is
3133 // treated as a non-deduced context.
3135 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3136 // Type deduction is done independently for each P/A pair, and
3137 // the deduced template argument values are then combined.
3138 // So we do not reject deductions which were made elsewhere.
3139 SmallVector<DeducedTemplateArgument, 8>
3140 Deduced(TemplateParams->size());
3141 TemplateDeductionInfo Info(Ovl->getNameLoc());
3142 Sema::TemplateDeductionResult Result
3143 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3144 ArgType, Info, Deduced, TDF);
3145 if (Result) continue;
3146 if (!Match.isNull()) return QualType();
3153 /// \brief Perform the adjustments to the parameter and argument types
3154 /// described in C++ [temp.deduct.call].
3156 /// \returns true if the caller should not attempt to perform any template
3157 /// argument deduction based on this P/A pair because the argument is an
3158 /// overloaded function set that could not be resolved.
3159 static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S,
3160 TemplateParameterList *TemplateParams,
3161 QualType &ParamType,
3165 // C++0x [temp.deduct.call]p3:
3166 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
3167 // are ignored for type deduction.
3168 if (ParamType.hasQualifiers())
3169 ParamType = ParamType.getUnqualifiedType();
3171 // [...] If P is a reference type, the type referred to by P is
3172 // used for type deduction.
3173 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
3175 ParamType = ParamRefType->getPointeeType();
3177 // Overload sets usually make this parameter an undeduced context,
3178 // but there are sometimes special circumstances. Typically
3179 // involving a template-id-expr.
3180 if (ArgType == S.Context.OverloadTy) {
3181 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3183 ParamRefType != nullptr);
3184 if (ArgType.isNull())
3189 // If the argument has incomplete array type, try to complete its type.
3190 if (ArgType->isIncompleteArrayType()) {
3191 S.completeExprArrayBound(Arg);
3192 ArgType = Arg->getType();
3195 // C++0x [temp.deduct.call]p3:
3196 // If P is an rvalue reference to a cv-unqualified template
3197 // parameter and the argument is an lvalue, the type "lvalue
3198 // reference to A" is used in place of A for type deduction.
3199 if (ParamRefType->isRValueReferenceType() &&
3200 !ParamType.getQualifiers() &&
3201 isa<TemplateTypeParmType>(ParamType) &&
3203 ArgType = S.Context.getLValueReferenceType(ArgType);
3205 // C++ [temp.deduct.call]p2:
3206 // If P is not a reference type:
3207 // - If A is an array type, the pointer type produced by the
3208 // array-to-pointer standard conversion (4.2) is used in place of
3209 // A for type deduction; otherwise,
3210 if (ArgType->isArrayType())
3211 ArgType = S.Context.getArrayDecayedType(ArgType);
3212 // - If A is a function type, the pointer type produced by the
3213 // function-to-pointer standard conversion (4.3) is used in place
3214 // of A for type deduction; otherwise,
3215 else if (ArgType->isFunctionType())
3216 ArgType = S.Context.getPointerType(ArgType);
3218 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
3219 // type are ignored for type deduction.
3220 ArgType = ArgType.getUnqualifiedType();
3224 // C++0x [temp.deduct.call]p4:
3225 // In general, the deduction process attempts to find template argument
3226 // values that will make the deduced A identical to A (after the type A
3227 // is transformed as described above). [...]
3228 TDF = TDF_SkipNonDependent;
3230 // - If the original P is a reference type, the deduced A (i.e., the
3231 // type referred to by the reference) can be more cv-qualified than
3232 // the transformed A.
3234 TDF |= TDF_ParamWithReferenceType;
3235 // - The transformed A can be another pointer or pointer to member
3236 // type that can be converted to the deduced A via a qualification
3237 // conversion (4.4).
3238 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3239 ArgType->isObjCObjectPointerType())
3240 TDF |= TDF_IgnoreQualifiers;
3241 // - If P is a class and P has the form simple-template-id, then the
3242 // transformed A can be a derived class of the deduced A. Likewise,
3243 // if P is a pointer to a class of the form simple-template-id, the
3244 // transformed A can be a pointer to a derived class pointed to by
3246 if (isSimpleTemplateIdType(ParamType) ||
3247 (isa<PointerType>(ParamType) &&
3248 isSimpleTemplateIdType(
3249 ParamType->getAs<PointerType>()->getPointeeType())))
3250 TDF |= TDF_DerivedClass;
3256 hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3259 static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
3260 Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3261 Expr *Arg, TemplateDeductionInfo &Info,
3262 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3263 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
3264 bool DecomposedParam, unsigned ArgIdx, unsigned TDF);
3266 /// \brief Attempt template argument deduction from an initializer list
3267 /// deemed to be an argument in a function call.
3268 static Sema::TemplateDeductionResult DeduceFromInitializerList(
3269 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
3270 InitListExpr *ILE, TemplateDeductionInfo &Info,
3271 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3272 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
3274 // C++ [temp.deduct.call]p1: (CWG 1591)
3275 // If removing references and cv-qualifiers from P gives
3276 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
3277 // a non-empty initializer list, then deduction is performed instead for
3278 // each element of the initializer list, taking P0 as a function template
3279 // parameter type and the initializer element as its argument
3281 // We've already removed references and cv-qualifiers here.
3282 if (!ILE->getNumInits())
3283 return Sema::TDK_Success;
3286 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
3288 ElTy = ArrTy->getElementType();
3289 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
3290 // Otherwise, an initializer list argument causes the parameter to be
3291 // considered a non-deduced context
3292 return Sema::TDK_Success;
3295 // Deduction only needs to be done for dependent types.
3296 if (ElTy->isDependentType()) {
3297 for (Expr *E : ILE->inits()) {
3298 if (auto Result = DeduceTemplateArgumentsFromCallArgument(
3299 S, TemplateParams, ElTy, E, Info, Deduced, OriginalCallArgs, true,
3305 // in the P0[N] case, if N is a non-type template parameter, N is deduced
3306 // from the length of the initializer list.
3307 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
3308 // Determine the array bound is something we can deduce.
3309 if (NonTypeTemplateParmDecl *NTTP =
3310 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
3311 // We can perform template argument deduction for the given non-type
3312 // template parameter.
3313 llvm::APInt Size(S.Context.getIntWidth(NTTP->getType()),
3314 ILE->getNumInits());
3315 if (auto Result = DeduceNonTypeTemplateArgument(
3316 S, TemplateParams, NTTP, llvm::APSInt(Size), NTTP->getType(),
3317 /*ArrayBound=*/true, Info, Deduced))
3322 return Sema::TDK_Success;
3325 /// \brief Perform template argument deduction per [temp.deduct.call] for a
3326 /// single parameter / argument pair.
3327 static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
3328 Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3329 Expr *Arg, TemplateDeductionInfo &Info,
3330 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3331 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
3332 bool DecomposedParam, unsigned ArgIdx, unsigned TDF) {
3333 QualType ArgType = Arg->getType();
3334 QualType OrigParamType = ParamType;
3336 // If P is a reference type [...]
3337 // If P is a cv-qualified type [...]
3338 if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
3340 return Sema::TDK_Success;
3342 // If [...] the argument is a non-empty initializer list [...]
3343 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg))
3344 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
3345 Deduced, OriginalCallArgs, ArgIdx, TDF);
3347 // [...] the deduction process attempts to find template argument values
3348 // that will make the deduced A identical to A
3350 // Keep track of the argument type and corresponding parameter index,
3351 // so we can check for compatibility between the deduced A and A.
3352 OriginalCallArgs.push_back(
3353 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
3354 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3355 ArgType, Info, Deduced, TDF);
3358 /// \brief Perform template argument deduction from a function call
3359 /// (C++ [temp.deduct.call]).
3361 /// \param FunctionTemplate the function template for which we are performing
3362 /// template argument deduction.
3364 /// \param ExplicitTemplateArgs the explicit template arguments provided
3367 /// \param Args the function call arguments
3369 /// \param Specialization if template argument deduction was successful,
3370 /// this will be set to the function template specialization produced by
3371 /// template argument deduction.
3373 /// \param Info the argument will be updated to provide additional information
3374 /// about template argument deduction.
3376 /// \returns the result of template argument deduction.
3377 Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3378 FunctionTemplateDecl *FunctionTemplate,
3379 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3380 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3381 bool PartialOverloading) {
3382 if (FunctionTemplate->isInvalidDecl())
3385 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3386 unsigned NumParams = Function->getNumParams();
3388 // C++ [temp.deduct.call]p1:
3389 // Template argument deduction is done by comparing each function template
3390 // parameter type (call it P) with the type of the corresponding argument
3391 // of the call (call it A) as described below.
3392 unsigned CheckArgs = Args.size();
3393 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
3394 return TDK_TooFewArguments;
3395 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
3396 const FunctionProtoType *Proto
3397 = Function->getType()->getAs<FunctionProtoType>();
3398 if (Proto->isTemplateVariadic())
3400 else if (Proto->isVariadic())
3401 CheckArgs = NumParams;
3403 return TDK_TooManyArguments;
3406 // The types of the parameters from which we will perform template argument
3408 LocalInstantiationScope InstScope(*this);
3409 TemplateParameterList *TemplateParams
3410 = FunctionTemplate->getTemplateParameters();
3411 SmallVector<DeducedTemplateArgument, 4> Deduced;
3412 SmallVector<QualType, 4> ParamTypes;
3413 unsigned NumExplicitlySpecified = 0;
3414 if (ExplicitTemplateArgs) {
3415 TemplateDeductionResult Result =
3416 SubstituteExplicitTemplateArguments(FunctionTemplate,
3417 *ExplicitTemplateArgs,
3425 NumExplicitlySpecified = Deduced.size();
3427 // Just fill in the parameter types from the function declaration.
3428 for (unsigned I = 0; I != NumParams; ++I)
3429 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3432 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
3434 // Deduce an argument of type ParamType from an expression with index ArgIdx.
3435 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx) {
3436 // C++ [demp.deduct.call]p1: (DR1391)
3437 // Template argument deduction is done by comparing each function template
3438 // parameter that contains template-parameters that participate in
3439 // template argument deduction ...
3440 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3441 return Sema::TDK_Success;
3443 // ... with the type of the corresponding argument
3444 return DeduceTemplateArgumentsFromCallArgument(
3445 *this, TemplateParams, ParamType, Args[ArgIdx], Info, Deduced,
3446 OriginalCallArgs, /*Decomposed*/false, ArgIdx, /*TDF*/ 0);
3449 // Deduce template arguments from the function parameters.
3450 Deduced.resize(TemplateParams->size());
3451 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
3452 ParamIdx != NumParamTypes; ++ParamIdx) {
3453 QualType ParamType = ParamTypes[ParamIdx];
3455 const PackExpansionType *ParamExpansion =
3456 dyn_cast<PackExpansionType>(ParamType);
3457 if (!ParamExpansion) {
3458 // Simple case: matching a function parameter to a function argument.
3459 if (ArgIdx >= CheckArgs)
3462 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++))
3468 // C++0x [temp.deduct.call]p1:
3469 // For a function parameter pack that occurs at the end of the
3470 // parameter-declaration-list, the type A of each remaining argument of
3471 // the call is compared with the type P of the declarator-id of the
3472 // function parameter pack. Each comparison deduces template arguments
3473 // for subsequent positions in the template parameter packs expanded by
3474 // the function parameter pack. For a function parameter pack that does
3475 // not occur at the end of the parameter-declaration-list, the type of
3476 // the parameter pack is a non-deduced context.
3477 // FIXME: This does not say that subsequent parameters are also non-deduced.
3478 // See also DR1388 / DR1399, which effectively says we should keep deducing
3480 if (ParamIdx + 1 < NumParamTypes)
3483 QualType ParamPattern = ParamExpansion->getPattern();
3484 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3487 for (; ArgIdx < Args.size(); PackScope.nextPackElement(), ++ArgIdx)
3488 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx))
3491 // Build argument packs for each of the parameter packs expanded by this
3493 if (auto Result = PackScope.finish())
3496 // After we've matching against a parameter pack, we're done.
3500 return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3501 NumExplicitlySpecified, Specialization,
3502 Info, &OriginalCallArgs,
3503 PartialOverloading);
3506 QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
3507 QualType FunctionType,
3508 bool AdjustExceptionSpec) {
3509 if (ArgFunctionType.isNull())
3510 return ArgFunctionType;
3512 const FunctionProtoType *FunctionTypeP =
3513 FunctionType->castAs<FunctionProtoType>();
3514 const FunctionProtoType *ArgFunctionTypeP =
3515 ArgFunctionType->getAs<FunctionProtoType>();
3517 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
3518 bool Rebuild = false;
3520 CallingConv CC = FunctionTypeP->getCallConv();
3521 if (EPI.ExtInfo.getCC() != CC) {
3522 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
3526 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3527 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
3528 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
3532 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
3533 ArgFunctionTypeP->hasExceptionSpec())) {
3534 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
3539 return ArgFunctionType;
3541 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
3542 ArgFunctionTypeP->getParamTypes(), EPI);
3545 /// \brief Deduce template arguments when taking the address of a function
3546 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3549 /// \param FunctionTemplate the function template for which we are performing
3550 /// template argument deduction.
3552 /// \param ExplicitTemplateArgs the explicitly-specified template
3555 /// \param ArgFunctionType the function type that will be used as the
3556 /// "argument" type (A) when performing template argument deduction from the
3557 /// function template's function type. This type may be NULL, if there is no
3558 /// argument type to compare against, in C++0x [temp.arg.explicit]p3.
3560 /// \param Specialization if template argument deduction was successful,
3561 /// this will be set to the function template specialization produced by
3562 /// template argument deduction.
3564 /// \param Info the argument will be updated to provide additional information
3565 /// about template argument deduction.
3567 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3568 /// the address of a function template per [temp.deduct.funcaddr] and
3569 /// [over.over]. If \c false, we are looking up a function template
3570 /// specialization based on its signature, per [temp.deduct.decl].
3572 /// \returns the result of template argument deduction.
3573 Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3574 FunctionTemplateDecl *FunctionTemplate,
3575 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
3576 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3577 bool IsAddressOfFunction) {
3578 if (FunctionTemplate->isInvalidDecl())
3581 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3582 TemplateParameterList *TemplateParams
3583 = FunctionTemplate->getTemplateParameters();
3584 QualType FunctionType = Function->getType();
3586 // When taking the address of a function, we require convertibility of
3587 // the resulting function type. Otherwise, we allow arbitrary mismatches
3588 // of calling convention, noreturn, and noexcept.
3589 if (!IsAddressOfFunction)
3590 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
3591 /*AdjustExceptionSpec*/true);
3593 // Substitute any explicit template arguments.
3594 LocalInstantiationScope InstScope(*this);
3595 SmallVector<DeducedTemplateArgument, 4> Deduced;
3596 unsigned NumExplicitlySpecified = 0;
3597 SmallVector<QualType, 4> ParamTypes;
3598 if (ExplicitTemplateArgs) {
3599 if (TemplateDeductionResult Result
3600 = SubstituteExplicitTemplateArguments(FunctionTemplate,
3601 *ExplicitTemplateArgs,
3602 Deduced, ParamTypes,
3603 &FunctionType, Info))
3606 NumExplicitlySpecified = Deduced.size();
3609 // Unevaluated SFINAE context.
3610 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
3611 SFINAETrap Trap(*this);
3613 Deduced.resize(TemplateParams->size());
3615 // If the function has a deduced return type, substitute it for a dependent
3616 // type so that we treat it as a non-deduced context in what follows. If we
3617 // are looking up by signature, the signature type should also have a deduced
3618 // return type, which we instead expect to exactly match.
3619 bool HasDeducedReturnType = false;
3620 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
3621 Function->getReturnType()->getContainedAutoType()) {
3622 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
3623 HasDeducedReturnType = true;
3626 if (!ArgFunctionType.isNull()) {
3627 unsigned TDF = TDF_TopLevelParameterTypeList;
3628 if (IsAddressOfFunction)
3629 TDF |= TDF_InOverloadResolution;
3630 // Deduce template arguments from the function type.
3631 if (TemplateDeductionResult Result
3632 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3633 FunctionType, ArgFunctionType,
3634 Info, Deduced, TDF))
3638 if (TemplateDeductionResult Result
3639 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3640 NumExplicitlySpecified,
3641 Specialization, Info))
3644 // If the function has a deduced return type, deduce it now, so we can check
3645 // that the deduced function type matches the requested type.
3646 if (HasDeducedReturnType &&
3647 Specialization->getReturnType()->isUndeducedType() &&
3648 DeduceReturnType(Specialization, Info.getLocation(), false))
3649 return TDK_MiscellaneousDeductionFailure;
3651 // If the function has a dependent exception specification, resolve it now,
3652 // so we can check that the exception specification matches.
3653 auto *SpecializationFPT =
3654 Specialization->getType()->castAs<FunctionProtoType>();
3655 if (getLangOpts().CPlusPlus1z &&
3656 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
3657 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
3658 return TDK_MiscellaneousDeductionFailure;
3660 // Adjust the exception specification of the argument again to match the
3661 // substituted and resolved type we just formed. (Calling convention and
3662 // noreturn can't be dependent, so we don't actually need this for them
3664 QualType SpecializationType = Specialization->getType();
3665 if (!IsAddressOfFunction)
3666 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
3667 /*AdjustExceptionSpec*/true);
3669 // If the requested function type does not match the actual type of the
3670 // specialization with respect to arguments of compatible pointer to function
3671 // types, template argument deduction fails.
3672 if (!ArgFunctionType.isNull()) {
3673 if (IsAddressOfFunction &&
3674 !isSameOrCompatibleFunctionType(
3675 Context.getCanonicalType(SpecializationType),
3676 Context.getCanonicalType(ArgFunctionType)))
3677 return TDK_MiscellaneousDeductionFailure;
3679 if (!IsAddressOfFunction &&
3680 !Context.hasSameType(SpecializationType, ArgFunctionType))
3681 return TDK_MiscellaneousDeductionFailure;
3687 /// \brief Given a function declaration (e.g. a generic lambda conversion
3688 /// function) that contains an 'auto' in its result type, substitute it
3689 /// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3690 /// to replace 'auto' with and not the actual result type you want
3691 /// to set the function to.
3693 SubstAutoWithinFunctionReturnType(FunctionDecl *F,
3694 QualType TypeToReplaceAutoWith, Sema &S) {
3695 assert(!TypeToReplaceAutoWith->getContainedAutoType());
3696 QualType AutoResultType = F->getReturnType();
3697 assert(AutoResultType->getContainedAutoType());
3698 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
3699 TypeToReplaceAutoWith);
3700 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3703 /// \brief Given a specialized conversion operator of a generic lambda
3704 /// create the corresponding specializations of the call operator and
3705 /// the static-invoker. If the return type of the call operator is auto,
3706 /// deduce its return type and check if that matches the
3707 /// return type of the destination function ptr.
3709 static inline Sema::TemplateDeductionResult
3710 SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3711 CXXConversionDecl *ConversionSpecialized,
3712 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3713 QualType ReturnTypeOfDestFunctionPtr,
3714 TemplateDeductionInfo &TDInfo,
3717 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
3718 assert(LambdaClass && LambdaClass->isGenericLambda());
3720 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
3721 QualType CallOpResultType = CallOpGeneric->getReturnType();
3722 const bool GenericLambdaCallOperatorHasDeducedReturnType =
3723 CallOpResultType->getContainedAutoType();
3725 FunctionTemplateDecl *CallOpTemplate =
3726 CallOpGeneric->getDescribedFunctionTemplate();
3728 FunctionDecl *CallOpSpecialized = nullptr;
3729 // Use the deduced arguments of the conversion function, to specialize our
3730 // generic lambda's call operator.
3731 if (Sema::TemplateDeductionResult Result
3732 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3734 0, CallOpSpecialized, TDInfo))
3737 // If we need to deduce the return type, do so (instantiates the callop).
3738 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3739 CallOpSpecialized->getReturnType()->isUndeducedType())
3740 S.DeduceReturnType(CallOpSpecialized,
3741 CallOpSpecialized->getPointOfInstantiation(),
3744 // Check to see if the return type of the destination ptr-to-function
3745 // matches the return type of the call operator.
3746 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
3747 ReturnTypeOfDestFunctionPtr))
3748 return Sema::TDK_NonDeducedMismatch;
3749 // Since we have succeeded in matching the source and destination
3750 // ptr-to-functions (now including return type), and have successfully
3751 // specialized our corresponding call operator, we are ready to
3752 // specialize the static invoker with the deduced arguments of our
3754 FunctionDecl *InvokerSpecialized = nullptr;
3755 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3756 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3759 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3761 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
3762 InvokerSpecialized, TDInfo);
3763 assert(Result == Sema::TDK_Success &&
3764 "If the call operator succeeded so should the invoker!");
3765 // Set the result type to match the corresponding call operator
3766 // specialization's result type.
3767 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3768 InvokerSpecialized->getReturnType()->isUndeducedType()) {
3769 // Be sure to get the type to replace 'auto' with and not
3770 // the full result type of the call op specialization
3771 // to substitute into the 'auto' of the invoker and conversion
3774 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3775 // We don't want to subst 'int*' into 'auto' to get int**.
3777 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3778 ->getContainedAutoType()
3780 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3781 TypeToReplaceAutoWith, S);
3782 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
3783 TypeToReplaceAutoWith, S);
3786 // Ensure that static invoker doesn't have a const qualifier.
3787 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
3788 // do not use the CallOperator's TypeSourceInfo which allows
3789 // the const qualifier to leak through.
3790 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3791 getType().getTypePtr()->castAs<FunctionProtoType>();
3792 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3794 InvokerSpecialized->setType(S.Context.getFunctionType(
3795 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
3796 return Sema::TDK_Success;
3798 /// \brief Deduce template arguments for a templated conversion
3799 /// function (C++ [temp.deduct.conv]) and, if successful, produce a
3800 /// conversion function template specialization.
3801 Sema::TemplateDeductionResult
3802 Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
3804 CXXConversionDecl *&Specialization,
3805 TemplateDeductionInfo &Info) {
3806 if (ConversionTemplate->isInvalidDecl())
3809 CXXConversionDecl *ConversionGeneric
3810 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3812 QualType FromType = ConversionGeneric->getConversionType();
3814 // Canonicalize the types for deduction.
3815 QualType P = Context.getCanonicalType(FromType);
3816 QualType A = Context.getCanonicalType(ToType);
3818 // C++0x [temp.deduct.conv]p2:
3819 // If P is a reference type, the type referred to by P is used for
3821 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3822 P = PRef->getPointeeType();
3824 // C++0x [temp.deduct.conv]p4:
3825 // [...] If A is a reference type, the type referred to by A is used
3826 // for type deduction.
3827 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3828 A = ARef->getPointeeType().getUnqualifiedType();
3829 // C++ [temp.deduct.conv]p3:
3831 // If A is not a reference type:
3833 assert(!A->isReferenceType() && "Reference types were handled above");
3835 // - If P is an array type, the pointer type produced by the
3836 // array-to-pointer standard conversion (4.2) is used in place
3837 // of P for type deduction; otherwise,
3838 if (P->isArrayType())
3839 P = Context.getArrayDecayedType(P);
3840 // - If P is a function type, the pointer type produced by the
3841 // function-to-pointer standard conversion (4.3) is used in
3842 // place of P for type deduction; otherwise,
3843 else if (P->isFunctionType())
3844 P = Context.getPointerType(P);
3845 // - If P is a cv-qualified type, the top level cv-qualifiers of
3846 // P's type are ignored for type deduction.
3848 P = P.getUnqualifiedType();
3850 // C++0x [temp.deduct.conv]p4:
3851 // If A is a cv-qualified type, the top level cv-qualifiers of A's
3852 // type are ignored for type deduction. If A is a reference type, the type
3853 // referred to by A is used for type deduction.
3854 A = A.getUnqualifiedType();
3857 // Unevaluated SFINAE context.
3858 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
3859 SFINAETrap Trap(*this);
3861 // C++ [temp.deduct.conv]p1:
3862 // Template argument deduction is done by comparing the return
3863 // type of the template conversion function (call it P) with the
3864 // type that is required as the result of the conversion (call it
3865 // A) as described in 14.8.2.4.
3866 TemplateParameterList *TemplateParams
3867 = ConversionTemplate->getTemplateParameters();
3868 SmallVector<DeducedTemplateArgument, 4> Deduced;
3869 Deduced.resize(TemplateParams->size());
3871 // C++0x [temp.deduct.conv]p4:
3872 // In general, the deduction process attempts to find template
3873 // argument values that will make the deduced A identical to
3874 // A. However, there are two cases that allow a difference:
3876 // - If the original A is a reference type, A can be more
3877 // cv-qualified than the deduced A (i.e., the type referred to
3878 // by the reference)
3879 if (ToType->isReferenceType())
3880 TDF |= TDF_ParamWithReferenceType;
3881 // - The deduced A can be another pointer or pointer to member
3882 // type that can be converted to A via a qualification
3885 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3886 // both P and A are pointers or member pointers. In this case, we
3887 // just ignore cv-qualifiers completely).
3888 if ((P->isPointerType() && A->isPointerType()) ||
3889 (P->isMemberPointerType() && A->isMemberPointerType()))
3890 TDF |= TDF_IgnoreQualifiers;
3891 if (TemplateDeductionResult Result
3892 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3893 P, A, Info, Deduced, TDF))
3896 // Create an Instantiation Scope for finalizing the operator.
3897 LocalInstantiationScope InstScope(*this);
3898 // Finish template argument deduction.
3899 FunctionDecl *ConversionSpecialized = nullptr;
3900 TemplateDeductionResult Result
3901 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
3902 ConversionSpecialized, Info);
3903 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3905 // If the conversion operator is being invoked on a lambda closure to convert
3906 // to a ptr-to-function, use the deduced arguments from the conversion
3907 // function to specialize the corresponding call operator.
3908 // e.g., int (*fp)(int) = [](auto a) { return a; };
3909 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
3911 // Get the return type of the destination ptr-to-function we are converting
3912 // to. This is necessary for matching the lambda call operator's return
3913 // type to that of the destination ptr-to-function's return type.
3914 assert(A->isPointerType() &&
3915 "Can only convert from lambda to ptr-to-function");
3916 const FunctionType *ToFunType =
3917 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
3918 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3920 // Create the corresponding specializations of the call operator and
3921 // the static-invoker; and if the return type is auto,
3922 // deduce the return type and check if it matches the
3923 // DestFunctionPtrReturnType.
3925 // auto L = [](auto a) { return f(a); };
3926 // int (*fp)(int) = L;
3927 // char (*fp2)(int) = L; <-- Not OK.
3929 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3930 Specialization, Deduced, DestFunctionPtrReturnType,
3936 /// \brief Deduce template arguments for a function template when there is
3937 /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3939 /// \param FunctionTemplate the function template for which we are performing
3940 /// template argument deduction.
3942 /// \param ExplicitTemplateArgs the explicitly-specified template
3945 /// \param Specialization if template argument deduction was successful,
3946 /// this will be set to the function template specialization produced by
3947 /// template argument deduction.
3949 /// \param Info the argument will be updated to provide additional information
3950 /// about template argument deduction.
3952 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3953 /// the address of a function template in a context where we do not have a
3954 /// target type, per [over.over]. If \c false, we are looking up a function
3955 /// template specialization based on its signature, which only happens when
3956 /// deducing a function parameter type from an argument that is a template-id
3957 /// naming a function template specialization.
3959 /// \returns the result of template argument deduction.
3960 Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3961 FunctionTemplateDecl *FunctionTemplate,
3962 TemplateArgumentListInfo *ExplicitTemplateArgs,
3963 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3964 bool IsAddressOfFunction) {
3965 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
3966 QualType(), Specialization, Info,
3967 IsAddressOfFunction);
3971 /// Substitute the 'auto' type specifier within a type for a given replacement
3973 class SubstituteAutoTransform :
3974 public TreeTransform<SubstituteAutoTransform> {
3975 QualType Replacement;
3978 SubstituteAutoTransform(Sema &SemaRef, QualType Replacement,
3979 bool UseAutoSugar = true)
3980 : TreeTransform<SubstituteAutoTransform>(SemaRef),
3981 Replacement(Replacement), UseAutoSugar(UseAutoSugar) {}
3983 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3984 // If we're building the type pattern to deduce against, don't wrap the
3985 // substituted type in an AutoType. Certain template deduction rules
3986 // apply only when a template type parameter appears directly (and not if
3987 // the parameter is found through desugaring). For instance:
3988 // auto &&lref = lvalue;
3989 // must transform into "rvalue reference to T" not "rvalue reference to
3990 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
3991 if (!UseAutoSugar) {
3992 assert(isa<TemplateTypeParmType>(Replacement) &&
3993 "unexpected unsugared replacement kind");
3994 QualType Result = Replacement;
3995 TemplateTypeParmTypeLoc NewTL =
3996 TLB.push<TemplateTypeParmTypeLoc>(Result);
3997 NewTL.setNameLoc(TL.getNameLoc());
4000 QualType Result = SemaRef.Context.getAutoType(
4001 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull());
4002 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
4003 NewTL.setNameLoc(TL.getNameLoc());
4008 ExprResult TransformLambdaExpr(LambdaExpr *E) {
4009 // Lambdas never need to be transformed.
4013 QualType Apply(TypeLoc TL) {
4014 // Create some scratch storage for the transformed type locations.
4015 // FIXME: We're just going to throw this information away. Don't build it.
4017 TLB.reserve(TL.getFullDataSize());
4018 return TransformType(TLB, TL);
4023 Sema::DeduceAutoResult
4024 Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result,
4025 Optional<unsigned> DependentDeductionDepth) {
4026 return DeduceAutoType(Type->getTypeLoc(), Init, Result,
4027 DependentDeductionDepth);
4030 /// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
4032 /// Note that this is done even if the initializer is dependent. (This is
4033 /// necessary to support partial ordering of templates using 'auto'.)
4034 /// A dependent type will be produced when deducing from a dependent type.
4036 /// \param Type the type pattern using the auto type-specifier.
4037 /// \param Init the initializer for the variable whose type is to be deduced.
4038 /// \param Result if type deduction was successful, this will be set to the
4040 /// \param DependentDeductionDepth Set if we should permit deduction in
4041 /// dependent cases. This is necessary for template partial ordering with
4042 /// 'auto' template parameters. The value specified is the template
4043 /// parameter depth at which we should perform 'auto' deduction.
4044 Sema::DeduceAutoResult
4045 Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result,
4046 Optional<unsigned> DependentDeductionDepth) {
4047 if (Init->getType()->isNonOverloadPlaceholderType()) {
4048 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4049 if (NonPlaceholder.isInvalid())
4050 return DAR_FailedAlreadyDiagnosed;
4051 Init = NonPlaceholder.get();
4054 if (!DependentDeductionDepth &&
4055 (Type.getType()->isDependentType() || Init->isTypeDependent())) {
4056 Result = SubstituteAutoTransform(*this, QualType()).Apply(Type);
4057 assert(!Result.isNull() && "substituting DependentTy can't fail");
4058 return DAR_Succeeded;
4061 // Find the depth of template parameter to synthesize.
4062 unsigned Depth = DependentDeductionDepth.getValueOr(0);
4064 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4065 // Since 'decltype(auto)' can only occur at the top of the type, we
4066 // don't need to go digging for it.
4067 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
4068 if (AT->isDecltypeAuto()) {
4069 if (isa<InitListExpr>(Init)) {
4070 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4071 return DAR_FailedAlreadyDiagnosed;
4074 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
4075 if (Deduced.isNull())
4076 return DAR_FailedAlreadyDiagnosed;
4077 // FIXME: Support a non-canonical deduced type for 'auto'.
4078 Deduced = Context.getCanonicalType(Deduced);
4079 Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
4080 if (Result.isNull())
4081 return DAR_FailedAlreadyDiagnosed;
4082 return DAR_Succeeded;
4083 } else if (!getLangOpts().CPlusPlus) {
4084 if (isa<InitListExpr>(Init)) {
4085 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4086 return DAR_FailedAlreadyDiagnosed;
4091 SourceLocation Loc = Init->getExprLoc();
4093 LocalInstantiationScope InstScope(*this);
4095 // Build template<class TemplParam> void Func(FuncParam);
4096 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
4097 Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false);
4098 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4099 NamedDecl *TemplParamPtr = TemplParam;
4100 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4101 Loc, Loc, TemplParamPtr, Loc, nullptr);
4103 QualType FuncParam =
4104 SubstituteAutoTransform(*this, TemplArg, /*UseAutoSugar*/false)
4106 assert(!FuncParam.isNull() &&
4107 "substituting template parameter for 'auto' failed");
4109 // Deduce type of TemplParam in Func(Init)
4110 SmallVector<DeducedTemplateArgument, 1> Deduced;
4113 TemplateDeductionInfo Info(Loc, Depth);
4115 // If deduction failed, don't diagnose if the initializer is dependent; it
4116 // might acquire a matching type in the instantiation.
4117 auto DeductionFailed = [&]() -> DeduceAutoResult {
4118 if (Init->isTypeDependent()) {
4119 Result = SubstituteAutoTransform(*this, QualType()).Apply(Type);
4120 assert(!Result.isNull() && "substituting DependentTy can't fail");
4121 return DAR_Succeeded;
4126 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
4128 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
4130 // Notionally, we substitute std::initializer_list<T> for 'auto' and deduce
4131 // against that. Such deduction only succeeds if removing cv-qualifiers and
4132 // references results in std::initializer_list<T>.
4133 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
4136 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
4137 if (DeduceTemplateArgumentsFromCallArgument(
4138 *this, TemplateParamsSt.get(), TemplArg, InitList->getInit(i),
4139 Info, Deduced, OriginalCallArgs, /*Decomposed*/ true,
4140 /*ArgIdx*/ 0, /*TDF*/ 0))
4141 return DeductionFailed();
4144 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4145 Diag(Loc, diag::err_auto_bitfield);
4146 return DAR_FailedAlreadyDiagnosed;
4149 if (DeduceTemplateArgumentsFromCallArgument(
4150 *this, TemplateParamsSt.get(), FuncParam, Init, Info, Deduced,
4151 OriginalCallArgs, /*Decomposed*/ false, /*ArgIdx*/ 0, /*TDF*/ 0))
4152 return DeductionFailed();
4155 // Could be null if somehow 'auto' appears in a non-deduced context.
4156 if (Deduced[0].getKind() != TemplateArgument::Type)
4157 return DeductionFailed();
4159 QualType DeducedType = Deduced[0].getAsType();
4162 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4163 if (DeducedType.isNull())
4164 return DAR_FailedAlreadyDiagnosed;
4167 Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
4168 if (Result.isNull())
4169 return DAR_FailedAlreadyDiagnosed;
4171 // Check that the deduced argument type is compatible with the original
4172 // argument type per C++ [temp.deduct.call]p4.
4173 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
4174 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
4175 assert((bool)InitList == OriginalArg.DecomposedParam &&
4176 "decomposed non-init-list in auto deduction?");
4177 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
4178 Result = QualType();
4179 return DeductionFailed();
4183 return DAR_Succeeded;
4186 QualType Sema::SubstAutoType(QualType TypeWithAuto,
4187 QualType TypeToReplaceAuto) {
4188 if (TypeToReplaceAuto->isDependentType())
4189 TypeToReplaceAuto = QualType();
4190 return SubstituteAutoTransform(*this, TypeToReplaceAuto)
4191 .TransformType(TypeWithAuto);
4194 TypeSourceInfo* Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4195 QualType TypeToReplaceAuto) {
4196 if (TypeToReplaceAuto->isDependentType())
4197 TypeToReplaceAuto = QualType();
4198 return SubstituteAutoTransform(*this, TypeToReplaceAuto)
4199 .TransformType(TypeWithAuto);
4202 void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4203 if (isa<InitListExpr>(Init))
4204 Diag(VDecl->getLocation(),
4205 VDecl->isInitCapture()
4206 ? diag::err_init_capture_deduction_failure_from_init_list
4207 : diag::err_auto_var_deduction_failure_from_init_list)
4208 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4210 Diag(VDecl->getLocation(),
4211 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4212 : diag::err_auto_var_deduction_failure)
4213 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4214 << Init->getSourceRange();
4217 bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4219 assert(FD->getReturnType()->isUndeducedType());
4221 if (FD->getTemplateInstantiationPattern())
4222 InstantiateFunctionDefinition(Loc, FD);
4224 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
4225 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4226 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4227 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4230 return StillUndeduced;
4234 MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
4237 llvm::SmallBitVector &Deduced);
4239 /// \brief If this is a non-static member function,
4241 AddImplicitObjectParameterType(ASTContext &Context,
4242 CXXMethodDecl *Method,
4243 SmallVectorImpl<QualType> &ArgTypes) {
4244 // C++11 [temp.func.order]p3:
4245 // [...] The new parameter is of type "reference to cv A," where cv are
4246 // the cv-qualifiers of the function template (if any) and A is
4247 // the class of which the function template is a member.
4249 // The standard doesn't say explicitly, but we pick the appropriate kind of
4250 // reference type based on [over.match.funcs]p4.
4251 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4252 ArgTy = Context.getQualifiedType(ArgTy,
4253 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
4254 if (Method->getRefQualifier() == RQ_RValue)
4255 ArgTy = Context.getRValueReferenceType(ArgTy);
4257 ArgTy = Context.getLValueReferenceType(ArgTy);
4258 ArgTypes.push_back(ArgTy);
4261 /// \brief Determine whether the function template \p FT1 is at least as
4262 /// specialized as \p FT2.
4263 static bool isAtLeastAsSpecializedAs(Sema &S,
4265 FunctionTemplateDecl *FT1,
4266 FunctionTemplateDecl *FT2,
4267 TemplatePartialOrderingContext TPOC,
4268 unsigned NumCallArguments1) {
4269 FunctionDecl *FD1 = FT1->getTemplatedDecl();
4270 FunctionDecl *FD2 = FT2->getTemplatedDecl();
4271 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4272 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
4274 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4275 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
4276 SmallVector<DeducedTemplateArgument, 4> Deduced;
4277 Deduced.resize(TemplateParams->size());
4279 // C++0x [temp.deduct.partial]p3:
4280 // The types used to determine the ordering depend on the context in which
4281 // the partial ordering is done:
4282 TemplateDeductionInfo Info(Loc);
4283 SmallVector<QualType, 4> Args2;
4286 // - In the context of a function call, the function parameter types are
4288 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4289 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
4291 // C++11 [temp.func.order]p3:
4292 // [...] If only one of the function templates is a non-static
4293 // member, that function template is considered to have a new
4294 // first parameter inserted in its function parameter list. The
4295 // new parameter is of type "reference to cv A," where cv are
4296 // the cv-qualifiers of the function template (if any) and A is
4297 // the class of which the function template is a member.
4299 // Note that we interpret this to mean "if one of the function
4300 // templates is a non-static member and the other is a non-member";
4301 // otherwise, the ordering rules for static functions against non-static
4302 // functions don't make any sense.
4304 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4305 // it as wording was broken prior to it.
4306 SmallVector<QualType, 4> Args1;
4308 unsigned NumComparedArguments = NumCallArguments1;
4310 if (!Method2 && Method1 && !Method1->isStatic()) {
4311 // Compare 'this' from Method1 against first parameter from Method2.
4312 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4313 ++NumComparedArguments;
4314 } else if (!Method1 && Method2 && !Method2->isStatic()) {
4315 // Compare 'this' from Method2 against first parameter from Method1.
4316 AddImplicitObjectParameterType(S.Context, Method2, Args2);
4319 Args1.insert(Args1.end(), Proto1->param_type_begin(),
4320 Proto1->param_type_end());
4321 Args2.insert(Args2.end(), Proto2->param_type_begin(),
4322 Proto2->param_type_end());
4324 // C++ [temp.func.order]p5:
4325 // The presence of unused ellipsis and default arguments has no effect on
4326 // the partial ordering of function templates.
4327 if (Args1.size() > NumComparedArguments)
4328 Args1.resize(NumComparedArguments);
4329 if (Args2.size() > NumComparedArguments)
4330 Args2.resize(NumComparedArguments);
4331 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4332 Args1.data(), Args1.size(), Info, Deduced,
4333 TDF_None, /*PartialOrdering=*/true))
4339 case TPOC_Conversion:
4340 // - In the context of a call to a conversion operator, the return types
4341 // of the conversion function templates are used.
4342 if (DeduceTemplateArgumentsByTypeMatch(
4343 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4344 Info, Deduced, TDF_None,
4345 /*PartialOrdering=*/true))
4350 // - In other contexts (14.6.6.2) the function template's function type
4352 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4353 FD2->getType(), FD1->getType(),
4354 Info, Deduced, TDF_None,
4355 /*PartialOrdering=*/true))
4360 // C++0x [temp.deduct.partial]p11:
4361 // In most cases, all template parameters must have values in order for
4362 // deduction to succeed, but for partial ordering purposes a template
4363 // parameter may remain without a value provided it is not used in the
4364 // types being used for partial ordering. [ Note: a template parameter used
4365 // in a non-deduced context is considered used. -end note]
4366 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4367 for (; ArgIdx != NumArgs; ++ArgIdx)
4368 if (Deduced[ArgIdx].isNull())
4371 // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
4372 // to substitute the deduced arguments back into the template and check that
4373 // we get the right type.
4375 if (ArgIdx == NumArgs) {
4376 // All template arguments were deduced. FT1 is at least as specialized
4381 // Figure out which template parameters were used.
4382 llvm::SmallBitVector UsedParameters(TemplateParams->size());
4385 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4386 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
4387 TemplateParams->getDepth(),
4391 case TPOC_Conversion:
4392 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4393 TemplateParams->getDepth(), UsedParameters);
4397 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
4398 TemplateParams->getDepth(),
4403 for (; ArgIdx != NumArgs; ++ArgIdx)
4404 // If this argument had no value deduced but was used in one of the types
4405 // used for partial ordering, then deduction fails.
4406 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4412 /// \brief Determine whether this a function template whose parameter-type-list
4413 /// ends with a function parameter pack.
4414 static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4415 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4416 unsigned NumParams = Function->getNumParams();
4420 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4421 if (!Last->isParameterPack())
4424 // Make sure that no previous parameter is a parameter pack.
4425 while (--NumParams > 0) {
4426 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4433 /// \brief Returns the more specialized function template according
4434 /// to the rules of function template partial ordering (C++ [temp.func.order]).
4436 /// \param FT1 the first function template
4438 /// \param FT2 the second function template
4440 /// \param TPOC the context in which we are performing partial ordering of
4441 /// function templates.
4443 /// \param NumCallArguments1 The number of arguments in the call to FT1, used
4444 /// only when \c TPOC is \c TPOC_Call.
4446 /// \param NumCallArguments2 The number of arguments in the call to FT2, used
4447 /// only when \c TPOC is \c TPOC_Call.
4449 /// \returns the more specialized function template. If neither
4450 /// template is more specialized, returns NULL.
4451 FunctionTemplateDecl *
4452 Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4453 FunctionTemplateDecl *FT2,
4455 TemplatePartialOrderingContext TPOC,
4456 unsigned NumCallArguments1,
4457 unsigned NumCallArguments2) {
4458 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
4460 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
4463 if (Better1 != Better2) // We have a clear winner
4464 return Better1 ? FT1 : FT2;
4466 if (!Better1 && !Better2) // Neither is better than the other
4469 // FIXME: This mimics what GCC implements, but doesn't match up with the
4470 // proposed resolution for core issue 692. This area needs to be sorted out,
4471 // but for now we attempt to maintain compatibility.
4472 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4473 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4474 if (Variadic1 != Variadic2)
4475 return Variadic1? FT2 : FT1;
4480 /// \brief Determine if the two templates are equivalent.
4481 static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4488 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4491 /// \brief Retrieve the most specialized of the given function template
4492 /// specializations.
4494 /// \param SpecBegin the start iterator of the function template
4495 /// specializations that we will be comparing.
4497 /// \param SpecEnd the end iterator of the function template
4498 /// specializations, paired with \p SpecBegin.
4500 /// \param Loc the location where the ambiguity or no-specializations
4501 /// diagnostic should occur.
4503 /// \param NoneDiag partial diagnostic used to diagnose cases where there are
4504 /// no matching candidates.
4506 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4509 /// \param CandidateDiag partial diagnostic used for each function template
4510 /// specialization that is a candidate in the ambiguous ordering. One parameter
4511 /// in this diagnostic should be unbound, which will correspond to the string
4512 /// describing the template arguments for the function template specialization.
4514 /// \returns the most specialized function template specialization, if
4515 /// found. Otherwise, returns SpecEnd.
4516 UnresolvedSetIterator Sema::getMostSpecialized(
4517 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4518 TemplateSpecCandidateSet &FailedCandidates,
4519 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4520 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4521 bool Complain, QualType TargetType) {
4522 if (SpecBegin == SpecEnd) {
4524 Diag(Loc, NoneDiag);
4525 FailedCandidates.NoteCandidates(*this, Loc);
4530 if (SpecBegin + 1 == SpecEnd)
4533 // Find the function template that is better than all of the templates it
4534 // has been compared to.
4535 UnresolvedSetIterator Best = SpecBegin;
4536 FunctionTemplateDecl *BestTemplate
4537 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
4538 assert(BestTemplate && "Not a function template specialization?");
4539 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4540 FunctionTemplateDecl *Challenger
4541 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
4542 assert(Challenger && "Not a function template specialization?");
4543 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
4544 Loc, TPOC_Other, 0, 0),
4547 BestTemplate = Challenger;
4551 // Make sure that the "best" function template is more specialized than all
4553 bool Ambiguous = false;
4554 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4555 FunctionTemplateDecl *Challenger
4556 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
4558 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
4559 Loc, TPOC_Other, 0, 0),
4567 // We found an answer. Return it.
4571 // Diagnose the ambiguity.
4573 Diag(Loc, AmbigDiag);
4575 // FIXME: Can we order the candidates in some sane way?
4576 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4577 PartialDiagnostic PD = CandidateDiag;
4578 const auto *FD = cast<FunctionDecl>(*I);
4579 PD << FD << getTemplateArgumentBindingsText(
4580 FD->getPrimaryTemplate()->getTemplateParameters(),
4581 *FD->getTemplateSpecializationArgs());
4582 if (!TargetType.isNull())
4583 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
4584 Diag((*I)->getLocation(), PD);
4591 /// Determine whether one partial specialization, P1, is at least as
4592 /// specialized than another, P2.
4594 /// \tparam TemplateLikeDecl The kind of P2, which must be a
4595 /// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
4596 /// \param T1 The injected-class-name of P1 (faked for a variable template).
4597 /// \param T2 The injected-class-name of P2 (faked for a variable template).
4598 template<typename TemplateLikeDecl>
4599 static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
4600 TemplateLikeDecl *P2,
4601 TemplateDeductionInfo &Info) {
4602 // C++ [temp.class.order]p1:
4603 // For two class template partial specializations, the first is at least as
4604 // specialized as the second if, given the following rewrite to two
4605 // function templates, the first function template is at least as
4606 // specialized as the second according to the ordering rules for function
4607 // templates (14.6.6.2):
4608 // - the first function template has the same template parameters as the
4609 // first partial specialization and has a single function parameter
4610 // whose type is a class template specialization with the template
4611 // arguments of the first partial specialization, and
4612 // - the second function template has the same template parameters as the
4613 // second partial specialization and has a single function parameter
4614 // whose type is a class template specialization with the template
4615 // arguments of the second partial specialization.
4617 // Rather than synthesize function templates, we merely perform the
4618 // equivalent partial ordering by performing deduction directly on
4619 // the template arguments of the class template partial
4620 // specializations. This computation is slightly simpler than the
4621 // general problem of function template partial ordering, because
4622 // class template partial specializations are more constrained. We
4623 // know that every template parameter is deducible from the class
4624 // template partial specialization's template arguments, for
4626 SmallVector<DeducedTemplateArgument, 4> Deduced;
4628 // Determine whether P1 is at least as specialized as P2.
4629 Deduced.resize(P2->getTemplateParameters()->size());
4630 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
4631 T2, T1, Info, Deduced, TDF_None,
4632 /*PartialOrdering=*/true))
4635 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4637 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
4639 auto *TST1 = T1->castAs<TemplateSpecializationType>();
4640 if (FinishTemplateArgumentDeduction(
4641 S, P2, /*PartialOrdering=*/true,
4642 TemplateArgumentList(TemplateArgumentList::OnStack,
4643 TST1->template_arguments()),
4650 /// \brief Returns the more specialized class template partial specialization
4651 /// according to the rules of partial ordering of class template partial
4652 /// specializations (C++ [temp.class.order]).
4654 /// \param PS1 the first class template partial specialization
4656 /// \param PS2 the second class template partial specialization
4658 /// \returns the more specialized class template partial specialization. If
4659 /// neither partial specialization is more specialized, returns NULL.
4660 ClassTemplatePartialSpecializationDecl *
4661 Sema::getMoreSpecializedPartialSpecialization(
4662 ClassTemplatePartialSpecializationDecl *PS1,
4663 ClassTemplatePartialSpecializationDecl *PS2,
4664 SourceLocation Loc) {
4665 QualType PT1 = PS1->getInjectedSpecializationType();
4666 QualType PT2 = PS2->getInjectedSpecializationType();
4668 TemplateDeductionInfo Info(Loc);
4669 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4670 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
4672 if (Better1 == Better2)
4675 return Better1 ? PS1 : PS2;
4678 bool Sema::isMoreSpecializedThanPrimary(
4679 ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4680 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
4681 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
4682 QualType PartialT = Spec->getInjectedSpecializationType();
4683 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
4685 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
4686 Info.clearSFINAEDiagnostic();
4692 VarTemplatePartialSpecializationDecl *
4693 Sema::getMoreSpecializedPartialSpecialization(
4694 VarTemplatePartialSpecializationDecl *PS1,
4695 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
4696 // Pretend the variable template specializations are class template
4697 // specializations and form a fake injected class name type for comparison.
4698 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
4699 "the partial specializations being compared should specialize"
4700 " the same template.");
4701 TemplateName Name(PS1->getSpecializedTemplate());
4702 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4703 QualType PT1 = Context.getTemplateSpecializationType(
4704 CanonTemplate, PS1->getTemplateArgs().asArray());
4705 QualType PT2 = Context.getTemplateSpecializationType(
4706 CanonTemplate, PS2->getTemplateArgs().asArray());
4708 TemplateDeductionInfo Info(Loc);
4709 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4710 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
4712 if (Better1 == Better2)
4715 return Better1 ? PS1 : PS2;
4718 bool Sema::isMoreSpecializedThanPrimary(
4719 VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4720 TemplateDecl *Primary = Spec->getSpecializedTemplate();
4721 // FIXME: Cache the injected template arguments rather than recomputing
4722 // them for each partial specialization.
4723 SmallVector<TemplateArgument, 8> PrimaryArgs;
4724 Context.getInjectedTemplateArgs(Primary->getTemplateParameters(),
4727 TemplateName CanonTemplate =
4728 Context.getCanonicalTemplateName(TemplateName(Primary));
4729 QualType PrimaryT = Context.getTemplateSpecializationType(
4730 CanonTemplate, PrimaryArgs);
4731 QualType PartialT = Context.getTemplateSpecializationType(
4732 CanonTemplate, Spec->getTemplateArgs().asArray());
4733 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
4735 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
4736 Info.clearSFINAEDiagnostic();
4742 bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
4743 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) {
4744 // C++1z [temp.arg.template]p4: (DR 150)
4745 // A template template-parameter P is at least as specialized as a
4746 // template template-argument A if, given the following rewrite to two
4747 // function templates...
4749 // Rather than synthesize function templates, we merely perform the
4750 // equivalent partial ordering by performing deduction directly on
4751 // the template parameter lists of the template template parameters.
4753 // Given an invented class template X with the template parameter list of
4754 // A (including default arguments):
4755 TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg));
4756 TemplateParameterList *A = AArg->getTemplateParameters();
4758 // - Each function template has a single function parameter whose type is
4759 // a specialization of X with template arguments corresponding to the
4760 // template parameters from the respective function template
4761 SmallVector<TemplateArgument, 8> AArgs;
4762 Context.getInjectedTemplateArgs(A, AArgs);
4764 // Check P's arguments against A's parameter list. This will fill in default
4765 // template arguments as needed. AArgs are already correct by construction.
4766 // We can't just use CheckTemplateIdType because that will expand alias
4768 SmallVector<TemplateArgument, 4> PArgs;
4770 SFINAETrap Trap(*this);
4772 Context.getInjectedTemplateArgs(P, PArgs);
4773 TemplateArgumentListInfo PArgList(P->getLAngleLoc(), P->getRAngleLoc());
4774 for (unsigned I = 0, N = P->size(); I != N; ++I) {
4775 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
4776 // expansions, to form an "as written" argument list.
4777 TemplateArgument Arg = PArgs[I];
4778 if (Arg.getKind() == TemplateArgument::Pack) {
4779 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
4780 Arg = *Arg.pack_begin();
4782 PArgList.addArgument(getTrivialTemplateArgumentLoc(
4783 Arg, QualType(), P->getParam(I)->getLocation()));
4787 // C++1z [temp.arg.template]p3:
4788 // If the rewrite produces an invalid type, then P is not at least as
4789 // specialized as A.
4790 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, PArgs) ||
4791 Trap.hasErrorOccurred())
4795 QualType AType = Context.getTemplateSpecializationType(X, AArgs);
4796 QualType PType = Context.getTemplateSpecializationType(X, PArgs);
4798 // ... the function template corresponding to P is at least as specialized
4799 // as the function template corresponding to A according to the partial
4800 // ordering rules for function templates.
4801 TemplateDeductionInfo Info(Loc, A->getDepth());
4802 return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info);
4806 MarkUsedTemplateParameters(ASTContext &Ctx,
4807 const TemplateArgument &TemplateArg,
4810 llvm::SmallBitVector &Used);
4812 /// \brief Mark the template parameters that are used by the given
4815 MarkUsedTemplateParameters(ASTContext &Ctx,
4819 llvm::SmallBitVector &Used) {
4820 // We can deduce from a pack expansion.
4821 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4822 E = Expansion->getPattern();
4824 // Skip through any implicit casts we added while type-checking, and any
4825 // substitutions performed by template alias expansion.
4827 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4828 E = ICE->getSubExpr();
4829 else if (const SubstNonTypeTemplateParmExpr *Subst =
4830 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4831 E = Subst->getReplacement();
4836 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
4837 // find other occurrences of template parameters.
4838 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
4842 const NonTypeTemplateParmDecl *NTTP
4843 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4847 if (NTTP->getDepth() == Depth)
4848 Used[NTTP->getIndex()] = true;
4850 // In C++1z mode, additional arguments may be deduced from the type of a
4851 // non-type argument.
4852 if (Ctx.getLangOpts().CPlusPlus1z)
4853 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
4856 /// \brief Mark the template parameters that are used by the given
4857 /// nested name specifier.
4859 MarkUsedTemplateParameters(ASTContext &Ctx,
4860 NestedNameSpecifier *NNS,
4863 llvm::SmallBitVector &Used) {
4867 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
4869 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
4870 OnlyDeduced, Depth, Used);
4873 /// \brief Mark the template parameters that are used by the given
4876 MarkUsedTemplateParameters(ASTContext &Ctx,
4880 llvm::SmallBitVector &Used) {
4881 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4882 if (TemplateTemplateParmDecl *TTP
4883 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4884 if (TTP->getDepth() == Depth)
4885 Used[TTP->getIndex()] = true;
4890 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
4891 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
4893 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
4894 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
4898 /// \brief Mark the template parameters that are used by the given
4901 MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
4904 llvm::SmallBitVector &Used) {
4908 // Non-dependent types have nothing deducible
4909 if (!T->isDependentType())
4912 T = Ctx.getCanonicalType(T);
4913 switch (T->getTypeClass()) {
4915 MarkUsedTemplateParameters(Ctx,
4916 cast<PointerType>(T)->getPointeeType(),
4922 case Type::BlockPointer:
4923 MarkUsedTemplateParameters(Ctx,
4924 cast<BlockPointerType>(T)->getPointeeType(),
4930 case Type::LValueReference:
4931 case Type::RValueReference:
4932 MarkUsedTemplateParameters(Ctx,
4933 cast<ReferenceType>(T)->getPointeeType(),
4939 case Type::MemberPointer: {
4940 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
4941 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
4943 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
4944 OnlyDeduced, Depth, Used);
4948 case Type::DependentSizedArray:
4949 MarkUsedTemplateParameters(Ctx,
4950 cast<DependentSizedArrayType>(T)->getSizeExpr(),
4951 OnlyDeduced, Depth, Used);
4952 // Fall through to check the element type
4954 case Type::ConstantArray:
4955 case Type::IncompleteArray:
4956 MarkUsedTemplateParameters(Ctx,
4957 cast<ArrayType>(T)->getElementType(),
4958 OnlyDeduced, Depth, Used);
4962 case Type::ExtVector:
4963 MarkUsedTemplateParameters(Ctx,
4964 cast<VectorType>(T)->getElementType(),
4965 OnlyDeduced, Depth, Used);
4968 case Type::DependentSizedExtVector: {
4969 const DependentSizedExtVectorType *VecType
4970 = cast<DependentSizedExtVectorType>(T);
4971 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
4973 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
4978 case Type::FunctionProto: {
4979 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
4980 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4982 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4983 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
4988 case Type::TemplateTypeParm: {
4989 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4990 if (TTP->getDepth() == Depth)
4991 Used[TTP->getIndex()] = true;
4995 case Type::SubstTemplateTypeParmPack: {
4996 const SubstTemplateTypeParmPackType *Subst
4997 = cast<SubstTemplateTypeParmPackType>(T);
4998 MarkUsedTemplateParameters(Ctx,
4999 QualType(Subst->getReplacedParameter(), 0),
5000 OnlyDeduced, Depth, Used);
5001 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
5002 OnlyDeduced, Depth, Used);
5006 case Type::InjectedClassName:
5007 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
5010 case Type::TemplateSpecialization: {
5011 const TemplateSpecializationType *Spec
5012 = cast<TemplateSpecializationType>(T);
5013 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
5016 // C++0x [temp.deduct.type]p9:
5017 // If the template argument list of P contains a pack expansion that is
5018 // not the last template argument, the entire template argument list is a
5019 // non-deduced context.
5021 hasPackExpansionBeforeEnd(Spec->template_arguments()))
5024 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
5025 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
5032 MarkUsedTemplateParameters(Ctx,
5033 cast<ComplexType>(T)->getElementType(),
5034 OnlyDeduced, Depth, Used);
5039 MarkUsedTemplateParameters(Ctx,
5040 cast<AtomicType>(T)->getValueType(),
5041 OnlyDeduced, Depth, Used);
5044 case Type::DependentName:
5046 MarkUsedTemplateParameters(Ctx,
5047 cast<DependentNameType>(T)->getQualifier(),
5048 OnlyDeduced, Depth, Used);
5051 case Type::DependentTemplateSpecialization: {
5052 // C++14 [temp.deduct.type]p5:
5053 // The non-deduced contexts are:
5054 // -- The nested-name-specifier of a type that was specified using a
5057 // C++14 [temp.deduct.type]p6:
5058 // When a type name is specified in a way that includes a non-deduced
5059 // context, all of the types that comprise that type name are also
5064 const DependentTemplateSpecializationType *Spec
5065 = cast<DependentTemplateSpecializationType>(T);
5067 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
5068 OnlyDeduced, Depth, Used);
5070 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
5071 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
5078 MarkUsedTemplateParameters(Ctx,
5079 cast<TypeOfType>(T)->getUnderlyingType(),
5080 OnlyDeduced, Depth, Used);
5083 case Type::TypeOfExpr:
5085 MarkUsedTemplateParameters(Ctx,
5086 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
5087 OnlyDeduced, Depth, Used);
5090 case Type::Decltype:
5092 MarkUsedTemplateParameters(Ctx,
5093 cast<DecltypeType>(T)->getUnderlyingExpr(),
5094 OnlyDeduced, Depth, Used);
5097 case Type::UnaryTransform:
5099 MarkUsedTemplateParameters(Ctx,
5100 cast<UnaryTransformType>(T)->getUnderlyingType(),
5101 OnlyDeduced, Depth, Used);
5104 case Type::PackExpansion:
5105 MarkUsedTemplateParameters(Ctx,
5106 cast<PackExpansionType>(T)->getPattern(),
5107 OnlyDeduced, Depth, Used);
5111 MarkUsedTemplateParameters(Ctx,
5112 cast<AutoType>(T)->getDeducedType(),
5113 OnlyDeduced, Depth, Used);
5115 // None of these types have any template parameters in them.
5117 case Type::VariableArray:
5118 case Type::FunctionNoProto:
5121 case Type::ObjCInterface:
5122 case Type::ObjCObject:
5123 case Type::ObjCObjectPointer:
5124 case Type::UnresolvedUsing:
5126 #define TYPE(Class, Base)
5127 #define ABSTRACT_TYPE(Class, Base)
5128 #define DEPENDENT_TYPE(Class, Base)
5129 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5130 #include "clang/AST/TypeNodes.def"
5135 /// \brief Mark the template parameters that are used by this
5136 /// template argument.
5138 MarkUsedTemplateParameters(ASTContext &Ctx,
5139 const TemplateArgument &TemplateArg,
5142 llvm::SmallBitVector &Used) {
5143 switch (TemplateArg.getKind()) {
5144 case TemplateArgument::Null:
5145 case TemplateArgument::Integral:
5146 case TemplateArgument::Declaration:
5149 case TemplateArgument::NullPtr:
5150 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5154 case TemplateArgument::Type:
5155 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
5159 case TemplateArgument::Template:
5160 case TemplateArgument::TemplateExpansion:
5161 MarkUsedTemplateParameters(Ctx,
5162 TemplateArg.getAsTemplateOrTemplatePattern(),
5163 OnlyDeduced, Depth, Used);
5166 case TemplateArgument::Expression:
5167 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
5171 case TemplateArgument::Pack:
5172 for (const auto &P : TemplateArg.pack_elements())
5173 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
5178 /// \brief Mark which template parameters can be deduced from a given
5179 /// template argument list.
5181 /// \param TemplateArgs the template argument list from which template
5182 /// parameters will be deduced.
5184 /// \param Used a bit vector whose elements will be set to \c true
5185 /// to indicate when the corresponding template parameter will be
5188 Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
5189 bool OnlyDeduced, unsigned Depth,
5190 llvm::SmallBitVector &Used) {
5191 // C++0x [temp.deduct.type]p9:
5192 // If the template argument list of P contains a pack expansion that is not
5193 // the last template argument, the entire template argument list is a
5194 // non-deduced context.
5196 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
5199 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
5200 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
5204 /// \brief Marks all of the template parameters that will be deduced by a
5205 /// call to the given function template.
5206 void Sema::MarkDeducedTemplateParameters(
5207 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5208 llvm::SmallBitVector &Deduced) {
5209 TemplateParameterList *TemplateParams
5210 = FunctionTemplate->getTemplateParameters();
5212 Deduced.resize(TemplateParams->size());
5214 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5215 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
5216 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
5217 true, TemplateParams->getDepth(), Deduced);
5220 bool hasDeducibleTemplateParameters(Sema &S,
5221 FunctionTemplateDecl *FunctionTemplate,
5223 if (!T->isDependentType())
5226 TemplateParameterList *TemplateParams
5227 = FunctionTemplate->getTemplateParameters();
5228 llvm::SmallBitVector Deduced(TemplateParams->size());
5229 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
5232 return Deduced.any();