xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaTemplateDeduction.cpp (revision e63539f3059728ff58328ac0ecb2a7bf4e2f08e8)
10b57cec5SDimitry Andric //===- SemaTemplateDeduction.cpp - Template Argument Deduction ------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements C++ template argument deduction.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "clang/Sema/TemplateDeduction.h"
140b57cec5SDimitry Andric #include "TreeTransform.h"
150b57cec5SDimitry Andric #include "TypeLocBuilder.h"
160b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
170b57cec5SDimitry Andric #include "clang/AST/ASTLambda.h"
180b57cec5SDimitry Andric #include "clang/AST/Decl.h"
190b57cec5SDimitry Andric #include "clang/AST/DeclAccessPair.h"
200b57cec5SDimitry Andric #include "clang/AST/DeclBase.h"
210b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h"
220b57cec5SDimitry Andric #include "clang/AST/DeclTemplate.h"
230b57cec5SDimitry Andric #include "clang/AST/DeclarationName.h"
240b57cec5SDimitry Andric #include "clang/AST/Expr.h"
250b57cec5SDimitry Andric #include "clang/AST/ExprCXX.h"
260b57cec5SDimitry Andric #include "clang/AST/NestedNameSpecifier.h"
27480093f4SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
280b57cec5SDimitry Andric #include "clang/AST/TemplateBase.h"
290b57cec5SDimitry Andric #include "clang/AST/TemplateName.h"
300b57cec5SDimitry Andric #include "clang/AST/Type.h"
310b57cec5SDimitry Andric #include "clang/AST/TypeLoc.h"
320b57cec5SDimitry Andric #include "clang/AST/UnresolvedSet.h"
330b57cec5SDimitry Andric #include "clang/Basic/AddressSpaces.h"
340b57cec5SDimitry Andric #include "clang/Basic/ExceptionSpecificationType.h"
350b57cec5SDimitry Andric #include "clang/Basic/LLVM.h"
360b57cec5SDimitry Andric #include "clang/Basic/LangOptions.h"
370b57cec5SDimitry Andric #include "clang/Basic/PartialDiagnostic.h"
380b57cec5SDimitry Andric #include "clang/Basic/SourceLocation.h"
390b57cec5SDimitry Andric #include "clang/Basic/Specifiers.h"
400b57cec5SDimitry Andric #include "clang/Sema/Ownership.h"
410b57cec5SDimitry Andric #include "clang/Sema/Sema.h"
420b57cec5SDimitry Andric #include "clang/Sema/Template.h"
430b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
440b57cec5SDimitry Andric #include "llvm/ADT/APSInt.h"
450b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
460b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
470b57cec5SDimitry Andric #include "llvm/ADT/FoldingSet.h"
480b57cec5SDimitry Andric #include "llvm/ADT/Optional.h"
490b57cec5SDimitry Andric #include "llvm/ADT/SmallBitVector.h"
500b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
510b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
520b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
530b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
540b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
550b57cec5SDimitry Andric #include <algorithm>
560b57cec5SDimitry Andric #include <cassert>
570b57cec5SDimitry Andric #include <tuple>
580b57cec5SDimitry Andric #include <utility>
590b57cec5SDimitry Andric 
600b57cec5SDimitry Andric namespace clang {
610b57cec5SDimitry Andric 
620b57cec5SDimitry Andric   /// Various flags that control template argument deduction.
630b57cec5SDimitry Andric   ///
640b57cec5SDimitry Andric   /// These flags can be bitwise-OR'd together.
650b57cec5SDimitry Andric   enum TemplateDeductionFlags {
660b57cec5SDimitry Andric     /// No template argument deduction flags, which indicates the
670b57cec5SDimitry Andric     /// strictest results for template argument deduction (as used for, e.g.,
680b57cec5SDimitry Andric     /// matching class template partial specializations).
690b57cec5SDimitry Andric     TDF_None = 0,
700b57cec5SDimitry Andric 
710b57cec5SDimitry Andric     /// Within template argument deduction from a function call, we are
720b57cec5SDimitry Andric     /// matching with a parameter type for which the original parameter was
730b57cec5SDimitry Andric     /// a reference.
740b57cec5SDimitry Andric     TDF_ParamWithReferenceType = 0x1,
750b57cec5SDimitry Andric 
760b57cec5SDimitry Andric     /// Within template argument deduction from a function call, we
770b57cec5SDimitry Andric     /// are matching in a case where we ignore cv-qualifiers.
780b57cec5SDimitry Andric     TDF_IgnoreQualifiers = 0x02,
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric     /// Within template argument deduction from a function call,
810b57cec5SDimitry Andric     /// we are matching in a case where we can perform template argument
820b57cec5SDimitry Andric     /// deduction from a template-id of a derived class of the argument type.
830b57cec5SDimitry Andric     TDF_DerivedClass = 0x04,
840b57cec5SDimitry Andric 
850b57cec5SDimitry Andric     /// Allow non-dependent types to differ, e.g., when performing
860b57cec5SDimitry Andric     /// template argument deduction from a function call where conversions
870b57cec5SDimitry Andric     /// may apply.
880b57cec5SDimitry Andric     TDF_SkipNonDependent = 0x08,
890b57cec5SDimitry Andric 
900b57cec5SDimitry Andric     /// Whether we are performing template argument deduction for
910b57cec5SDimitry Andric     /// parameters and arguments in a top-level template argument
920b57cec5SDimitry Andric     TDF_TopLevelParameterTypeList = 0x10,
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric     /// Within template argument deduction from overload resolution per
950b57cec5SDimitry Andric     /// C++ [over.over] allow matching function types that are compatible in
960b57cec5SDimitry Andric     /// terms of noreturn and default calling convention adjustments, or
970b57cec5SDimitry Andric     /// similarly matching a declared template specialization against a
980b57cec5SDimitry Andric     /// possible template, per C++ [temp.deduct.decl]. In either case, permit
990b57cec5SDimitry Andric     /// deduction where the parameter is a function type that can be converted
1000b57cec5SDimitry Andric     /// to the argument type.
1010b57cec5SDimitry Andric     TDF_AllowCompatibleFunctionType = 0x20,
1020b57cec5SDimitry Andric 
1030b57cec5SDimitry Andric     /// Within template argument deduction for a conversion function, we are
1040b57cec5SDimitry Andric     /// matching with an argument type for which the original argument was
1050b57cec5SDimitry Andric     /// a reference.
1060b57cec5SDimitry Andric     TDF_ArgWithReferenceType = 0x40,
1070b57cec5SDimitry Andric   };
1080b57cec5SDimitry Andric }
1090b57cec5SDimitry Andric 
1100b57cec5SDimitry Andric using namespace clang;
1110b57cec5SDimitry Andric using namespace sema;
1120b57cec5SDimitry Andric 
1130b57cec5SDimitry Andric /// Compare two APSInts, extending and switching the sign as
1140b57cec5SDimitry Andric /// necessary to compare their values regardless of underlying type.
1150b57cec5SDimitry Andric static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
1160b57cec5SDimitry Andric   if (Y.getBitWidth() > X.getBitWidth())
1170b57cec5SDimitry Andric     X = X.extend(Y.getBitWidth());
1180b57cec5SDimitry Andric   else if (Y.getBitWidth() < X.getBitWidth())
1190b57cec5SDimitry Andric     Y = Y.extend(X.getBitWidth());
1200b57cec5SDimitry Andric 
1210b57cec5SDimitry Andric   // If there is a signedness mismatch, correct it.
1220b57cec5SDimitry Andric   if (X.isSigned() != Y.isSigned()) {
1230b57cec5SDimitry Andric     // If the signed value is negative, then the values cannot be the same.
1240b57cec5SDimitry Andric     if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
1250b57cec5SDimitry Andric       return false;
1260b57cec5SDimitry Andric 
1270b57cec5SDimitry Andric     Y.setIsSigned(true);
1280b57cec5SDimitry Andric     X.setIsSigned(true);
1290b57cec5SDimitry Andric   }
1300b57cec5SDimitry Andric 
1310b57cec5SDimitry Andric   return X == Y;
1320b57cec5SDimitry Andric }
1330b57cec5SDimitry Andric 
1340b57cec5SDimitry Andric static Sema::TemplateDeductionResult
1350b57cec5SDimitry Andric DeduceTemplateArguments(Sema &S,
1360b57cec5SDimitry Andric                         TemplateParameterList *TemplateParams,
1370b57cec5SDimitry Andric                         const TemplateArgument &Param,
1380b57cec5SDimitry Andric                         TemplateArgument Arg,
1390b57cec5SDimitry Andric                         TemplateDeductionInfo &Info,
1400b57cec5SDimitry Andric                         SmallVectorImpl<DeducedTemplateArgument> &Deduced);
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric static Sema::TemplateDeductionResult
1430b57cec5SDimitry Andric DeduceTemplateArgumentsByTypeMatch(Sema &S,
1440b57cec5SDimitry Andric                                    TemplateParameterList *TemplateParams,
1450b57cec5SDimitry Andric                                    QualType Param,
1460b57cec5SDimitry Andric                                    QualType Arg,
1470b57cec5SDimitry Andric                                    TemplateDeductionInfo &Info,
1480b57cec5SDimitry Andric                                    SmallVectorImpl<DeducedTemplateArgument> &
1490b57cec5SDimitry Andric                                                       Deduced,
1500b57cec5SDimitry Andric                                    unsigned TDF,
1510b57cec5SDimitry Andric                                    bool PartialOrdering = false,
1520b57cec5SDimitry Andric                                    bool DeducedFromArrayBound = false);
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric static Sema::TemplateDeductionResult
1550b57cec5SDimitry Andric DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
1560b57cec5SDimitry Andric                         ArrayRef<TemplateArgument> Params,
1570b57cec5SDimitry Andric                         ArrayRef<TemplateArgument> Args,
1580b57cec5SDimitry Andric                         TemplateDeductionInfo &Info,
1590b57cec5SDimitry Andric                         SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1600b57cec5SDimitry Andric                         bool NumberOfArgumentsMustMatch);
1610b57cec5SDimitry Andric 
1620b57cec5SDimitry Andric static void MarkUsedTemplateParameters(ASTContext &Ctx,
1630b57cec5SDimitry Andric                                        const TemplateArgument &TemplateArg,
1640b57cec5SDimitry Andric                                        bool OnlyDeduced, unsigned Depth,
1650b57cec5SDimitry Andric                                        llvm::SmallBitVector &Used);
1660b57cec5SDimitry Andric 
1670b57cec5SDimitry Andric static void MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
1680b57cec5SDimitry Andric                                        bool OnlyDeduced, unsigned Level,
1690b57cec5SDimitry Andric                                        llvm::SmallBitVector &Deduced);
1700b57cec5SDimitry Andric 
1710b57cec5SDimitry Andric /// If the given expression is of a form that permits the deduction
1720b57cec5SDimitry Andric /// of a non-type template parameter, return the declaration of that
1730b57cec5SDimitry Andric /// non-type template parameter.
1740b57cec5SDimitry Andric static NonTypeTemplateParmDecl *
1750b57cec5SDimitry Andric getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) {
1760b57cec5SDimitry Andric   // If we are within an alias template, the expression may have undergone
1770b57cec5SDimitry Andric   // any number of parameter substitutions already.
1780b57cec5SDimitry Andric   while (true) {
1790b57cec5SDimitry Andric     if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
1800b57cec5SDimitry Andric       E = IC->getSubExpr();
1810b57cec5SDimitry Andric     else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(E))
1820b57cec5SDimitry Andric       E = CE->getSubExpr();
1830b57cec5SDimitry Andric     else if (SubstNonTypeTemplateParmExpr *Subst =
1840b57cec5SDimitry Andric                dyn_cast<SubstNonTypeTemplateParmExpr>(E))
1850b57cec5SDimitry Andric       E = Subst->getReplacement();
1860b57cec5SDimitry Andric     else
1870b57cec5SDimitry Andric       break;
1880b57cec5SDimitry Andric   }
1890b57cec5SDimitry Andric 
1900b57cec5SDimitry Andric   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1910b57cec5SDimitry Andric     if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
1920b57cec5SDimitry Andric       if (NTTP->getDepth() == Info.getDeducedDepth())
1930b57cec5SDimitry Andric         return NTTP;
1940b57cec5SDimitry Andric 
1950b57cec5SDimitry Andric   return nullptr;
1960b57cec5SDimitry Andric }
1970b57cec5SDimitry Andric 
1980b57cec5SDimitry Andric /// Determine whether two declaration pointers refer to the same
1990b57cec5SDimitry Andric /// declaration.
2000b57cec5SDimitry Andric static bool isSameDeclaration(Decl *X, Decl *Y) {
2010b57cec5SDimitry Andric   if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
2020b57cec5SDimitry Andric     X = NX->getUnderlyingDecl();
2030b57cec5SDimitry Andric   if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
2040b57cec5SDimitry Andric     Y = NY->getUnderlyingDecl();
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric   return X->getCanonicalDecl() == Y->getCanonicalDecl();
2070b57cec5SDimitry Andric }
2080b57cec5SDimitry Andric 
2090b57cec5SDimitry Andric /// Verify that the given, deduced template arguments are compatible.
2100b57cec5SDimitry Andric ///
2110b57cec5SDimitry Andric /// \returns The deduced template argument, or a NULL template argument if
2120b57cec5SDimitry Andric /// the deduced template arguments were incompatible.
2130b57cec5SDimitry Andric static DeducedTemplateArgument
2140b57cec5SDimitry Andric checkDeducedTemplateArguments(ASTContext &Context,
2150b57cec5SDimitry Andric                               const DeducedTemplateArgument &X,
2160b57cec5SDimitry Andric                               const DeducedTemplateArgument &Y) {
2170b57cec5SDimitry Andric   // We have no deduction for one or both of the arguments; they're compatible.
2180b57cec5SDimitry Andric   if (X.isNull())
2190b57cec5SDimitry Andric     return Y;
2200b57cec5SDimitry Andric   if (Y.isNull())
2210b57cec5SDimitry Andric     return X;
2220b57cec5SDimitry Andric 
2230b57cec5SDimitry Andric   // If we have two non-type template argument values deduced for the same
2240b57cec5SDimitry Andric   // parameter, they must both match the type of the parameter, and thus must
2250b57cec5SDimitry Andric   // match each other's type. As we're only keeping one of them, we must check
2260b57cec5SDimitry Andric   // for that now. The exception is that if either was deduced from an array
2270b57cec5SDimitry Andric   // bound, the type is permitted to differ.
2280b57cec5SDimitry Andric   if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
2290b57cec5SDimitry Andric     QualType XType = X.getNonTypeTemplateArgumentType();
2300b57cec5SDimitry Andric     if (!XType.isNull()) {
2310b57cec5SDimitry Andric       QualType YType = Y.getNonTypeTemplateArgumentType();
2320b57cec5SDimitry Andric       if (YType.isNull() || !Context.hasSameType(XType, YType))
2330b57cec5SDimitry Andric         return DeducedTemplateArgument();
2340b57cec5SDimitry Andric     }
2350b57cec5SDimitry Andric   }
2360b57cec5SDimitry Andric 
2370b57cec5SDimitry Andric   switch (X.getKind()) {
2380b57cec5SDimitry Andric   case TemplateArgument::Null:
2390b57cec5SDimitry Andric     llvm_unreachable("Non-deduced template arguments handled above");
2400b57cec5SDimitry Andric 
2410b57cec5SDimitry Andric   case TemplateArgument::Type:
2420b57cec5SDimitry Andric     // If two template type arguments have the same type, they're compatible.
2430b57cec5SDimitry Andric     if (Y.getKind() == TemplateArgument::Type &&
2440b57cec5SDimitry Andric         Context.hasSameType(X.getAsType(), Y.getAsType()))
2450b57cec5SDimitry Andric       return X;
2460b57cec5SDimitry Andric 
2470b57cec5SDimitry Andric     // If one of the two arguments was deduced from an array bound, the other
2480b57cec5SDimitry Andric     // supersedes it.
2490b57cec5SDimitry Andric     if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
2500b57cec5SDimitry Andric       return X.wasDeducedFromArrayBound() ? Y : X;
2510b57cec5SDimitry Andric 
2520b57cec5SDimitry Andric     // The arguments are not compatible.
2530b57cec5SDimitry Andric     return DeducedTemplateArgument();
2540b57cec5SDimitry Andric 
2550b57cec5SDimitry Andric   case TemplateArgument::Integral:
2560b57cec5SDimitry Andric     // If we deduced a constant in one case and either a dependent expression or
2570b57cec5SDimitry Andric     // declaration in another case, keep the integral constant.
2580b57cec5SDimitry Andric     // If both are integral constants with the same value, keep that value.
2590b57cec5SDimitry Andric     if (Y.getKind() == TemplateArgument::Expression ||
2600b57cec5SDimitry Andric         Y.getKind() == TemplateArgument::Declaration ||
2610b57cec5SDimitry Andric         (Y.getKind() == TemplateArgument::Integral &&
2620b57cec5SDimitry Andric          hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
2630b57cec5SDimitry Andric       return X.wasDeducedFromArrayBound() ? Y : X;
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric     // All other combinations are incompatible.
2660b57cec5SDimitry Andric     return DeducedTemplateArgument();
2670b57cec5SDimitry Andric 
2680b57cec5SDimitry Andric   case TemplateArgument::Template:
2690b57cec5SDimitry Andric     if (Y.getKind() == TemplateArgument::Template &&
2700b57cec5SDimitry Andric         Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
2710b57cec5SDimitry Andric       return X;
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric     // All other combinations are incompatible.
2740b57cec5SDimitry Andric     return DeducedTemplateArgument();
2750b57cec5SDimitry Andric 
2760b57cec5SDimitry Andric   case TemplateArgument::TemplateExpansion:
2770b57cec5SDimitry Andric     if (Y.getKind() == TemplateArgument::TemplateExpansion &&
2780b57cec5SDimitry Andric         Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
2790b57cec5SDimitry Andric                                     Y.getAsTemplateOrTemplatePattern()))
2800b57cec5SDimitry Andric       return X;
2810b57cec5SDimitry Andric 
2820b57cec5SDimitry Andric     // All other combinations are incompatible.
2830b57cec5SDimitry Andric     return DeducedTemplateArgument();
2840b57cec5SDimitry Andric 
2850b57cec5SDimitry Andric   case TemplateArgument::Expression: {
2860b57cec5SDimitry Andric     if (Y.getKind() != TemplateArgument::Expression)
2870b57cec5SDimitry Andric       return checkDeducedTemplateArguments(Context, Y, X);
2880b57cec5SDimitry Andric 
2890b57cec5SDimitry Andric     // Compare the expressions for equality
2900b57cec5SDimitry Andric     llvm::FoldingSetNodeID ID1, ID2;
2910b57cec5SDimitry Andric     X.getAsExpr()->Profile(ID1, Context, true);
2920b57cec5SDimitry Andric     Y.getAsExpr()->Profile(ID2, Context, true);
2930b57cec5SDimitry Andric     if (ID1 == ID2)
2940b57cec5SDimitry Andric       return X.wasDeducedFromArrayBound() ? Y : X;
2950b57cec5SDimitry Andric 
2960b57cec5SDimitry Andric     // Differing dependent expressions are incompatible.
2970b57cec5SDimitry Andric     return DeducedTemplateArgument();
2980b57cec5SDimitry Andric   }
2990b57cec5SDimitry Andric 
3000b57cec5SDimitry Andric   case TemplateArgument::Declaration:
3010b57cec5SDimitry Andric     assert(!X.wasDeducedFromArrayBound());
3020b57cec5SDimitry Andric 
3030b57cec5SDimitry Andric     // If we deduced a declaration and a dependent expression, keep the
3040b57cec5SDimitry Andric     // declaration.
3050b57cec5SDimitry Andric     if (Y.getKind() == TemplateArgument::Expression)
3060b57cec5SDimitry Andric       return X;
3070b57cec5SDimitry Andric 
3080b57cec5SDimitry Andric     // If we deduced a declaration and an integral constant, keep the
3090b57cec5SDimitry Andric     // integral constant and whichever type did not come from an array
3100b57cec5SDimitry Andric     // bound.
3110b57cec5SDimitry Andric     if (Y.getKind() == TemplateArgument::Integral) {
3120b57cec5SDimitry Andric       if (Y.wasDeducedFromArrayBound())
3130b57cec5SDimitry Andric         return TemplateArgument(Context, Y.getAsIntegral(),
3140b57cec5SDimitry Andric                                 X.getParamTypeForDecl());
3150b57cec5SDimitry Andric       return Y;
3160b57cec5SDimitry Andric     }
3170b57cec5SDimitry Andric 
3180b57cec5SDimitry Andric     // If we deduced two declarations, make sure that they refer to the
3190b57cec5SDimitry Andric     // same declaration.
3200b57cec5SDimitry Andric     if (Y.getKind() == TemplateArgument::Declaration &&
3210b57cec5SDimitry Andric         isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
3220b57cec5SDimitry Andric       return X;
3230b57cec5SDimitry Andric 
3240b57cec5SDimitry Andric     // All other combinations are incompatible.
3250b57cec5SDimitry Andric     return DeducedTemplateArgument();
3260b57cec5SDimitry Andric 
3270b57cec5SDimitry Andric   case TemplateArgument::NullPtr:
3280b57cec5SDimitry Andric     // If we deduced a null pointer and a dependent expression, keep the
3290b57cec5SDimitry Andric     // null pointer.
3300b57cec5SDimitry Andric     if (Y.getKind() == TemplateArgument::Expression)
3310b57cec5SDimitry Andric       return X;
3320b57cec5SDimitry Andric 
3330b57cec5SDimitry Andric     // If we deduced a null pointer and an integral constant, keep the
3340b57cec5SDimitry Andric     // integral constant.
3350b57cec5SDimitry Andric     if (Y.getKind() == TemplateArgument::Integral)
3360b57cec5SDimitry Andric       return Y;
3370b57cec5SDimitry Andric 
3380b57cec5SDimitry Andric     // If we deduced two null pointers, they are the same.
3390b57cec5SDimitry Andric     if (Y.getKind() == TemplateArgument::NullPtr)
3400b57cec5SDimitry Andric       return X;
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric     // All other combinations are incompatible.
3430b57cec5SDimitry Andric     return DeducedTemplateArgument();
3440b57cec5SDimitry Andric 
3450b57cec5SDimitry Andric   case TemplateArgument::Pack: {
3460b57cec5SDimitry Andric     if (Y.getKind() != TemplateArgument::Pack ||
3470b57cec5SDimitry Andric         X.pack_size() != Y.pack_size())
3480b57cec5SDimitry Andric       return DeducedTemplateArgument();
3490b57cec5SDimitry Andric 
3500b57cec5SDimitry Andric     llvm::SmallVector<TemplateArgument, 8> NewPack;
3510b57cec5SDimitry Andric     for (TemplateArgument::pack_iterator XA = X.pack_begin(),
3520b57cec5SDimitry Andric                                       XAEnd = X.pack_end(),
3530b57cec5SDimitry Andric                                          YA = Y.pack_begin();
3540b57cec5SDimitry Andric          XA != XAEnd; ++XA, ++YA) {
3550b57cec5SDimitry Andric       TemplateArgument Merged = checkDeducedTemplateArguments(
3560b57cec5SDimitry Andric           Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
3570b57cec5SDimitry Andric           DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()));
3585ffd83dbSDimitry Andric       if (Merged.isNull() && !(XA->isNull() && YA->isNull()))
3590b57cec5SDimitry Andric         return DeducedTemplateArgument();
3600b57cec5SDimitry Andric       NewPack.push_back(Merged);
3610b57cec5SDimitry Andric     }
3620b57cec5SDimitry Andric 
3630b57cec5SDimitry Andric     return DeducedTemplateArgument(
3640b57cec5SDimitry Andric         TemplateArgument::CreatePackCopy(Context, NewPack),
3650b57cec5SDimitry Andric         X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
3660b57cec5SDimitry Andric   }
3670b57cec5SDimitry Andric   }
3680b57cec5SDimitry Andric 
3690b57cec5SDimitry Andric   llvm_unreachable("Invalid TemplateArgument Kind!");
3700b57cec5SDimitry Andric }
3710b57cec5SDimitry Andric 
3720b57cec5SDimitry Andric /// Deduce the value of the given non-type template parameter
3730b57cec5SDimitry Andric /// as the given deduced template argument. All non-type template parameter
3740b57cec5SDimitry Andric /// deduction is funneled through here.
3750b57cec5SDimitry Andric static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
3760b57cec5SDimitry Andric     Sema &S, TemplateParameterList *TemplateParams,
3770b57cec5SDimitry Andric     NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced,
3780b57cec5SDimitry Andric     QualType ValueType, TemplateDeductionInfo &Info,
3790b57cec5SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
3800b57cec5SDimitry Andric   assert(NTTP->getDepth() == Info.getDeducedDepth() &&
3810b57cec5SDimitry Andric          "deducing non-type template argument with wrong depth");
3820b57cec5SDimitry Andric 
3830b57cec5SDimitry Andric   DeducedTemplateArgument Result = checkDeducedTemplateArguments(
3840b57cec5SDimitry Andric       S.Context, Deduced[NTTP->getIndex()], NewDeduced);
3850b57cec5SDimitry Andric   if (Result.isNull()) {
3860b57cec5SDimitry Andric     Info.Param = NTTP;
3870b57cec5SDimitry Andric     Info.FirstArg = Deduced[NTTP->getIndex()];
3880b57cec5SDimitry Andric     Info.SecondArg = NewDeduced;
3890b57cec5SDimitry Andric     return Sema::TDK_Inconsistent;
3900b57cec5SDimitry Andric   }
3910b57cec5SDimitry Andric 
3920b57cec5SDimitry Andric   Deduced[NTTP->getIndex()] = Result;
3930b57cec5SDimitry Andric   if (!S.getLangOpts().CPlusPlus17)
3940b57cec5SDimitry Andric     return Sema::TDK_Success;
3950b57cec5SDimitry Andric 
3960b57cec5SDimitry Andric   if (NTTP->isExpandedParameterPack())
3970b57cec5SDimitry Andric     // FIXME: We may still need to deduce parts of the type here! But we
3980b57cec5SDimitry Andric     // don't have any way to find which slice of the type to use, and the
3990b57cec5SDimitry Andric     // type stored on the NTTP itself is nonsense. Perhaps the type of an
4000b57cec5SDimitry Andric     // expanded NTTP should be a pack expansion type?
4010b57cec5SDimitry Andric     return Sema::TDK_Success;
4020b57cec5SDimitry Andric 
4030b57cec5SDimitry Andric   // Get the type of the parameter for deduction. If it's a (dependent) array
4040b57cec5SDimitry Andric   // or function type, we will not have decayed it yet, so do that now.
4050b57cec5SDimitry Andric   QualType ParamType = S.Context.getAdjustedParameterType(NTTP->getType());
4060b57cec5SDimitry Andric   if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
4070b57cec5SDimitry Andric     ParamType = Expansion->getPattern();
4080b57cec5SDimitry Andric 
4090b57cec5SDimitry Andric   // FIXME: It's not clear how deduction of a parameter of reference
4100b57cec5SDimitry Andric   // type from an argument (of non-reference type) should be performed.
4110b57cec5SDimitry Andric   // For now, we just remove reference types from both sides and let
4120b57cec5SDimitry Andric   // the final check for matching types sort out the mess.
4130b57cec5SDimitry Andric   return DeduceTemplateArgumentsByTypeMatch(
4140b57cec5SDimitry Andric       S, TemplateParams, ParamType.getNonReferenceType(),
4150b57cec5SDimitry Andric       ValueType.getNonReferenceType(), Info, Deduced, TDF_SkipNonDependent,
4160b57cec5SDimitry Andric       /*PartialOrdering=*/false,
4170b57cec5SDimitry Andric       /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound());
4180b57cec5SDimitry Andric }
4190b57cec5SDimitry Andric 
4200b57cec5SDimitry Andric /// Deduce the value of the given non-type template parameter
4210b57cec5SDimitry Andric /// from the given integral constant.
4220b57cec5SDimitry Andric static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
4230b57cec5SDimitry Andric     Sema &S, TemplateParameterList *TemplateParams,
4240b57cec5SDimitry Andric     NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
4250b57cec5SDimitry Andric     QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
4260b57cec5SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
4270b57cec5SDimitry Andric   return DeduceNonTypeTemplateArgument(
4280b57cec5SDimitry Andric       S, TemplateParams, NTTP,
4290b57cec5SDimitry Andric       DeducedTemplateArgument(S.Context, Value, ValueType,
4300b57cec5SDimitry Andric                               DeducedFromArrayBound),
4310b57cec5SDimitry Andric       ValueType, Info, Deduced);
4320b57cec5SDimitry Andric }
4330b57cec5SDimitry Andric 
4340b57cec5SDimitry Andric /// Deduce the value of the given non-type template parameter
4350b57cec5SDimitry Andric /// from the given null pointer template argument type.
4360b57cec5SDimitry Andric static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
4370b57cec5SDimitry Andric     Sema &S, TemplateParameterList *TemplateParams,
4380b57cec5SDimitry Andric     NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
4390b57cec5SDimitry Andric     TemplateDeductionInfo &Info,
4400b57cec5SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
4410b57cec5SDimitry Andric   Expr *Value =
4420b57cec5SDimitry Andric       S.ImpCastExprToType(new (S.Context) CXXNullPtrLiteralExpr(
4430b57cec5SDimitry Andric                               S.Context.NullPtrTy, NTTP->getLocation()),
4440b57cec5SDimitry Andric                           NullPtrType, CK_NullToPointer)
4450b57cec5SDimitry Andric           .get();
4460b57cec5SDimitry Andric   return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
4470b57cec5SDimitry Andric                                        DeducedTemplateArgument(Value),
4480b57cec5SDimitry Andric                                        Value->getType(), Info, Deduced);
4490b57cec5SDimitry Andric }
4500b57cec5SDimitry Andric 
4510b57cec5SDimitry Andric /// Deduce the value of the given non-type template parameter
4520b57cec5SDimitry Andric /// from the given type- or value-dependent expression.
4530b57cec5SDimitry Andric ///
4540b57cec5SDimitry Andric /// \returns true if deduction succeeded, false otherwise.
4550b57cec5SDimitry Andric static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
4560b57cec5SDimitry Andric     Sema &S, TemplateParameterList *TemplateParams,
4570b57cec5SDimitry Andric     NonTypeTemplateParmDecl *NTTP, Expr *Value, TemplateDeductionInfo &Info,
4580b57cec5SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
4590b57cec5SDimitry Andric   return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
4600b57cec5SDimitry Andric                                        DeducedTemplateArgument(Value),
4610b57cec5SDimitry Andric                                        Value->getType(), Info, Deduced);
4620b57cec5SDimitry Andric }
4630b57cec5SDimitry Andric 
4640b57cec5SDimitry Andric /// Deduce the value of the given non-type template parameter
4650b57cec5SDimitry Andric /// from the given declaration.
4660b57cec5SDimitry Andric ///
4670b57cec5SDimitry Andric /// \returns true if deduction succeeded, false otherwise.
4680b57cec5SDimitry Andric static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
4690b57cec5SDimitry Andric     Sema &S, TemplateParameterList *TemplateParams,
4700b57cec5SDimitry Andric     NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
4710b57cec5SDimitry Andric     TemplateDeductionInfo &Info,
4720b57cec5SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
4730b57cec5SDimitry Andric   D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
4740b57cec5SDimitry Andric   TemplateArgument New(D, T);
4750b57cec5SDimitry Andric   return DeduceNonTypeTemplateArgument(
4760b57cec5SDimitry Andric       S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
4770b57cec5SDimitry Andric }
4780b57cec5SDimitry Andric 
4790b57cec5SDimitry Andric static Sema::TemplateDeductionResult
4800b57cec5SDimitry Andric DeduceTemplateArguments(Sema &S,
4810b57cec5SDimitry Andric                         TemplateParameterList *TemplateParams,
4820b57cec5SDimitry Andric                         TemplateName Param,
4830b57cec5SDimitry Andric                         TemplateName Arg,
4840b57cec5SDimitry Andric                         TemplateDeductionInfo &Info,
4850b57cec5SDimitry Andric                         SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
4860b57cec5SDimitry Andric   TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
4870b57cec5SDimitry Andric   if (!ParamDecl) {
4880b57cec5SDimitry Andric     // The parameter type is dependent and is not a template template parameter,
4890b57cec5SDimitry Andric     // so there is nothing that we can deduce.
4900b57cec5SDimitry Andric     return Sema::TDK_Success;
4910b57cec5SDimitry Andric   }
4920b57cec5SDimitry Andric 
4930b57cec5SDimitry Andric   if (TemplateTemplateParmDecl *TempParam
4940b57cec5SDimitry Andric         = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
4950b57cec5SDimitry Andric     // If we're not deducing at this depth, there's nothing to deduce.
4960b57cec5SDimitry Andric     if (TempParam->getDepth() != Info.getDeducedDepth())
4970b57cec5SDimitry Andric       return Sema::TDK_Success;
4980b57cec5SDimitry Andric 
4990b57cec5SDimitry Andric     DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
5000b57cec5SDimitry Andric     DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
5010b57cec5SDimitry Andric                                                  Deduced[TempParam->getIndex()],
5020b57cec5SDimitry Andric                                                                    NewDeduced);
5030b57cec5SDimitry Andric     if (Result.isNull()) {
5040b57cec5SDimitry Andric       Info.Param = TempParam;
5050b57cec5SDimitry Andric       Info.FirstArg = Deduced[TempParam->getIndex()];
5060b57cec5SDimitry Andric       Info.SecondArg = NewDeduced;
5070b57cec5SDimitry Andric       return Sema::TDK_Inconsistent;
5080b57cec5SDimitry Andric     }
5090b57cec5SDimitry Andric 
5100b57cec5SDimitry Andric     Deduced[TempParam->getIndex()] = Result;
5110b57cec5SDimitry Andric     return Sema::TDK_Success;
5120b57cec5SDimitry Andric   }
5130b57cec5SDimitry Andric 
5140b57cec5SDimitry Andric   // Verify that the two template names are equivalent.
5150b57cec5SDimitry Andric   if (S.Context.hasSameTemplateName(Param, Arg))
5160b57cec5SDimitry Andric     return Sema::TDK_Success;
5170b57cec5SDimitry Andric 
5180b57cec5SDimitry Andric   // Mismatch of non-dependent template parameter to argument.
5190b57cec5SDimitry Andric   Info.FirstArg = TemplateArgument(Param);
5200b57cec5SDimitry Andric   Info.SecondArg = TemplateArgument(Arg);
5210b57cec5SDimitry Andric   return Sema::TDK_NonDeducedMismatch;
5220b57cec5SDimitry Andric }
5230b57cec5SDimitry Andric 
5240b57cec5SDimitry Andric /// Deduce the template arguments by comparing the template parameter
5250b57cec5SDimitry Andric /// type (which is a template-id) with the template argument type.
5260b57cec5SDimitry Andric ///
5270b57cec5SDimitry Andric /// \param S the Sema
5280b57cec5SDimitry Andric ///
5290b57cec5SDimitry Andric /// \param TemplateParams the template parameters that we are deducing
5300b57cec5SDimitry Andric ///
5310b57cec5SDimitry Andric /// \param Param the parameter type
5320b57cec5SDimitry Andric ///
5330b57cec5SDimitry Andric /// \param Arg the argument type
5340b57cec5SDimitry Andric ///
5350b57cec5SDimitry Andric /// \param Info information about the template argument deduction itself
5360b57cec5SDimitry Andric ///
5370b57cec5SDimitry Andric /// \param Deduced the deduced template arguments
5380b57cec5SDimitry Andric ///
5390b57cec5SDimitry Andric /// \returns the result of template argument deduction so far. Note that a
5400b57cec5SDimitry Andric /// "success" result means that template argument deduction has not yet failed,
5410b57cec5SDimitry Andric /// but it may still fail, later, for other reasons.
5420b57cec5SDimitry Andric static Sema::TemplateDeductionResult
5430b57cec5SDimitry Andric DeduceTemplateArguments(Sema &S,
5440b57cec5SDimitry Andric                         TemplateParameterList *TemplateParams,
5450b57cec5SDimitry Andric                         const TemplateSpecializationType *Param,
5460b57cec5SDimitry Andric                         QualType Arg,
5470b57cec5SDimitry Andric                         TemplateDeductionInfo &Info,
5480b57cec5SDimitry Andric                         SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
5490b57cec5SDimitry Andric   assert(Arg.isCanonical() && "Argument type must be canonical");
5500b57cec5SDimitry Andric 
5510b57cec5SDimitry Andric   // Treat an injected-class-name as its underlying template-id.
5520b57cec5SDimitry Andric   if (auto *Injected = dyn_cast<InjectedClassNameType>(Arg))
5530b57cec5SDimitry Andric     Arg = Injected->getInjectedSpecializationType();
5540b57cec5SDimitry Andric 
5550b57cec5SDimitry Andric   // Check whether the template argument is a dependent template-id.
5560b57cec5SDimitry Andric   if (const TemplateSpecializationType *SpecArg
5570b57cec5SDimitry Andric         = dyn_cast<TemplateSpecializationType>(Arg)) {
5580b57cec5SDimitry Andric     // Perform template argument deduction for the template name.
5590b57cec5SDimitry Andric     if (Sema::TemplateDeductionResult Result
5600b57cec5SDimitry Andric           = DeduceTemplateArguments(S, TemplateParams,
5610b57cec5SDimitry Andric                                     Param->getTemplateName(),
5620b57cec5SDimitry Andric                                     SpecArg->getTemplateName(),
5630b57cec5SDimitry Andric                                     Info, Deduced))
5640b57cec5SDimitry Andric       return Result;
5650b57cec5SDimitry Andric 
5660b57cec5SDimitry Andric 
5670b57cec5SDimitry Andric     // Perform template argument deduction on each template
5680b57cec5SDimitry Andric     // argument. Ignore any missing/extra arguments, since they could be
5690b57cec5SDimitry Andric     // filled in by default arguments.
5700b57cec5SDimitry Andric     return DeduceTemplateArguments(S, TemplateParams,
5710b57cec5SDimitry Andric                                    Param->template_arguments(),
5720b57cec5SDimitry Andric                                    SpecArg->template_arguments(), Info, Deduced,
5730b57cec5SDimitry Andric                                    /*NumberOfArgumentsMustMatch=*/false);
5740b57cec5SDimitry Andric   }
5750b57cec5SDimitry Andric 
5760b57cec5SDimitry Andric   // If the argument type is a class template specialization, we
5770b57cec5SDimitry Andric   // perform template argument deduction using its template
5780b57cec5SDimitry Andric   // arguments.
5790b57cec5SDimitry Andric   const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
5800b57cec5SDimitry Andric   if (!RecordArg) {
5810b57cec5SDimitry Andric     Info.FirstArg = TemplateArgument(QualType(Param, 0));
5820b57cec5SDimitry Andric     Info.SecondArg = TemplateArgument(Arg);
5830b57cec5SDimitry Andric     return Sema::TDK_NonDeducedMismatch;
5840b57cec5SDimitry Andric   }
5850b57cec5SDimitry Andric 
5860b57cec5SDimitry Andric   ClassTemplateSpecializationDecl *SpecArg
5870b57cec5SDimitry Andric     = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
5880b57cec5SDimitry Andric   if (!SpecArg) {
5890b57cec5SDimitry Andric     Info.FirstArg = TemplateArgument(QualType(Param, 0));
5900b57cec5SDimitry Andric     Info.SecondArg = TemplateArgument(Arg);
5910b57cec5SDimitry Andric     return Sema::TDK_NonDeducedMismatch;
5920b57cec5SDimitry Andric   }
5930b57cec5SDimitry Andric 
5940b57cec5SDimitry Andric   // Perform template argument deduction for the template name.
5950b57cec5SDimitry Andric   if (Sema::TemplateDeductionResult Result
5960b57cec5SDimitry Andric         = DeduceTemplateArguments(S,
5970b57cec5SDimitry Andric                                   TemplateParams,
5980b57cec5SDimitry Andric                                   Param->getTemplateName(),
5990b57cec5SDimitry Andric                                TemplateName(SpecArg->getSpecializedTemplate()),
6000b57cec5SDimitry Andric                                   Info, Deduced))
6010b57cec5SDimitry Andric     return Result;
6020b57cec5SDimitry Andric 
6030b57cec5SDimitry Andric   // Perform template argument deduction for the template arguments.
6040b57cec5SDimitry Andric   return DeduceTemplateArguments(S, TemplateParams, Param->template_arguments(),
6050b57cec5SDimitry Andric                                  SpecArg->getTemplateArgs().asArray(), Info,
6060b57cec5SDimitry Andric                                  Deduced, /*NumberOfArgumentsMustMatch=*/true);
6070b57cec5SDimitry Andric }
6080b57cec5SDimitry Andric 
6090b57cec5SDimitry Andric /// Determines whether the given type is an opaque type that
6100b57cec5SDimitry Andric /// might be more qualified when instantiated.
6110b57cec5SDimitry Andric static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
6120b57cec5SDimitry Andric   switch (T->getTypeClass()) {
6130b57cec5SDimitry Andric   case Type::TypeOfExpr:
6140b57cec5SDimitry Andric   case Type::TypeOf:
6150b57cec5SDimitry Andric   case Type::DependentName:
6160b57cec5SDimitry Andric   case Type::Decltype:
6170b57cec5SDimitry Andric   case Type::UnresolvedUsing:
6180b57cec5SDimitry Andric   case Type::TemplateTypeParm:
6190b57cec5SDimitry Andric     return true;
6200b57cec5SDimitry Andric 
6210b57cec5SDimitry Andric   case Type::ConstantArray:
6220b57cec5SDimitry Andric   case Type::IncompleteArray:
6230b57cec5SDimitry Andric   case Type::VariableArray:
6240b57cec5SDimitry Andric   case Type::DependentSizedArray:
6250b57cec5SDimitry Andric     return IsPossiblyOpaquelyQualifiedType(
6260b57cec5SDimitry Andric                                       cast<ArrayType>(T)->getElementType());
6270b57cec5SDimitry Andric 
6280b57cec5SDimitry Andric   default:
6290b57cec5SDimitry Andric     return false;
6300b57cec5SDimitry Andric   }
6310b57cec5SDimitry Andric }
6320b57cec5SDimitry Andric 
6330b57cec5SDimitry Andric /// Helper function to build a TemplateParameter when we don't
6340b57cec5SDimitry Andric /// know its type statically.
6350b57cec5SDimitry Andric static TemplateParameter makeTemplateParameter(Decl *D) {
6360b57cec5SDimitry Andric   if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
6370b57cec5SDimitry Andric     return TemplateParameter(TTP);
6380b57cec5SDimitry Andric   if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
6390b57cec5SDimitry Andric     return TemplateParameter(NTTP);
6400b57cec5SDimitry Andric 
6410b57cec5SDimitry Andric   return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
6420b57cec5SDimitry Andric }
6430b57cec5SDimitry Andric 
6440b57cec5SDimitry Andric /// If \p Param is an expanded parameter pack, get the number of expansions.
6450b57cec5SDimitry Andric static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
646480093f4SDimitry Andric   if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
647480093f4SDimitry Andric     if (TTP->isExpandedParameterPack())
648480093f4SDimitry Andric       return TTP->getNumExpansionParameters();
649480093f4SDimitry Andric 
6500b57cec5SDimitry Andric   if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
6510b57cec5SDimitry Andric     if (NTTP->isExpandedParameterPack())
6520b57cec5SDimitry Andric       return NTTP->getNumExpansionTypes();
6530b57cec5SDimitry Andric 
6540b57cec5SDimitry Andric   if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param))
6550b57cec5SDimitry Andric     if (TTP->isExpandedParameterPack())
6560b57cec5SDimitry Andric       return TTP->getNumExpansionTemplateParameters();
6570b57cec5SDimitry Andric 
6580b57cec5SDimitry Andric   return None;
6590b57cec5SDimitry Andric }
6600b57cec5SDimitry Andric 
6610b57cec5SDimitry Andric /// A pack that we're currently deducing.
6620b57cec5SDimitry Andric struct clang::DeducedPack {
6630b57cec5SDimitry Andric   // The index of the pack.
6640b57cec5SDimitry Andric   unsigned Index;
6650b57cec5SDimitry Andric 
6660b57cec5SDimitry Andric   // The old value of the pack before we started deducing it.
6670b57cec5SDimitry Andric   DeducedTemplateArgument Saved;
6680b57cec5SDimitry Andric 
6690b57cec5SDimitry Andric   // A deferred value of this pack from an inner deduction, that couldn't be
6700b57cec5SDimitry Andric   // deduced because this deduction hadn't happened yet.
6710b57cec5SDimitry Andric   DeducedTemplateArgument DeferredDeduction;
6720b57cec5SDimitry Andric 
6730b57cec5SDimitry Andric   // The new value of the pack.
6740b57cec5SDimitry Andric   SmallVector<DeducedTemplateArgument, 4> New;
6750b57cec5SDimitry Andric 
6760b57cec5SDimitry Andric   // The outer deduction for this pack, if any.
6770b57cec5SDimitry Andric   DeducedPack *Outer = nullptr;
6780b57cec5SDimitry Andric 
6790b57cec5SDimitry Andric   DeducedPack(unsigned Index) : Index(Index) {}
6800b57cec5SDimitry Andric };
6810b57cec5SDimitry Andric 
6820b57cec5SDimitry Andric namespace {
6830b57cec5SDimitry Andric 
6840b57cec5SDimitry Andric /// A scope in which we're performing pack deduction.
6850b57cec5SDimitry Andric class PackDeductionScope {
6860b57cec5SDimitry Andric public:
6870b57cec5SDimitry Andric   /// Prepare to deduce the packs named within Pattern.
6880b57cec5SDimitry Andric   PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
6890b57cec5SDimitry Andric                      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6900b57cec5SDimitry Andric                      TemplateDeductionInfo &Info, TemplateArgument Pattern)
6910b57cec5SDimitry Andric       : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
6920b57cec5SDimitry Andric     unsigned NumNamedPacks = addPacks(Pattern);
6930b57cec5SDimitry Andric     finishConstruction(NumNamedPacks);
6940b57cec5SDimitry Andric   }
6950b57cec5SDimitry Andric 
6960b57cec5SDimitry Andric   /// Prepare to directly deduce arguments of the parameter with index \p Index.
6970b57cec5SDimitry Andric   PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
6980b57cec5SDimitry Andric                      SmallVectorImpl<DeducedTemplateArgument> &Deduced,
6990b57cec5SDimitry Andric                      TemplateDeductionInfo &Info, unsigned Index)
7000b57cec5SDimitry Andric       : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
7010b57cec5SDimitry Andric     addPack(Index);
7020b57cec5SDimitry Andric     finishConstruction(1);
7030b57cec5SDimitry Andric   }
7040b57cec5SDimitry Andric 
7050b57cec5SDimitry Andric private:
7060b57cec5SDimitry Andric   void addPack(unsigned Index) {
7070b57cec5SDimitry Andric     // Save the deduced template argument for the parameter pack expanded
7080b57cec5SDimitry Andric     // by this pack expansion, then clear out the deduction.
7090b57cec5SDimitry Andric     DeducedPack Pack(Index);
7100b57cec5SDimitry Andric     Pack.Saved = Deduced[Index];
7110b57cec5SDimitry Andric     Deduced[Index] = TemplateArgument();
7120b57cec5SDimitry Andric 
7130b57cec5SDimitry Andric     // FIXME: What if we encounter multiple packs with different numbers of
7140b57cec5SDimitry Andric     // pre-expanded expansions? (This should already have been diagnosed
7150b57cec5SDimitry Andric     // during substitution.)
7160b57cec5SDimitry Andric     if (Optional<unsigned> ExpandedPackExpansions =
7170b57cec5SDimitry Andric             getExpandedPackSize(TemplateParams->getParam(Index)))
7180b57cec5SDimitry Andric       FixedNumExpansions = ExpandedPackExpansions;
7190b57cec5SDimitry Andric 
7200b57cec5SDimitry Andric     Packs.push_back(Pack);
7210b57cec5SDimitry Andric   }
7220b57cec5SDimitry Andric 
7230b57cec5SDimitry Andric   unsigned addPacks(TemplateArgument Pattern) {
7240b57cec5SDimitry Andric     // Compute the set of template parameter indices that correspond to
7250b57cec5SDimitry Andric     // parameter packs expanded by the pack expansion.
7260b57cec5SDimitry Andric     llvm::SmallBitVector SawIndices(TemplateParams->size());
72755e4f9d5SDimitry Andric     llvm::SmallVector<TemplateArgument, 4> ExtraDeductions;
7280b57cec5SDimitry Andric 
7290b57cec5SDimitry Andric     auto AddPack = [&](unsigned Index) {
7300b57cec5SDimitry Andric       if (SawIndices[Index])
7310b57cec5SDimitry Andric         return;
7320b57cec5SDimitry Andric       SawIndices[Index] = true;
7330b57cec5SDimitry Andric       addPack(Index);
73455e4f9d5SDimitry Andric 
73555e4f9d5SDimitry Andric       // Deducing a parameter pack that is a pack expansion also constrains the
73655e4f9d5SDimitry Andric       // packs appearing in that parameter to have the same deduced arity. Also,
73755e4f9d5SDimitry Andric       // in C++17 onwards, deducing a non-type template parameter deduces its
73855e4f9d5SDimitry Andric       // type, so we need to collect the pending deduced values for those packs.
73955e4f9d5SDimitry Andric       if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(
74055e4f9d5SDimitry Andric               TemplateParams->getParam(Index))) {
7415ffd83dbSDimitry Andric         if (!NTTP->isExpandedParameterPack())
74255e4f9d5SDimitry Andric           if (auto *Expansion = dyn_cast<PackExpansionType>(NTTP->getType()))
74355e4f9d5SDimitry Andric             ExtraDeductions.push_back(Expansion->getPattern());
74455e4f9d5SDimitry Andric       }
74555e4f9d5SDimitry Andric       // FIXME: Also collect the unexpanded packs in any type and template
74655e4f9d5SDimitry Andric       // parameter packs that are pack expansions.
7470b57cec5SDimitry Andric     };
7480b57cec5SDimitry Andric 
74955e4f9d5SDimitry Andric     auto Collect = [&](TemplateArgument Pattern) {
7500b57cec5SDimitry Andric       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
7510b57cec5SDimitry Andric       S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
7520b57cec5SDimitry Andric       for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
7530b57cec5SDimitry Andric         unsigned Depth, Index;
7540b57cec5SDimitry Andric         std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
7550b57cec5SDimitry Andric         if (Depth == Info.getDeducedDepth())
7560b57cec5SDimitry Andric           AddPack(Index);
7570b57cec5SDimitry Andric       }
75855e4f9d5SDimitry Andric     };
75955e4f9d5SDimitry Andric 
76055e4f9d5SDimitry Andric     // Look for unexpanded packs in the pattern.
76155e4f9d5SDimitry Andric     Collect(Pattern);
7620b57cec5SDimitry Andric     assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric     unsigned NumNamedPacks = Packs.size();
7650b57cec5SDimitry Andric 
76655e4f9d5SDimitry Andric     // Also look for unexpanded packs that are indirectly deduced by deducing
76755e4f9d5SDimitry Andric     // the sizes of the packs in this pattern.
76855e4f9d5SDimitry Andric     while (!ExtraDeductions.empty())
76955e4f9d5SDimitry Andric       Collect(ExtraDeductions.pop_back_val());
7700b57cec5SDimitry Andric 
7710b57cec5SDimitry Andric     return NumNamedPacks;
7720b57cec5SDimitry Andric   }
7730b57cec5SDimitry Andric 
7740b57cec5SDimitry Andric   void finishConstruction(unsigned NumNamedPacks) {
7750b57cec5SDimitry Andric     // Dig out the partially-substituted pack, if there is one.
7760b57cec5SDimitry Andric     const TemplateArgument *PartialPackArgs = nullptr;
7770b57cec5SDimitry Andric     unsigned NumPartialPackArgs = 0;
7780b57cec5SDimitry Andric     std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
7790b57cec5SDimitry Andric     if (auto *Scope = S.CurrentInstantiationScope)
7800b57cec5SDimitry Andric       if (auto *Partial = Scope->getPartiallySubstitutedPack(
7810b57cec5SDimitry Andric               &PartialPackArgs, &NumPartialPackArgs))
7820b57cec5SDimitry Andric         PartialPackDepthIndex = getDepthAndIndex(Partial);
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric     // This pack expansion will have been partially or fully expanded if
7850b57cec5SDimitry Andric     // it only names explicitly-specified parameter packs (including the
7860b57cec5SDimitry Andric     // partially-substituted one, if any).
7870b57cec5SDimitry Andric     bool IsExpanded = true;
7880b57cec5SDimitry Andric     for (unsigned I = 0; I != NumNamedPacks; ++I) {
7890b57cec5SDimitry Andric       if (Packs[I].Index >= Info.getNumExplicitArgs()) {
7900b57cec5SDimitry Andric         IsExpanded = false;
7910b57cec5SDimitry Andric         IsPartiallyExpanded = false;
7920b57cec5SDimitry Andric         break;
7930b57cec5SDimitry Andric       }
7940b57cec5SDimitry Andric       if (PartialPackDepthIndex ==
7950b57cec5SDimitry Andric             std::make_pair(Info.getDeducedDepth(), Packs[I].Index)) {
7960b57cec5SDimitry Andric         IsPartiallyExpanded = true;
7970b57cec5SDimitry Andric       }
7980b57cec5SDimitry Andric     }
7990b57cec5SDimitry Andric 
8000b57cec5SDimitry Andric     // Skip over the pack elements that were expanded into separate arguments.
8010b57cec5SDimitry Andric     // If we partially expanded, this is the number of partial arguments.
8020b57cec5SDimitry Andric     if (IsPartiallyExpanded)
8030b57cec5SDimitry Andric       PackElements += NumPartialPackArgs;
8040b57cec5SDimitry Andric     else if (IsExpanded)
8050b57cec5SDimitry Andric       PackElements += *FixedNumExpansions;
8060b57cec5SDimitry Andric 
8070b57cec5SDimitry Andric     for (auto &Pack : Packs) {
8080b57cec5SDimitry Andric       if (Info.PendingDeducedPacks.size() > Pack.Index)
8090b57cec5SDimitry Andric         Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
8100b57cec5SDimitry Andric       else
8110b57cec5SDimitry Andric         Info.PendingDeducedPacks.resize(Pack.Index + 1);
8120b57cec5SDimitry Andric       Info.PendingDeducedPacks[Pack.Index] = &Pack;
8130b57cec5SDimitry Andric 
8140b57cec5SDimitry Andric       if (PartialPackDepthIndex ==
8150b57cec5SDimitry Andric             std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
8160b57cec5SDimitry Andric         Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
8170b57cec5SDimitry Andric         // We pre-populate the deduced value of the partially-substituted
8180b57cec5SDimitry Andric         // pack with the specified value. This is not entirely correct: the
8190b57cec5SDimitry Andric         // value is supposed to have been substituted, not deduced, but the
8200b57cec5SDimitry Andric         // cases where this is observable require an exact type match anyway.
8210b57cec5SDimitry Andric         //
8220b57cec5SDimitry Andric         // FIXME: If we could represent a "depth i, index j, pack elem k"
8230b57cec5SDimitry Andric         // parameter, we could substitute the partially-substituted pack
8240b57cec5SDimitry Andric         // everywhere and avoid this.
8250b57cec5SDimitry Andric         if (!IsPartiallyExpanded)
8260b57cec5SDimitry Andric           Deduced[Pack.Index] = Pack.New[PackElements];
8270b57cec5SDimitry Andric       }
8280b57cec5SDimitry Andric     }
8290b57cec5SDimitry Andric   }
8300b57cec5SDimitry Andric 
8310b57cec5SDimitry Andric public:
8320b57cec5SDimitry Andric   ~PackDeductionScope() {
8330b57cec5SDimitry Andric     for (auto &Pack : Packs)
8340b57cec5SDimitry Andric       Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
8350b57cec5SDimitry Andric   }
8360b57cec5SDimitry Andric 
8370b57cec5SDimitry Andric   /// Determine whether this pack has already been partially expanded into a
8380b57cec5SDimitry Andric   /// sequence of (prior) function parameters / template arguments.
8390b57cec5SDimitry Andric   bool isPartiallyExpanded() { return IsPartiallyExpanded; }
8400b57cec5SDimitry Andric 
8410b57cec5SDimitry Andric   /// Determine whether this pack expansion scope has a known, fixed arity.
8420b57cec5SDimitry Andric   /// This happens if it involves a pack from an outer template that has
8430b57cec5SDimitry Andric   /// (notionally) already been expanded.
8440b57cec5SDimitry Andric   bool hasFixedArity() { return FixedNumExpansions.hasValue(); }
8450b57cec5SDimitry Andric 
8460b57cec5SDimitry Andric   /// Determine whether the next element of the argument is still part of this
8470b57cec5SDimitry Andric   /// pack. This is the case unless the pack is already expanded to a fixed
8480b57cec5SDimitry Andric   /// length.
8490b57cec5SDimitry Andric   bool hasNextElement() {
8500b57cec5SDimitry Andric     return !FixedNumExpansions || *FixedNumExpansions > PackElements;
8510b57cec5SDimitry Andric   }
8520b57cec5SDimitry Andric 
8530b57cec5SDimitry Andric   /// Move to deducing the next element in each pack that is being deduced.
8540b57cec5SDimitry Andric   void nextPackElement() {
8550b57cec5SDimitry Andric     // Capture the deduced template arguments for each parameter pack expanded
8560b57cec5SDimitry Andric     // by this pack expansion, add them to the list of arguments we've deduced
8570b57cec5SDimitry Andric     // for that pack, then clear out the deduced argument.
8580b57cec5SDimitry Andric     for (auto &Pack : Packs) {
8590b57cec5SDimitry Andric       DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
8600b57cec5SDimitry Andric       if (!Pack.New.empty() || !DeducedArg.isNull()) {
8610b57cec5SDimitry Andric         while (Pack.New.size() < PackElements)
8620b57cec5SDimitry Andric           Pack.New.push_back(DeducedTemplateArgument());
8630b57cec5SDimitry Andric         if (Pack.New.size() == PackElements)
8640b57cec5SDimitry Andric           Pack.New.push_back(DeducedArg);
8650b57cec5SDimitry Andric         else
8660b57cec5SDimitry Andric           Pack.New[PackElements] = DeducedArg;
8670b57cec5SDimitry Andric         DeducedArg = Pack.New.size() > PackElements + 1
8680b57cec5SDimitry Andric                          ? Pack.New[PackElements + 1]
8690b57cec5SDimitry Andric                          : DeducedTemplateArgument();
8700b57cec5SDimitry Andric       }
8710b57cec5SDimitry Andric     }
8720b57cec5SDimitry Andric     ++PackElements;
8730b57cec5SDimitry Andric   }
8740b57cec5SDimitry Andric 
8750b57cec5SDimitry Andric   /// Finish template argument deduction for a set of argument packs,
8760b57cec5SDimitry Andric   /// producing the argument packs and checking for consistency with prior
8770b57cec5SDimitry Andric   /// deductions.
878480093f4SDimitry Andric   Sema::TemplateDeductionResult finish() {
8790b57cec5SDimitry Andric     // Build argument packs for each of the parameter packs expanded by this
8800b57cec5SDimitry Andric     // pack expansion.
8810b57cec5SDimitry Andric     for (auto &Pack : Packs) {
8820b57cec5SDimitry Andric       // Put back the old value for this pack.
8830b57cec5SDimitry Andric       Deduced[Pack.Index] = Pack.Saved;
8840b57cec5SDimitry Andric 
885480093f4SDimitry Andric       // Always make sure the size of this pack is correct, even if we didn't
886480093f4SDimitry Andric       // deduce any values for it.
887480093f4SDimitry Andric       //
888480093f4SDimitry Andric       // FIXME: This isn't required by the normative wording, but substitution
889480093f4SDimitry Andric       // and post-substitution checking will always fail if the arity of any
890480093f4SDimitry Andric       // pack is not equal to the number of elements we processed. (Either that
891480093f4SDimitry Andric       // or something else has gone *very* wrong.) We're permitted to skip any
892480093f4SDimitry Andric       // hard errors from those follow-on steps by the intent (but not the
893480093f4SDimitry Andric       // wording) of C++ [temp.inst]p8:
894480093f4SDimitry Andric       //
895480093f4SDimitry Andric       //   If the function selected by overload resolution can be determined
896480093f4SDimitry Andric       //   without instantiating a class template definition, it is unspecified
897480093f4SDimitry Andric       //   whether that instantiation actually takes place
8980b57cec5SDimitry Andric       Pack.New.resize(PackElements);
8990b57cec5SDimitry Andric 
9000b57cec5SDimitry Andric       // Build or find a new value for this pack.
9010b57cec5SDimitry Andric       DeducedTemplateArgument NewPack;
902480093f4SDimitry Andric       if (Pack.New.empty()) {
9030b57cec5SDimitry Andric         // If we deduced an empty argument pack, create it now.
9040b57cec5SDimitry Andric         NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
9050b57cec5SDimitry Andric       } else {
9060b57cec5SDimitry Andric         TemplateArgument *ArgumentPack =
9070b57cec5SDimitry Andric             new (S.Context) TemplateArgument[Pack.New.size()];
9080b57cec5SDimitry Andric         std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
9090b57cec5SDimitry Andric         NewPack = DeducedTemplateArgument(
9100b57cec5SDimitry Andric             TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
9110b57cec5SDimitry Andric             // FIXME: This is wrong, it's possible that some pack elements are
9120b57cec5SDimitry Andric             // deduced from an array bound and others are not:
9130b57cec5SDimitry Andric             //   template<typename ...T, T ...V> void g(const T (&...p)[V]);
9140b57cec5SDimitry Andric             //   g({1, 2, 3}, {{}, {}});
9150b57cec5SDimitry Andric             // ... should deduce T = {int, size_t (from array bound)}.
9160b57cec5SDimitry Andric             Pack.New[0].wasDeducedFromArrayBound());
9170b57cec5SDimitry Andric       }
9180b57cec5SDimitry Andric 
9190b57cec5SDimitry Andric       // Pick where we're going to put the merged pack.
9200b57cec5SDimitry Andric       DeducedTemplateArgument *Loc;
9210b57cec5SDimitry Andric       if (Pack.Outer) {
9220b57cec5SDimitry Andric         if (Pack.Outer->DeferredDeduction.isNull()) {
9230b57cec5SDimitry Andric           // Defer checking this pack until we have a complete pack to compare
9240b57cec5SDimitry Andric           // it against.
9250b57cec5SDimitry Andric           Pack.Outer->DeferredDeduction = NewPack;
9260b57cec5SDimitry Andric           continue;
9270b57cec5SDimitry Andric         }
9280b57cec5SDimitry Andric         Loc = &Pack.Outer->DeferredDeduction;
9290b57cec5SDimitry Andric       } else {
9300b57cec5SDimitry Andric         Loc = &Deduced[Pack.Index];
9310b57cec5SDimitry Andric       }
9320b57cec5SDimitry Andric 
9330b57cec5SDimitry Andric       // Check the new pack matches any previous value.
9340b57cec5SDimitry Andric       DeducedTemplateArgument OldPack = *Loc;
9350b57cec5SDimitry Andric       DeducedTemplateArgument Result =
9360b57cec5SDimitry Andric           checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
9370b57cec5SDimitry Andric 
9380b57cec5SDimitry Andric       // If we deferred a deduction of this pack, check that one now too.
9390b57cec5SDimitry Andric       if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
9400b57cec5SDimitry Andric         OldPack = Result;
9410b57cec5SDimitry Andric         NewPack = Pack.DeferredDeduction;
9420b57cec5SDimitry Andric         Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
9430b57cec5SDimitry Andric       }
9440b57cec5SDimitry Andric 
9450b57cec5SDimitry Andric       NamedDecl *Param = TemplateParams->getParam(Pack.Index);
9460b57cec5SDimitry Andric       if (Result.isNull()) {
9470b57cec5SDimitry Andric         Info.Param = makeTemplateParameter(Param);
9480b57cec5SDimitry Andric         Info.FirstArg = OldPack;
9490b57cec5SDimitry Andric         Info.SecondArg = NewPack;
9500b57cec5SDimitry Andric         return Sema::TDK_Inconsistent;
9510b57cec5SDimitry Andric       }
9520b57cec5SDimitry Andric 
9530b57cec5SDimitry Andric       // If we have a pre-expanded pack and we didn't deduce enough elements
9540b57cec5SDimitry Andric       // for it, fail deduction.
9550b57cec5SDimitry Andric       if (Optional<unsigned> Expansions = getExpandedPackSize(Param)) {
9560b57cec5SDimitry Andric         if (*Expansions != PackElements) {
9570b57cec5SDimitry Andric           Info.Param = makeTemplateParameter(Param);
9580b57cec5SDimitry Andric           Info.FirstArg = Result;
9590b57cec5SDimitry Andric           return Sema::TDK_IncompletePack;
9600b57cec5SDimitry Andric         }
9610b57cec5SDimitry Andric       }
9620b57cec5SDimitry Andric 
9630b57cec5SDimitry Andric       *Loc = Result;
9640b57cec5SDimitry Andric     }
9650b57cec5SDimitry Andric 
9660b57cec5SDimitry Andric     return Sema::TDK_Success;
9670b57cec5SDimitry Andric   }
9680b57cec5SDimitry Andric 
9690b57cec5SDimitry Andric private:
9700b57cec5SDimitry Andric   Sema &S;
9710b57cec5SDimitry Andric   TemplateParameterList *TemplateParams;
9720b57cec5SDimitry Andric   SmallVectorImpl<DeducedTemplateArgument> &Deduced;
9730b57cec5SDimitry Andric   TemplateDeductionInfo &Info;
9740b57cec5SDimitry Andric   unsigned PackElements = 0;
9750b57cec5SDimitry Andric   bool IsPartiallyExpanded = false;
9760b57cec5SDimitry Andric   /// The number of expansions, if we have a fully-expanded pack in this scope.
9770b57cec5SDimitry Andric   Optional<unsigned> FixedNumExpansions;
9780b57cec5SDimitry Andric 
9790b57cec5SDimitry Andric   SmallVector<DeducedPack, 2> Packs;
9800b57cec5SDimitry Andric };
9810b57cec5SDimitry Andric 
9820b57cec5SDimitry Andric } // namespace
9830b57cec5SDimitry Andric 
9840b57cec5SDimitry Andric /// Deduce the template arguments by comparing the list of parameter
9850b57cec5SDimitry Andric /// types to the list of argument types, as in the parameter-type-lists of
9860b57cec5SDimitry Andric /// function types (C++ [temp.deduct.type]p10).
9870b57cec5SDimitry Andric ///
9880b57cec5SDimitry Andric /// \param S The semantic analysis object within which we are deducing
9890b57cec5SDimitry Andric ///
9900b57cec5SDimitry Andric /// \param TemplateParams The template parameters that we are deducing
9910b57cec5SDimitry Andric ///
9920b57cec5SDimitry Andric /// \param Params The list of parameter types
9930b57cec5SDimitry Andric ///
9940b57cec5SDimitry Andric /// \param NumParams The number of types in \c Params
9950b57cec5SDimitry Andric ///
9960b57cec5SDimitry Andric /// \param Args The list of argument types
9970b57cec5SDimitry Andric ///
9980b57cec5SDimitry Andric /// \param NumArgs The number of types in \c Args
9990b57cec5SDimitry Andric ///
10000b57cec5SDimitry Andric /// \param Info information about the template argument deduction itself
10010b57cec5SDimitry Andric ///
10020b57cec5SDimitry Andric /// \param Deduced the deduced template arguments
10030b57cec5SDimitry Andric ///
10040b57cec5SDimitry Andric /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
10050b57cec5SDimitry Andric /// how template argument deduction is performed.
10060b57cec5SDimitry Andric ///
10070b57cec5SDimitry Andric /// \param PartialOrdering If true, we are performing template argument
10080b57cec5SDimitry Andric /// deduction for during partial ordering for a call
10090b57cec5SDimitry Andric /// (C++0x [temp.deduct.partial]).
10100b57cec5SDimitry Andric ///
10110b57cec5SDimitry Andric /// \returns the result of template argument deduction so far. Note that a
10120b57cec5SDimitry Andric /// "success" result means that template argument deduction has not yet failed,
10130b57cec5SDimitry Andric /// but it may still fail, later, for other reasons.
10140b57cec5SDimitry Andric static Sema::TemplateDeductionResult
10150b57cec5SDimitry Andric DeduceTemplateArguments(Sema &S,
10160b57cec5SDimitry Andric                         TemplateParameterList *TemplateParams,
10170b57cec5SDimitry Andric                         const QualType *Params, unsigned NumParams,
10180b57cec5SDimitry Andric                         const QualType *Args, unsigned NumArgs,
10190b57cec5SDimitry Andric                         TemplateDeductionInfo &Info,
10200b57cec5SDimitry Andric                         SmallVectorImpl<DeducedTemplateArgument> &Deduced,
10210b57cec5SDimitry Andric                         unsigned TDF,
10220b57cec5SDimitry Andric                         bool PartialOrdering = false) {
10230b57cec5SDimitry Andric   // C++0x [temp.deduct.type]p10:
10240b57cec5SDimitry Andric   //   Similarly, if P has a form that contains (T), then each parameter type
10250b57cec5SDimitry Andric   //   Pi of the respective parameter-type- list of P is compared with the
10260b57cec5SDimitry Andric   //   corresponding parameter type Ai of the corresponding parameter-type-list
10270b57cec5SDimitry Andric   //   of A. [...]
10280b57cec5SDimitry Andric   unsigned ArgIdx = 0, ParamIdx = 0;
10290b57cec5SDimitry Andric   for (; ParamIdx != NumParams; ++ParamIdx) {
10300b57cec5SDimitry Andric     // Check argument types.
10310b57cec5SDimitry Andric     const PackExpansionType *Expansion
10320b57cec5SDimitry Andric                                 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
10330b57cec5SDimitry Andric     if (!Expansion) {
10340b57cec5SDimitry Andric       // Simple case: compare the parameter and argument types at this point.
10350b57cec5SDimitry Andric 
10360b57cec5SDimitry Andric       // Make sure we have an argument.
10370b57cec5SDimitry Andric       if (ArgIdx >= NumArgs)
10380b57cec5SDimitry Andric         return Sema::TDK_MiscellaneousDeductionFailure;
10390b57cec5SDimitry Andric 
10400b57cec5SDimitry Andric       if (isa<PackExpansionType>(Args[ArgIdx])) {
10410b57cec5SDimitry Andric         // C++0x [temp.deduct.type]p22:
10420b57cec5SDimitry Andric         //   If the original function parameter associated with A is a function
10430b57cec5SDimitry Andric         //   parameter pack and the function parameter associated with P is not
10440b57cec5SDimitry Andric         //   a function parameter pack, then template argument deduction fails.
10450b57cec5SDimitry Andric         return Sema::TDK_MiscellaneousDeductionFailure;
10460b57cec5SDimitry Andric       }
10470b57cec5SDimitry Andric 
10480b57cec5SDimitry Andric       if (Sema::TemplateDeductionResult Result
10490b57cec5SDimitry Andric             = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
10500b57cec5SDimitry Andric                                                  Params[ParamIdx], Args[ArgIdx],
10510b57cec5SDimitry Andric                                                  Info, Deduced, TDF,
10520b57cec5SDimitry Andric                                                  PartialOrdering))
10530b57cec5SDimitry Andric         return Result;
10540b57cec5SDimitry Andric 
10550b57cec5SDimitry Andric       ++ArgIdx;
10560b57cec5SDimitry Andric       continue;
10570b57cec5SDimitry Andric     }
10580b57cec5SDimitry Andric 
10590b57cec5SDimitry Andric     // C++0x [temp.deduct.type]p10:
10600b57cec5SDimitry Andric     //   If the parameter-declaration corresponding to Pi is a function
10610b57cec5SDimitry Andric     //   parameter pack, then the type of its declarator- id is compared with
10620b57cec5SDimitry Andric     //   each remaining parameter type in the parameter-type-list of A. Each
10630b57cec5SDimitry Andric     //   comparison deduces template arguments for subsequent positions in the
10640b57cec5SDimitry Andric     //   template parameter packs expanded by the function parameter pack.
10650b57cec5SDimitry Andric 
10660b57cec5SDimitry Andric     QualType Pattern = Expansion->getPattern();
10670b57cec5SDimitry Andric     PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
10680b57cec5SDimitry Andric 
10690b57cec5SDimitry Andric     // A pack scope with fixed arity is not really a pack any more, so is not
10700b57cec5SDimitry Andric     // a non-deduced context.
10710b57cec5SDimitry Andric     if (ParamIdx + 1 == NumParams || PackScope.hasFixedArity()) {
10720b57cec5SDimitry Andric       for (; ArgIdx < NumArgs && PackScope.hasNextElement(); ++ArgIdx) {
10730b57cec5SDimitry Andric         // Deduce template arguments from the pattern.
10740b57cec5SDimitry Andric         if (Sema::TemplateDeductionResult Result
10750b57cec5SDimitry Andric               = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
10760b57cec5SDimitry Andric                                                    Args[ArgIdx], Info, Deduced,
10770b57cec5SDimitry Andric                                                    TDF, PartialOrdering))
10780b57cec5SDimitry Andric           return Result;
10790b57cec5SDimitry Andric 
10800b57cec5SDimitry Andric         PackScope.nextPackElement();
10810b57cec5SDimitry Andric       }
10820b57cec5SDimitry Andric     } else {
10830b57cec5SDimitry Andric       // C++0x [temp.deduct.type]p5:
10840b57cec5SDimitry Andric       //   The non-deduced contexts are:
10850b57cec5SDimitry Andric       //     - A function parameter pack that does not occur at the end of the
10860b57cec5SDimitry Andric       //       parameter-declaration-clause.
10870b57cec5SDimitry Andric       //
10880b57cec5SDimitry Andric       // FIXME: There is no wording to say what we should do in this case. We
10890b57cec5SDimitry Andric       // choose to resolve this by applying the same rule that is applied for a
10900b57cec5SDimitry Andric       // function call: that is, deduce all contained packs to their
10910b57cec5SDimitry Andric       // explicitly-specified values (or to <> if there is no such value).
10920b57cec5SDimitry Andric       //
10930b57cec5SDimitry Andric       // This is seemingly-arbitrarily different from the case of a template-id
10940b57cec5SDimitry Andric       // with a non-trailing pack-expansion in its arguments, which renders the
10950b57cec5SDimitry Andric       // entire template-argument-list a non-deduced context.
10960b57cec5SDimitry Andric 
10970b57cec5SDimitry Andric       // If the parameter type contains an explicitly-specified pack that we
10980b57cec5SDimitry Andric       // could not expand, skip the number of parameters notionally created
10990b57cec5SDimitry Andric       // by the expansion.
11000b57cec5SDimitry Andric       Optional<unsigned> NumExpansions = Expansion->getNumExpansions();
11010b57cec5SDimitry Andric       if (NumExpansions && !PackScope.isPartiallyExpanded()) {
11020b57cec5SDimitry Andric         for (unsigned I = 0; I != *NumExpansions && ArgIdx < NumArgs;
11030b57cec5SDimitry Andric              ++I, ++ArgIdx)
11040b57cec5SDimitry Andric           PackScope.nextPackElement();
11050b57cec5SDimitry Andric       }
11060b57cec5SDimitry Andric     }
11070b57cec5SDimitry Andric 
11080b57cec5SDimitry Andric     // Build argument packs for each of the parameter packs expanded by this
11090b57cec5SDimitry Andric     // pack expansion.
11100b57cec5SDimitry Andric     if (auto Result = PackScope.finish())
11110b57cec5SDimitry Andric       return Result;
11120b57cec5SDimitry Andric   }
11130b57cec5SDimitry Andric 
11140b57cec5SDimitry Andric   // Make sure we don't have any extra arguments.
11150b57cec5SDimitry Andric   if (ArgIdx < NumArgs)
11160b57cec5SDimitry Andric     return Sema::TDK_MiscellaneousDeductionFailure;
11170b57cec5SDimitry Andric 
11180b57cec5SDimitry Andric   return Sema::TDK_Success;
11190b57cec5SDimitry Andric }
11200b57cec5SDimitry Andric 
11210b57cec5SDimitry Andric /// Determine whether the parameter has qualifiers that the argument
11220b57cec5SDimitry Andric /// lacks. Put another way, determine whether there is no way to add
11230b57cec5SDimitry Andric /// a deduced set of qualifiers to the ParamType that would result in
11240b57cec5SDimitry Andric /// its qualifiers matching those of the ArgType.
11250b57cec5SDimitry Andric static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
11260b57cec5SDimitry Andric                                                   QualType ArgType) {
11270b57cec5SDimitry Andric   Qualifiers ParamQs = ParamType.getQualifiers();
11280b57cec5SDimitry Andric   Qualifiers ArgQs = ArgType.getQualifiers();
11290b57cec5SDimitry Andric 
11300b57cec5SDimitry Andric   if (ParamQs == ArgQs)
11310b57cec5SDimitry Andric     return false;
11320b57cec5SDimitry Andric 
11330b57cec5SDimitry Andric   // Mismatched (but not missing) Objective-C GC attributes.
11340b57cec5SDimitry Andric   if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
11350b57cec5SDimitry Andric       ParamQs.hasObjCGCAttr())
11360b57cec5SDimitry Andric     return true;
11370b57cec5SDimitry Andric 
11380b57cec5SDimitry Andric   // Mismatched (but not missing) address spaces.
11390b57cec5SDimitry Andric   if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
11400b57cec5SDimitry Andric       ParamQs.hasAddressSpace())
11410b57cec5SDimitry Andric     return true;
11420b57cec5SDimitry Andric 
11430b57cec5SDimitry Andric   // Mismatched (but not missing) Objective-C lifetime qualifiers.
11440b57cec5SDimitry Andric   if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
11450b57cec5SDimitry Andric       ParamQs.hasObjCLifetime())
11460b57cec5SDimitry Andric     return true;
11470b57cec5SDimitry Andric 
11480b57cec5SDimitry Andric   // CVR qualifiers inconsistent or a superset.
11490b57cec5SDimitry Andric   return (ParamQs.getCVRQualifiers() & ~ArgQs.getCVRQualifiers()) != 0;
11500b57cec5SDimitry Andric }
11510b57cec5SDimitry Andric 
11520b57cec5SDimitry Andric /// Compare types for equality with respect to possibly compatible
11530b57cec5SDimitry Andric /// function types (noreturn adjustment, implicit calling conventions). If any
11540b57cec5SDimitry Andric /// of parameter and argument is not a function, just perform type comparison.
11550b57cec5SDimitry Andric ///
11560b57cec5SDimitry Andric /// \param Param the template parameter type.
11570b57cec5SDimitry Andric ///
11580b57cec5SDimitry Andric /// \param Arg the argument type.
11590b57cec5SDimitry Andric bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
11600b57cec5SDimitry Andric                                           CanQualType Arg) {
11610b57cec5SDimitry Andric   const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
11620b57cec5SDimitry Andric                      *ArgFunction   = Arg->getAs<FunctionType>();
11630b57cec5SDimitry Andric 
11640b57cec5SDimitry Andric   // Just compare if not functions.
11650b57cec5SDimitry Andric   if (!ParamFunction || !ArgFunction)
11660b57cec5SDimitry Andric     return Param == Arg;
11670b57cec5SDimitry Andric 
11680b57cec5SDimitry Andric   // Noreturn and noexcept adjustment.
11690b57cec5SDimitry Andric   QualType AdjustedParam;
11700b57cec5SDimitry Andric   if (IsFunctionConversion(Param, Arg, AdjustedParam))
11710b57cec5SDimitry Andric     return Arg == Context.getCanonicalType(AdjustedParam);
11720b57cec5SDimitry Andric 
11730b57cec5SDimitry Andric   // FIXME: Compatible calling conventions.
11740b57cec5SDimitry Andric 
11750b57cec5SDimitry Andric   return Param == Arg;
11760b57cec5SDimitry Andric }
11770b57cec5SDimitry Andric 
11780b57cec5SDimitry Andric /// Get the index of the first template parameter that was originally from the
11790b57cec5SDimitry Andric /// innermost template-parameter-list. This is 0 except when we concatenate
11800b57cec5SDimitry Andric /// the template parameter lists of a class template and a constructor template
11810b57cec5SDimitry Andric /// when forming an implicit deduction guide.
11820b57cec5SDimitry Andric static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD) {
11830b57cec5SDimitry Andric   auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
11840b57cec5SDimitry Andric   if (!Guide || !Guide->isImplicit())
11850b57cec5SDimitry Andric     return 0;
11860b57cec5SDimitry Andric   return Guide->getDeducedTemplate()->getTemplateParameters()->size();
11870b57cec5SDimitry Andric }
11880b57cec5SDimitry Andric 
11890b57cec5SDimitry Andric /// Determine whether a type denotes a forwarding reference.
11900b57cec5SDimitry Andric static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
11910b57cec5SDimitry Andric   // C++1z [temp.deduct.call]p3:
11920b57cec5SDimitry Andric   //   A forwarding reference is an rvalue reference to a cv-unqualified
11930b57cec5SDimitry Andric   //   template parameter that does not represent a template parameter of a
11940b57cec5SDimitry Andric   //   class template.
11950b57cec5SDimitry Andric   if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
11960b57cec5SDimitry Andric     if (ParamRef->getPointeeType().getQualifiers())
11970b57cec5SDimitry Andric       return false;
11980b57cec5SDimitry Andric     auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
11990b57cec5SDimitry Andric     return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
12000b57cec5SDimitry Andric   }
12010b57cec5SDimitry Andric   return false;
12020b57cec5SDimitry Andric }
12030b57cec5SDimitry Andric 
12040b57cec5SDimitry Andric /// Deduce the template arguments by comparing the parameter type and
12050b57cec5SDimitry Andric /// the argument type (C++ [temp.deduct.type]).
12060b57cec5SDimitry Andric ///
12070b57cec5SDimitry Andric /// \param S the semantic analysis object within which we are deducing
12080b57cec5SDimitry Andric ///
12090b57cec5SDimitry Andric /// \param TemplateParams the template parameters that we are deducing
12100b57cec5SDimitry Andric ///
12110b57cec5SDimitry Andric /// \param ParamIn the parameter type
12120b57cec5SDimitry Andric ///
12130b57cec5SDimitry Andric /// \param ArgIn the argument type
12140b57cec5SDimitry Andric ///
12150b57cec5SDimitry Andric /// \param Info information about the template argument deduction itself
12160b57cec5SDimitry Andric ///
12170b57cec5SDimitry Andric /// \param Deduced the deduced template arguments
12180b57cec5SDimitry Andric ///
12190b57cec5SDimitry Andric /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
12200b57cec5SDimitry Andric /// how template argument deduction is performed.
12210b57cec5SDimitry Andric ///
12220b57cec5SDimitry Andric /// \param PartialOrdering Whether we're performing template argument deduction
12230b57cec5SDimitry Andric /// in the context of partial ordering (C++0x [temp.deduct.partial]).
12240b57cec5SDimitry Andric ///
12250b57cec5SDimitry Andric /// \returns the result of template argument deduction so far. Note that a
12260b57cec5SDimitry Andric /// "success" result means that template argument deduction has not yet failed,
12270b57cec5SDimitry Andric /// but it may still fail, later, for other reasons.
12280b57cec5SDimitry Andric static Sema::TemplateDeductionResult
12290b57cec5SDimitry Andric DeduceTemplateArgumentsByTypeMatch(Sema &S,
12300b57cec5SDimitry Andric                                    TemplateParameterList *TemplateParams,
12310b57cec5SDimitry Andric                                    QualType ParamIn, QualType ArgIn,
12320b57cec5SDimitry Andric                                    TemplateDeductionInfo &Info,
12330b57cec5SDimitry Andric                             SmallVectorImpl<DeducedTemplateArgument> &Deduced,
12340b57cec5SDimitry Andric                                    unsigned TDF,
12350b57cec5SDimitry Andric                                    bool PartialOrdering,
12360b57cec5SDimitry Andric                                    bool DeducedFromArrayBound) {
12370b57cec5SDimitry Andric   // We only want to look at the canonical types, since typedefs and
12380b57cec5SDimitry Andric   // sugar are not part of template argument deduction.
12390b57cec5SDimitry Andric   QualType Param = S.Context.getCanonicalType(ParamIn);
12400b57cec5SDimitry Andric   QualType Arg = S.Context.getCanonicalType(ArgIn);
12410b57cec5SDimitry Andric 
12420b57cec5SDimitry Andric   // If the argument type is a pack expansion, look at its pattern.
12430b57cec5SDimitry Andric   // This isn't explicitly called out
12440b57cec5SDimitry Andric   if (const PackExpansionType *ArgExpansion
12450b57cec5SDimitry Andric                                             = dyn_cast<PackExpansionType>(Arg))
12460b57cec5SDimitry Andric     Arg = ArgExpansion->getPattern();
12470b57cec5SDimitry Andric 
12480b57cec5SDimitry Andric   if (PartialOrdering) {
12490b57cec5SDimitry Andric     // C++11 [temp.deduct.partial]p5:
12500b57cec5SDimitry Andric     //   Before the partial ordering is done, certain transformations are
12510b57cec5SDimitry Andric     //   performed on the types used for partial ordering:
12520b57cec5SDimitry Andric     //     - If P is a reference type, P is replaced by the type referred to.
12530b57cec5SDimitry Andric     const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
12540b57cec5SDimitry Andric     if (ParamRef)
12550b57cec5SDimitry Andric       Param = ParamRef->getPointeeType();
12560b57cec5SDimitry Andric 
12570b57cec5SDimitry Andric     //     - If A is a reference type, A is replaced by the type referred to.
12580b57cec5SDimitry Andric     const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
12590b57cec5SDimitry Andric     if (ArgRef)
12600b57cec5SDimitry Andric       Arg = ArgRef->getPointeeType();
12610b57cec5SDimitry Andric 
12620b57cec5SDimitry Andric     if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
12630b57cec5SDimitry Andric       // C++11 [temp.deduct.partial]p9:
12640b57cec5SDimitry Andric       //   If, for a given type, deduction succeeds in both directions (i.e.,
12650b57cec5SDimitry Andric       //   the types are identical after the transformations above) and both
12660b57cec5SDimitry Andric       //   P and A were reference types [...]:
12670b57cec5SDimitry Andric       //     - if [one type] was an lvalue reference and [the other type] was
12680b57cec5SDimitry Andric       //       not, [the other type] is not considered to be at least as
12690b57cec5SDimitry Andric       //       specialized as [the first type]
12700b57cec5SDimitry Andric       //     - if [one type] is more cv-qualified than [the other type],
12710b57cec5SDimitry Andric       //       [the other type] is not considered to be at least as specialized
12720b57cec5SDimitry Andric       //       as [the first type]
12730b57cec5SDimitry Andric       // Objective-C ARC adds:
12740b57cec5SDimitry Andric       //     - [one type] has non-trivial lifetime, [the other type] has
12750b57cec5SDimitry Andric       //       __unsafe_unretained lifetime, and the types are otherwise
12760b57cec5SDimitry Andric       //       identical
12770b57cec5SDimitry Andric       //
12780b57cec5SDimitry Andric       // A is "considered to be at least as specialized" as P iff deduction
12790b57cec5SDimitry Andric       // succeeds, so we model this as a deduction failure. Note that
12800b57cec5SDimitry Andric       // [the first type] is P and [the other type] is A here; the standard
12810b57cec5SDimitry Andric       // gets this backwards.
12820b57cec5SDimitry Andric       Qualifiers ParamQuals = Param.getQualifiers();
12830b57cec5SDimitry Andric       Qualifiers ArgQuals = Arg.getQualifiers();
12840b57cec5SDimitry Andric       if ((ParamRef->isLValueReferenceType() &&
12850b57cec5SDimitry Andric            !ArgRef->isLValueReferenceType()) ||
12860b57cec5SDimitry Andric           ParamQuals.isStrictSupersetOf(ArgQuals) ||
12870b57cec5SDimitry Andric           (ParamQuals.hasNonTrivialObjCLifetime() &&
12880b57cec5SDimitry Andric            ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
12890b57cec5SDimitry Andric            ParamQuals.withoutObjCLifetime() ==
12900b57cec5SDimitry Andric                ArgQuals.withoutObjCLifetime())) {
12910b57cec5SDimitry Andric         Info.FirstArg = TemplateArgument(ParamIn);
12920b57cec5SDimitry Andric         Info.SecondArg = TemplateArgument(ArgIn);
12930b57cec5SDimitry Andric         return Sema::TDK_NonDeducedMismatch;
12940b57cec5SDimitry Andric       }
12950b57cec5SDimitry Andric     }
12960b57cec5SDimitry Andric 
12970b57cec5SDimitry Andric     // C++11 [temp.deduct.partial]p7:
12980b57cec5SDimitry Andric     //   Remove any top-level cv-qualifiers:
12990b57cec5SDimitry Andric     //     - If P is a cv-qualified type, P is replaced by the cv-unqualified
13000b57cec5SDimitry Andric     //       version of P.
13010b57cec5SDimitry Andric     Param = Param.getUnqualifiedType();
13020b57cec5SDimitry Andric     //     - If A is a cv-qualified type, A is replaced by the cv-unqualified
13030b57cec5SDimitry Andric     //       version of A.
13040b57cec5SDimitry Andric     Arg = Arg.getUnqualifiedType();
13050b57cec5SDimitry Andric   } else {
13060b57cec5SDimitry Andric     // C++0x [temp.deduct.call]p4 bullet 1:
13070b57cec5SDimitry Andric     //   - If the original P is a reference type, the deduced A (i.e., the type
13080b57cec5SDimitry Andric     //     referred to by the reference) can be more cv-qualified than the
13090b57cec5SDimitry Andric     //     transformed A.
13100b57cec5SDimitry Andric     if (TDF & TDF_ParamWithReferenceType) {
13110b57cec5SDimitry Andric       Qualifiers Quals;
13120b57cec5SDimitry Andric       QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
13130b57cec5SDimitry Andric       Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
13140b57cec5SDimitry Andric                              Arg.getCVRQualifiers());
13150b57cec5SDimitry Andric       Param = S.Context.getQualifiedType(UnqualParam, Quals);
13160b57cec5SDimitry Andric     }
13170b57cec5SDimitry Andric 
13180b57cec5SDimitry Andric     if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
13190b57cec5SDimitry Andric       // C++0x [temp.deduct.type]p10:
13200b57cec5SDimitry Andric       //   If P and A are function types that originated from deduction when
13210b57cec5SDimitry Andric       //   taking the address of a function template (14.8.2.2) or when deducing
13220b57cec5SDimitry Andric       //   template arguments from a function declaration (14.8.2.6) and Pi and
13230b57cec5SDimitry Andric       //   Ai are parameters of the top-level parameter-type-list of P and A,
13240b57cec5SDimitry Andric       //   respectively, Pi is adjusted if it is a forwarding reference and Ai
13250b57cec5SDimitry Andric       //   is an lvalue reference, in
13260b57cec5SDimitry Andric       //   which case the type of Pi is changed to be the template parameter
13270b57cec5SDimitry Andric       //   type (i.e., T&& is changed to simply T). [ Note: As a result, when
13280b57cec5SDimitry Andric       //   Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
13290b57cec5SDimitry Andric       //   deduced as X&. - end note ]
13300b57cec5SDimitry Andric       TDF &= ~TDF_TopLevelParameterTypeList;
13310b57cec5SDimitry Andric       if (isForwardingReference(Param, 0) && Arg->isLValueReferenceType())
13320b57cec5SDimitry Andric         Param = Param->getPointeeType();
13330b57cec5SDimitry Andric     }
13340b57cec5SDimitry Andric   }
13350b57cec5SDimitry Andric 
13360b57cec5SDimitry Andric   // C++ [temp.deduct.type]p9:
13370b57cec5SDimitry Andric   //   A template type argument T, a template template argument TT or a
13380b57cec5SDimitry Andric   //   template non-type argument i can be deduced if P and A have one of
13390b57cec5SDimitry Andric   //   the following forms:
13400b57cec5SDimitry Andric   //
13410b57cec5SDimitry Andric   //     T
13420b57cec5SDimitry Andric   //     cv-list T
13430b57cec5SDimitry Andric   if (const TemplateTypeParmType *TemplateTypeParm
13440b57cec5SDimitry Andric         = Param->getAs<TemplateTypeParmType>()) {
13450b57cec5SDimitry Andric     // Just skip any attempts to deduce from a placeholder type or a parameter
13460b57cec5SDimitry Andric     // at a different depth.
13470b57cec5SDimitry Andric     if (Arg->isPlaceholderType() ||
13480b57cec5SDimitry Andric         Info.getDeducedDepth() != TemplateTypeParm->getDepth())
13490b57cec5SDimitry Andric       return Sema::TDK_Success;
13500b57cec5SDimitry Andric 
13510b57cec5SDimitry Andric     unsigned Index = TemplateTypeParm->getIndex();
13520b57cec5SDimitry Andric     bool RecanonicalizeArg = false;
13530b57cec5SDimitry Andric 
13540b57cec5SDimitry Andric     // If the argument type is an array type, move the qualifiers up to the
13550b57cec5SDimitry Andric     // top level, so they can be matched with the qualifiers on the parameter.
13560b57cec5SDimitry Andric     if (isa<ArrayType>(Arg)) {
13570b57cec5SDimitry Andric       Qualifiers Quals;
13580b57cec5SDimitry Andric       Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
13590b57cec5SDimitry Andric       if (Quals) {
13600b57cec5SDimitry Andric         Arg = S.Context.getQualifiedType(Arg, Quals);
13610b57cec5SDimitry Andric         RecanonicalizeArg = true;
13620b57cec5SDimitry Andric       }
13630b57cec5SDimitry Andric     }
13640b57cec5SDimitry Andric 
13650b57cec5SDimitry Andric     // The argument type can not be less qualified than the parameter
13660b57cec5SDimitry Andric     // type.
13670b57cec5SDimitry Andric     if (!(TDF & TDF_IgnoreQualifiers) &&
13680b57cec5SDimitry Andric         hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
13690b57cec5SDimitry Andric       Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
13700b57cec5SDimitry Andric       Info.FirstArg = TemplateArgument(Param);
13710b57cec5SDimitry Andric       Info.SecondArg = TemplateArgument(Arg);
13720b57cec5SDimitry Andric       return Sema::TDK_Underqualified;
13730b57cec5SDimitry Andric     }
13740b57cec5SDimitry Andric 
13750b57cec5SDimitry Andric     // Do not match a function type with a cv-qualified type.
13760b57cec5SDimitry Andric     // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1584
13770b57cec5SDimitry Andric     if (Arg->isFunctionType() && Param.hasQualifiers()) {
13780b57cec5SDimitry Andric       return Sema::TDK_NonDeducedMismatch;
13790b57cec5SDimitry Andric     }
13800b57cec5SDimitry Andric 
13810b57cec5SDimitry Andric     assert(TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&
13820b57cec5SDimitry Andric            "saw template type parameter with wrong depth");
13830b57cec5SDimitry Andric     assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
13840b57cec5SDimitry Andric     QualType DeducedType = Arg;
13850b57cec5SDimitry Andric 
13860b57cec5SDimitry Andric     // Remove any qualifiers on the parameter from the deduced type.
13870b57cec5SDimitry Andric     // We checked the qualifiers for consistency above.
13880b57cec5SDimitry Andric     Qualifiers DeducedQs = DeducedType.getQualifiers();
13890b57cec5SDimitry Andric     Qualifiers ParamQs = Param.getQualifiers();
13900b57cec5SDimitry Andric     DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
13910b57cec5SDimitry Andric     if (ParamQs.hasObjCGCAttr())
13920b57cec5SDimitry Andric       DeducedQs.removeObjCGCAttr();
13930b57cec5SDimitry Andric     if (ParamQs.hasAddressSpace())
13940b57cec5SDimitry Andric       DeducedQs.removeAddressSpace();
13950b57cec5SDimitry Andric     if (ParamQs.hasObjCLifetime())
13960b57cec5SDimitry Andric       DeducedQs.removeObjCLifetime();
13970b57cec5SDimitry Andric 
13980b57cec5SDimitry Andric     // Objective-C ARC:
13990b57cec5SDimitry Andric     //   If template deduction would produce a lifetime qualifier on a type
14000b57cec5SDimitry Andric     //   that is not a lifetime type, template argument deduction fails.
14010b57cec5SDimitry Andric     if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
14020b57cec5SDimitry Andric         !DeducedType->isDependentType()) {
14030b57cec5SDimitry Andric       Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
14040b57cec5SDimitry Andric       Info.FirstArg = TemplateArgument(Param);
14050b57cec5SDimitry Andric       Info.SecondArg = TemplateArgument(Arg);
14060b57cec5SDimitry Andric       return Sema::TDK_Underqualified;
14070b57cec5SDimitry Andric     }
14080b57cec5SDimitry Andric 
14090b57cec5SDimitry Andric     // Objective-C ARC:
14100b57cec5SDimitry Andric     //   If template deduction would produce an argument type with lifetime type
14110b57cec5SDimitry Andric     //   but no lifetime qualifier, the __strong lifetime qualifier is inferred.
14120b57cec5SDimitry Andric     if (S.getLangOpts().ObjCAutoRefCount &&
14130b57cec5SDimitry Andric         DeducedType->isObjCLifetimeType() &&
14140b57cec5SDimitry Andric         !DeducedQs.hasObjCLifetime())
14150b57cec5SDimitry Andric       DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
14160b57cec5SDimitry Andric 
14170b57cec5SDimitry Andric     DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
14180b57cec5SDimitry Andric                                              DeducedQs);
14190b57cec5SDimitry Andric 
14200b57cec5SDimitry Andric     if (RecanonicalizeArg)
14210b57cec5SDimitry Andric       DeducedType = S.Context.getCanonicalType(DeducedType);
14220b57cec5SDimitry Andric 
14230b57cec5SDimitry Andric     DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
14240b57cec5SDimitry Andric     DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
14250b57cec5SDimitry Andric                                                                  Deduced[Index],
14260b57cec5SDimitry Andric                                                                    NewDeduced);
14270b57cec5SDimitry Andric     if (Result.isNull()) {
14280b57cec5SDimitry Andric       Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
14290b57cec5SDimitry Andric       Info.FirstArg = Deduced[Index];
14300b57cec5SDimitry Andric       Info.SecondArg = NewDeduced;
14310b57cec5SDimitry Andric       return Sema::TDK_Inconsistent;
14320b57cec5SDimitry Andric     }
14330b57cec5SDimitry Andric 
14340b57cec5SDimitry Andric     Deduced[Index] = Result;
14350b57cec5SDimitry Andric     return Sema::TDK_Success;
14360b57cec5SDimitry Andric   }
14370b57cec5SDimitry Andric 
14380b57cec5SDimitry Andric   // Set up the template argument deduction information for a failure.
14390b57cec5SDimitry Andric   Info.FirstArg = TemplateArgument(ParamIn);
14400b57cec5SDimitry Andric   Info.SecondArg = TemplateArgument(ArgIn);
14410b57cec5SDimitry Andric 
14420b57cec5SDimitry Andric   // If the parameter is an already-substituted template parameter
14430b57cec5SDimitry Andric   // pack, do nothing: we don't know which of its arguments to look
14440b57cec5SDimitry Andric   // at, so we have to wait until all of the parameter packs in this
14450b57cec5SDimitry Andric   // expansion have arguments.
14460b57cec5SDimitry Andric   if (isa<SubstTemplateTypeParmPackType>(Param))
14470b57cec5SDimitry Andric     return Sema::TDK_Success;
14480b57cec5SDimitry Andric 
14490b57cec5SDimitry Andric   // Check the cv-qualifiers on the parameter and argument types.
14500b57cec5SDimitry Andric   CanQualType CanParam = S.Context.getCanonicalType(Param);
14510b57cec5SDimitry Andric   CanQualType CanArg = S.Context.getCanonicalType(Arg);
14520b57cec5SDimitry Andric   if (!(TDF & TDF_IgnoreQualifiers)) {
14530b57cec5SDimitry Andric     if (TDF & TDF_ParamWithReferenceType) {
14540b57cec5SDimitry Andric       if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
14550b57cec5SDimitry Andric         return Sema::TDK_NonDeducedMismatch;
14560b57cec5SDimitry Andric     } else if (TDF & TDF_ArgWithReferenceType) {
14570b57cec5SDimitry Andric       // C++ [temp.deduct.conv]p4:
14580b57cec5SDimitry Andric       //   If the original A is a reference type, A can be more cv-qualified
14590b57cec5SDimitry Andric       //   than the deduced A
14600b57cec5SDimitry Andric       if (!Arg.getQualifiers().compatiblyIncludes(Param.getQualifiers()))
14610b57cec5SDimitry Andric         return Sema::TDK_NonDeducedMismatch;
14620b57cec5SDimitry Andric 
14630b57cec5SDimitry Andric       // Strip out all extra qualifiers from the argument to figure out the
14640b57cec5SDimitry Andric       // type we're converting to, prior to the qualification conversion.
14650b57cec5SDimitry Andric       Qualifiers Quals;
14660b57cec5SDimitry Andric       Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
14670b57cec5SDimitry Andric       Arg = S.Context.getQualifiedType(Arg, Param.getQualifiers());
14680b57cec5SDimitry Andric     } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
14690b57cec5SDimitry Andric       if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
14700b57cec5SDimitry Andric         return Sema::TDK_NonDeducedMismatch;
14710b57cec5SDimitry Andric     }
14720b57cec5SDimitry Andric 
14730b57cec5SDimitry Andric     // If the parameter type is not dependent, there is nothing to deduce.
14740b57cec5SDimitry Andric     if (!Param->isDependentType()) {
14750b57cec5SDimitry Andric       if (!(TDF & TDF_SkipNonDependent)) {
14760b57cec5SDimitry Andric         bool NonDeduced =
14770b57cec5SDimitry Andric             (TDF & TDF_AllowCompatibleFunctionType)
14780b57cec5SDimitry Andric                 ? !S.isSameOrCompatibleFunctionType(CanParam, CanArg)
14790b57cec5SDimitry Andric                 : Param != Arg;
14800b57cec5SDimitry Andric         if (NonDeduced) {
14810b57cec5SDimitry Andric           return Sema::TDK_NonDeducedMismatch;
14820b57cec5SDimitry Andric         }
14830b57cec5SDimitry Andric       }
14840b57cec5SDimitry Andric       return Sema::TDK_Success;
14850b57cec5SDimitry Andric     }
14860b57cec5SDimitry Andric   } else if (!Param->isDependentType()) {
14870b57cec5SDimitry Andric     CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
14880b57cec5SDimitry Andric                 ArgUnqualType = CanArg.getUnqualifiedType();
14890b57cec5SDimitry Andric     bool Success =
14900b57cec5SDimitry Andric         (TDF & TDF_AllowCompatibleFunctionType)
14910b57cec5SDimitry Andric             ? S.isSameOrCompatibleFunctionType(ParamUnqualType, ArgUnqualType)
14920b57cec5SDimitry Andric             : ParamUnqualType == ArgUnqualType;
14930b57cec5SDimitry Andric     if (Success)
14940b57cec5SDimitry Andric       return Sema::TDK_Success;
14950b57cec5SDimitry Andric   }
14960b57cec5SDimitry Andric 
14970b57cec5SDimitry Andric   switch (Param->getTypeClass()) {
14980b57cec5SDimitry Andric     // Non-canonical types cannot appear here.
14990b57cec5SDimitry Andric #define NON_CANONICAL_TYPE(Class, Base) \
15000b57cec5SDimitry Andric   case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
15010b57cec5SDimitry Andric #define TYPE(Class, Base)
1502a7dea167SDimitry Andric #include "clang/AST/TypeNodes.inc"
15030b57cec5SDimitry Andric 
15040b57cec5SDimitry Andric     case Type::TemplateTypeParm:
15050b57cec5SDimitry Andric     case Type::SubstTemplateTypeParmPack:
15060b57cec5SDimitry Andric       llvm_unreachable("Type nodes handled above");
15070b57cec5SDimitry Andric 
15080b57cec5SDimitry Andric     // These types cannot be dependent, so simply check whether the types are
15090b57cec5SDimitry Andric     // the same.
15100b57cec5SDimitry Andric     case Type::Builtin:
15110b57cec5SDimitry Andric     case Type::VariableArray:
15120b57cec5SDimitry Andric     case Type::Vector:
15130b57cec5SDimitry Andric     case Type::FunctionNoProto:
15140b57cec5SDimitry Andric     case Type::Record:
15150b57cec5SDimitry Andric     case Type::Enum:
15160b57cec5SDimitry Andric     case Type::ObjCObject:
15170b57cec5SDimitry Andric     case Type::ObjCInterface:
15180b57cec5SDimitry Andric     case Type::ObjCObjectPointer:
15195ffd83dbSDimitry Andric     case Type::ExtInt:
15200b57cec5SDimitry Andric       if (TDF & TDF_SkipNonDependent)
15210b57cec5SDimitry Andric         return Sema::TDK_Success;
15220b57cec5SDimitry Andric 
15230b57cec5SDimitry Andric       if (TDF & TDF_IgnoreQualifiers) {
15240b57cec5SDimitry Andric         Param = Param.getUnqualifiedType();
15250b57cec5SDimitry Andric         Arg = Arg.getUnqualifiedType();
15260b57cec5SDimitry Andric       }
15270b57cec5SDimitry Andric 
15280b57cec5SDimitry Andric       return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
15290b57cec5SDimitry Andric 
15300b57cec5SDimitry Andric     //     _Complex T   [placeholder extension]
15310b57cec5SDimitry Andric     case Type::Complex:
15320b57cec5SDimitry Andric       if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
15330b57cec5SDimitry Andric         return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
15340b57cec5SDimitry Andric                                     cast<ComplexType>(Param)->getElementType(),
15350b57cec5SDimitry Andric                                     ComplexArg->getElementType(),
15360b57cec5SDimitry Andric                                     Info, Deduced, TDF);
15370b57cec5SDimitry Andric 
15380b57cec5SDimitry Andric       return Sema::TDK_NonDeducedMismatch;
15390b57cec5SDimitry Andric 
15400b57cec5SDimitry Andric     //     _Atomic T   [extension]
15410b57cec5SDimitry Andric     case Type::Atomic:
15420b57cec5SDimitry Andric       if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
15430b57cec5SDimitry Andric         return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
15440b57cec5SDimitry Andric                                        cast<AtomicType>(Param)->getValueType(),
15450b57cec5SDimitry Andric                                        AtomicArg->getValueType(),
15460b57cec5SDimitry Andric                                        Info, Deduced, TDF);
15470b57cec5SDimitry Andric 
15480b57cec5SDimitry Andric       return Sema::TDK_NonDeducedMismatch;
15490b57cec5SDimitry Andric 
15500b57cec5SDimitry Andric     //     T *
15510b57cec5SDimitry Andric     case Type::Pointer: {
15520b57cec5SDimitry Andric       QualType PointeeType;
15530b57cec5SDimitry Andric       if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
15540b57cec5SDimitry Andric         PointeeType = PointerArg->getPointeeType();
15550b57cec5SDimitry Andric       } else if (const ObjCObjectPointerType *PointerArg
15560b57cec5SDimitry Andric                    = Arg->getAs<ObjCObjectPointerType>()) {
15570b57cec5SDimitry Andric         PointeeType = PointerArg->getPointeeType();
15580b57cec5SDimitry Andric       } else {
15590b57cec5SDimitry Andric         return Sema::TDK_NonDeducedMismatch;
15600b57cec5SDimitry Andric       }
15610b57cec5SDimitry Andric 
15620b57cec5SDimitry Andric       unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
15630b57cec5SDimitry Andric       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
15640b57cec5SDimitry Andric                                      cast<PointerType>(Param)->getPointeeType(),
15650b57cec5SDimitry Andric                                      PointeeType,
15660b57cec5SDimitry Andric                                      Info, Deduced, SubTDF);
15670b57cec5SDimitry Andric     }
15680b57cec5SDimitry Andric 
15690b57cec5SDimitry Andric     //     T &
15700b57cec5SDimitry Andric     case Type::LValueReference: {
15710b57cec5SDimitry Andric       const LValueReferenceType *ReferenceArg =
15720b57cec5SDimitry Andric           Arg->getAs<LValueReferenceType>();
15730b57cec5SDimitry Andric       if (!ReferenceArg)
15740b57cec5SDimitry Andric         return Sema::TDK_NonDeducedMismatch;
15750b57cec5SDimitry Andric 
15760b57cec5SDimitry Andric       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
15770b57cec5SDimitry Andric                            cast<LValueReferenceType>(Param)->getPointeeType(),
15780b57cec5SDimitry Andric                            ReferenceArg->getPointeeType(), Info, Deduced, 0);
15790b57cec5SDimitry Andric     }
15800b57cec5SDimitry Andric 
15810b57cec5SDimitry Andric     //     T && [C++0x]
15820b57cec5SDimitry Andric     case Type::RValueReference: {
15830b57cec5SDimitry Andric       const RValueReferenceType *ReferenceArg =
15840b57cec5SDimitry Andric           Arg->getAs<RValueReferenceType>();
15850b57cec5SDimitry Andric       if (!ReferenceArg)
15860b57cec5SDimitry Andric         return Sema::TDK_NonDeducedMismatch;
15870b57cec5SDimitry Andric 
15880b57cec5SDimitry Andric       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
15890b57cec5SDimitry Andric                              cast<RValueReferenceType>(Param)->getPointeeType(),
15900b57cec5SDimitry Andric                              ReferenceArg->getPointeeType(),
15910b57cec5SDimitry Andric                              Info, Deduced, 0);
15920b57cec5SDimitry Andric     }
15930b57cec5SDimitry Andric 
15940b57cec5SDimitry Andric     //     T [] (implied, but not stated explicitly)
15950b57cec5SDimitry Andric     case Type::IncompleteArray: {
15960b57cec5SDimitry Andric       const IncompleteArrayType *IncompleteArrayArg =
15970b57cec5SDimitry Andric         S.Context.getAsIncompleteArrayType(Arg);
15980b57cec5SDimitry Andric       if (!IncompleteArrayArg)
15990b57cec5SDimitry Andric         return Sema::TDK_NonDeducedMismatch;
16000b57cec5SDimitry Andric 
16010b57cec5SDimitry Andric       unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
16020b57cec5SDimitry Andric       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
16030b57cec5SDimitry Andric                     S.Context.getAsIncompleteArrayType(Param)->getElementType(),
16040b57cec5SDimitry Andric                     IncompleteArrayArg->getElementType(),
16050b57cec5SDimitry Andric                     Info, Deduced, SubTDF);
16060b57cec5SDimitry Andric     }
16070b57cec5SDimitry Andric 
16080b57cec5SDimitry Andric     //     T [integer-constant]
16090b57cec5SDimitry Andric     case Type::ConstantArray: {
16100b57cec5SDimitry Andric       const ConstantArrayType *ConstantArrayArg =
16110b57cec5SDimitry Andric         S.Context.getAsConstantArrayType(Arg);
16120b57cec5SDimitry Andric       if (!ConstantArrayArg)
16130b57cec5SDimitry Andric         return Sema::TDK_NonDeducedMismatch;
16140b57cec5SDimitry Andric 
16150b57cec5SDimitry Andric       const ConstantArrayType *ConstantArrayParm =
16160b57cec5SDimitry Andric         S.Context.getAsConstantArrayType(Param);
16170b57cec5SDimitry Andric       if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
16180b57cec5SDimitry Andric         return Sema::TDK_NonDeducedMismatch;
16190b57cec5SDimitry Andric 
16200b57cec5SDimitry Andric       unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
16210b57cec5SDimitry Andric       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
16220b57cec5SDimitry Andric                                            ConstantArrayParm->getElementType(),
16230b57cec5SDimitry Andric                                            ConstantArrayArg->getElementType(),
16240b57cec5SDimitry Andric                                            Info, Deduced, SubTDF);
16250b57cec5SDimitry Andric     }
16260b57cec5SDimitry Andric 
16270b57cec5SDimitry Andric     //     type [i]
16280b57cec5SDimitry Andric     case Type::DependentSizedArray: {
16290b57cec5SDimitry Andric       const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
16300b57cec5SDimitry Andric       if (!ArrayArg)
16310b57cec5SDimitry Andric         return Sema::TDK_NonDeducedMismatch;
16320b57cec5SDimitry Andric 
16330b57cec5SDimitry Andric       unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
16340b57cec5SDimitry Andric 
16350b57cec5SDimitry Andric       // Check the element type of the arrays
16360b57cec5SDimitry Andric       const DependentSizedArrayType *DependentArrayParm
16370b57cec5SDimitry Andric         = S.Context.getAsDependentSizedArrayType(Param);
16380b57cec5SDimitry Andric       if (Sema::TemplateDeductionResult Result
16390b57cec5SDimitry Andric             = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
16400b57cec5SDimitry Andric                                           DependentArrayParm->getElementType(),
16410b57cec5SDimitry Andric                                           ArrayArg->getElementType(),
16420b57cec5SDimitry Andric                                           Info, Deduced, SubTDF))
16430b57cec5SDimitry Andric         return Result;
16440b57cec5SDimitry Andric 
16450b57cec5SDimitry Andric       // Determine the array bound is something we can deduce.
16460b57cec5SDimitry Andric       NonTypeTemplateParmDecl *NTTP
16470b57cec5SDimitry Andric         = getDeducedParameterFromExpr(Info, DependentArrayParm->getSizeExpr());
16480b57cec5SDimitry Andric       if (!NTTP)
16490b57cec5SDimitry Andric         return Sema::TDK_Success;
16500b57cec5SDimitry Andric 
16510b57cec5SDimitry Andric       // We can perform template argument deduction for the given non-type
16520b57cec5SDimitry Andric       // template parameter.
16530b57cec5SDimitry Andric       assert(NTTP->getDepth() == Info.getDeducedDepth() &&
16540b57cec5SDimitry Andric              "saw non-type template parameter with wrong depth");
16550b57cec5SDimitry Andric       if (const ConstantArrayType *ConstantArrayArg
16560b57cec5SDimitry Andric             = dyn_cast<ConstantArrayType>(ArrayArg)) {
16570b57cec5SDimitry Andric         llvm::APSInt Size(ConstantArrayArg->getSize());
16580b57cec5SDimitry Andric         return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
16590b57cec5SDimitry Andric                                              S.Context.getSizeType(),
16600b57cec5SDimitry Andric                                              /*ArrayBound=*/true,
16610b57cec5SDimitry Andric                                              Info, Deduced);
16620b57cec5SDimitry Andric       }
16630b57cec5SDimitry Andric       if (const DependentSizedArrayType *DependentArrayArg
16640b57cec5SDimitry Andric             = dyn_cast<DependentSizedArrayType>(ArrayArg))
16650b57cec5SDimitry Andric         if (DependentArrayArg->getSizeExpr())
16660b57cec5SDimitry Andric           return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
16670b57cec5SDimitry Andric                                                DependentArrayArg->getSizeExpr(),
16680b57cec5SDimitry Andric                                                Info, Deduced);
16690b57cec5SDimitry Andric 
16700b57cec5SDimitry Andric       // Incomplete type does not match a dependently-sized array type
16710b57cec5SDimitry Andric       return Sema::TDK_NonDeducedMismatch;
16720b57cec5SDimitry Andric     }
16730b57cec5SDimitry Andric 
16740b57cec5SDimitry Andric     //     type(*)(T)
16750b57cec5SDimitry Andric     //     T(*)()
16760b57cec5SDimitry Andric     //     T(*)(T)
16770b57cec5SDimitry Andric     case Type::FunctionProto: {
16780b57cec5SDimitry Andric       unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
16790b57cec5SDimitry Andric       const FunctionProtoType *FunctionProtoArg =
16800b57cec5SDimitry Andric         dyn_cast<FunctionProtoType>(Arg);
16810b57cec5SDimitry Andric       if (!FunctionProtoArg)
16820b57cec5SDimitry Andric         return Sema::TDK_NonDeducedMismatch;
16830b57cec5SDimitry Andric 
16840b57cec5SDimitry Andric       const FunctionProtoType *FunctionProtoParam =
16850b57cec5SDimitry Andric         cast<FunctionProtoType>(Param);
16860b57cec5SDimitry Andric 
16870b57cec5SDimitry Andric       if (FunctionProtoParam->getMethodQuals()
16880b57cec5SDimitry Andric             != FunctionProtoArg->getMethodQuals() ||
16890b57cec5SDimitry Andric           FunctionProtoParam->getRefQualifier()
16900b57cec5SDimitry Andric             != FunctionProtoArg->getRefQualifier() ||
16910b57cec5SDimitry Andric           FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
16920b57cec5SDimitry Andric         return Sema::TDK_NonDeducedMismatch;
16930b57cec5SDimitry Andric 
16940b57cec5SDimitry Andric       // Check return types.
16950b57cec5SDimitry Andric       if (auto Result = DeduceTemplateArgumentsByTypeMatch(
16960b57cec5SDimitry Andric               S, TemplateParams, FunctionProtoParam->getReturnType(),
16970b57cec5SDimitry Andric               FunctionProtoArg->getReturnType(), Info, Deduced, 0))
16980b57cec5SDimitry Andric         return Result;
16990b57cec5SDimitry Andric 
17000b57cec5SDimitry Andric       // Check parameter types.
17010b57cec5SDimitry Andric       if (auto Result = DeduceTemplateArguments(
17020b57cec5SDimitry Andric               S, TemplateParams, FunctionProtoParam->param_type_begin(),
17030b57cec5SDimitry Andric               FunctionProtoParam->getNumParams(),
17040b57cec5SDimitry Andric               FunctionProtoArg->param_type_begin(),
17050b57cec5SDimitry Andric               FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF))
17060b57cec5SDimitry Andric         return Result;
17070b57cec5SDimitry Andric 
17080b57cec5SDimitry Andric       if (TDF & TDF_AllowCompatibleFunctionType)
17090b57cec5SDimitry Andric         return Sema::TDK_Success;
17100b57cec5SDimitry Andric 
17110b57cec5SDimitry Andric       // FIXME: Per core-2016/10/1019 (no corresponding core issue yet), permit
17120b57cec5SDimitry Andric       // deducing through the noexcept-specifier if it's part of the canonical
17130b57cec5SDimitry Andric       // type. libstdc++ relies on this.
17140b57cec5SDimitry Andric       Expr *NoexceptExpr = FunctionProtoParam->getNoexceptExpr();
17150b57cec5SDimitry Andric       if (NonTypeTemplateParmDecl *NTTP =
17160b57cec5SDimitry Andric           NoexceptExpr ? getDeducedParameterFromExpr(Info, NoexceptExpr)
17170b57cec5SDimitry Andric                        : nullptr) {
17180b57cec5SDimitry Andric         assert(NTTP->getDepth() == Info.getDeducedDepth() &&
17190b57cec5SDimitry Andric                "saw non-type template parameter with wrong depth");
17200b57cec5SDimitry Andric 
17210b57cec5SDimitry Andric         llvm::APSInt Noexcept(1);
17220b57cec5SDimitry Andric         switch (FunctionProtoArg->canThrow()) {
17230b57cec5SDimitry Andric         case CT_Cannot:
17240b57cec5SDimitry Andric           Noexcept = 1;
17250b57cec5SDimitry Andric           LLVM_FALLTHROUGH;
17260b57cec5SDimitry Andric 
17270b57cec5SDimitry Andric         case CT_Can:
17280b57cec5SDimitry Andric           // We give E in noexcept(E) the "deduced from array bound" treatment.
17290b57cec5SDimitry Andric           // FIXME: Should we?
17300b57cec5SDimitry Andric           return DeduceNonTypeTemplateArgument(
17310b57cec5SDimitry Andric               S, TemplateParams, NTTP, Noexcept, S.Context.BoolTy,
17320b57cec5SDimitry Andric               /*ArrayBound*/true, Info, Deduced);
17330b57cec5SDimitry Andric 
17340b57cec5SDimitry Andric         case CT_Dependent:
17350b57cec5SDimitry Andric           if (Expr *ArgNoexceptExpr = FunctionProtoArg->getNoexceptExpr())
17360b57cec5SDimitry Andric             return DeduceNonTypeTemplateArgument(
17370b57cec5SDimitry Andric                 S, TemplateParams, NTTP, ArgNoexceptExpr, Info, Deduced);
17380b57cec5SDimitry Andric           // Can't deduce anything from throw(T...).
17390b57cec5SDimitry Andric           break;
17400b57cec5SDimitry Andric         }
17410b57cec5SDimitry Andric       }
17420b57cec5SDimitry Andric       // FIXME: Detect non-deduced exception specification mismatches?
17430b57cec5SDimitry Andric       //
17440b57cec5SDimitry Andric       // Careful about [temp.deduct.call] and [temp.deduct.conv], which allow
17450b57cec5SDimitry Andric       // top-level differences in noexcept-specifications.
17460b57cec5SDimitry Andric 
17470b57cec5SDimitry Andric       return Sema::TDK_Success;
17480b57cec5SDimitry Andric     }
17490b57cec5SDimitry Andric 
17500b57cec5SDimitry Andric     case Type::InjectedClassName:
17510b57cec5SDimitry Andric       // Treat a template's injected-class-name as if the template
17520b57cec5SDimitry Andric       // specialization type had been used.
17530b57cec5SDimitry Andric       Param = cast<InjectedClassNameType>(Param)
17540b57cec5SDimitry Andric         ->getInjectedSpecializationType();
17550b57cec5SDimitry Andric       assert(isa<TemplateSpecializationType>(Param) &&
17560b57cec5SDimitry Andric              "injected class name is not a template specialization type");
17570b57cec5SDimitry Andric       LLVM_FALLTHROUGH;
17580b57cec5SDimitry Andric 
17590b57cec5SDimitry Andric     //     template-name<T> (where template-name refers to a class template)
17600b57cec5SDimitry Andric     //     template-name<i>
17610b57cec5SDimitry Andric     //     TT<T>
17620b57cec5SDimitry Andric     //     TT<i>
17630b57cec5SDimitry Andric     //     TT<>
17640b57cec5SDimitry Andric     case Type::TemplateSpecialization: {
17650b57cec5SDimitry Andric       const TemplateSpecializationType *SpecParam =
17660b57cec5SDimitry Andric           cast<TemplateSpecializationType>(Param);
17670b57cec5SDimitry Andric 
17680b57cec5SDimitry Andric       // When Arg cannot be a derived class, we can just try to deduce template
17690b57cec5SDimitry Andric       // arguments from the template-id.
17700b57cec5SDimitry Andric       const RecordType *RecordT = Arg->getAs<RecordType>();
17710b57cec5SDimitry Andric       if (!(TDF & TDF_DerivedClass) || !RecordT)
17720b57cec5SDimitry Andric         return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
17730b57cec5SDimitry Andric                                        Deduced);
17740b57cec5SDimitry Andric 
17750b57cec5SDimitry Andric       SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
17760b57cec5SDimitry Andric                                                           Deduced.end());
17770b57cec5SDimitry Andric 
17780b57cec5SDimitry Andric       Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
17790b57cec5SDimitry Andric           S, TemplateParams, SpecParam, Arg, Info, Deduced);
17800b57cec5SDimitry Andric 
17810b57cec5SDimitry Andric       if (Result == Sema::TDK_Success)
17820b57cec5SDimitry Andric         return Result;
17830b57cec5SDimitry Andric 
17840b57cec5SDimitry Andric       // We cannot inspect base classes as part of deduction when the type
17850b57cec5SDimitry Andric       // is incomplete, so either instantiate any templates necessary to
17860b57cec5SDimitry Andric       // complete the type, or skip over it if it cannot be completed.
17870b57cec5SDimitry Andric       if (!S.isCompleteType(Info.getLocation(), Arg))
17880b57cec5SDimitry Andric         return Result;
17890b57cec5SDimitry Andric 
17900b57cec5SDimitry Andric       // C++14 [temp.deduct.call] p4b3:
17910b57cec5SDimitry Andric       //   If P is a class and P has the form simple-template-id, then the
17920b57cec5SDimitry Andric       //   transformed A can be a derived class of the deduced A. Likewise if
17930b57cec5SDimitry Andric       //   P is a pointer to a class of the form simple-template-id, the
17940b57cec5SDimitry Andric       //   transformed A can be a pointer to a derived class pointed to by the
17950b57cec5SDimitry Andric       //   deduced A.
17960b57cec5SDimitry Andric       //
17970b57cec5SDimitry Andric       //   These alternatives are considered only if type deduction would
17980b57cec5SDimitry Andric       //   otherwise fail. If they yield more than one possible deduced A, the
17990b57cec5SDimitry Andric       //   type deduction fails.
18000b57cec5SDimitry Andric 
18010b57cec5SDimitry Andric       // Reset the incorrectly deduced argument from above.
18020b57cec5SDimitry Andric       Deduced = DeducedOrig;
18030b57cec5SDimitry Andric 
18040b57cec5SDimitry Andric       // Use data recursion to crawl through the list of base classes.
18050b57cec5SDimitry Andric       // Visited contains the set of nodes we have already visited, while
18060b57cec5SDimitry Andric       // ToVisit is our stack of records that we still need to visit.
18070b57cec5SDimitry Andric       llvm::SmallPtrSet<const RecordType *, 8> Visited;
18080b57cec5SDimitry Andric       SmallVector<const RecordType *, 8> ToVisit;
18090b57cec5SDimitry Andric       ToVisit.push_back(RecordT);
18100b57cec5SDimitry Andric       bool Successful = false;
18110b57cec5SDimitry Andric       SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
18120b57cec5SDimitry Andric       while (!ToVisit.empty()) {
18130b57cec5SDimitry Andric         // Retrieve the next class in the inheritance hierarchy.
18140b57cec5SDimitry Andric         const RecordType *NextT = ToVisit.pop_back_val();
18150b57cec5SDimitry Andric 
18160b57cec5SDimitry Andric         // If we have already seen this type, skip it.
18170b57cec5SDimitry Andric         if (!Visited.insert(NextT).second)
18180b57cec5SDimitry Andric           continue;
18190b57cec5SDimitry Andric 
18200b57cec5SDimitry Andric         // If this is a base class, try to perform template argument
18210b57cec5SDimitry Andric         // deduction from it.
18220b57cec5SDimitry Andric         if (NextT != RecordT) {
182347395794SDimitry Andric           TemplateDeductionInfo BaseInfo(TemplateDeductionInfo::ForBase, Info);
18240b57cec5SDimitry Andric           Sema::TemplateDeductionResult BaseResult =
18250b57cec5SDimitry Andric               DeduceTemplateArguments(S, TemplateParams, SpecParam,
18260b57cec5SDimitry Andric                                       QualType(NextT, 0), BaseInfo, Deduced);
18270b57cec5SDimitry Andric 
18280b57cec5SDimitry Andric           // If template argument deduction for this base was successful,
18290b57cec5SDimitry Andric           // note that we had some success. Otherwise, ignore any deductions
18300b57cec5SDimitry Andric           // from this base class.
18310b57cec5SDimitry Andric           if (BaseResult == Sema::TDK_Success) {
18320b57cec5SDimitry Andric             // If we've already seen some success, then deduction fails due to
18330b57cec5SDimitry Andric             // an ambiguity (temp.deduct.call p5).
18340b57cec5SDimitry Andric             if (Successful)
18350b57cec5SDimitry Andric               return Sema::TDK_MiscellaneousDeductionFailure;
18360b57cec5SDimitry Andric 
18370b57cec5SDimitry Andric             Successful = true;
18380b57cec5SDimitry Andric             std::swap(SuccessfulDeduced, Deduced);
18390b57cec5SDimitry Andric 
18400b57cec5SDimitry Andric             Info.Param = BaseInfo.Param;
18410b57cec5SDimitry Andric             Info.FirstArg = BaseInfo.FirstArg;
18420b57cec5SDimitry Andric             Info.SecondArg = BaseInfo.SecondArg;
18430b57cec5SDimitry Andric           }
18440b57cec5SDimitry Andric 
18450b57cec5SDimitry Andric           Deduced = DeducedOrig;
18460b57cec5SDimitry Andric         }
18470b57cec5SDimitry Andric 
18480b57cec5SDimitry Andric         // Visit base classes
18490b57cec5SDimitry Andric         CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
18500b57cec5SDimitry Andric         for (const auto &Base : Next->bases()) {
18510b57cec5SDimitry Andric           assert(Base.getType()->isRecordType() &&
18520b57cec5SDimitry Andric                  "Base class that isn't a record?");
18530b57cec5SDimitry Andric           ToVisit.push_back(Base.getType()->getAs<RecordType>());
18540b57cec5SDimitry Andric         }
18550b57cec5SDimitry Andric       }
18560b57cec5SDimitry Andric 
18570b57cec5SDimitry Andric       if (Successful) {
18580b57cec5SDimitry Andric         std::swap(SuccessfulDeduced, Deduced);
18590b57cec5SDimitry Andric         return Sema::TDK_Success;
18600b57cec5SDimitry Andric       }
18610b57cec5SDimitry Andric 
18620b57cec5SDimitry Andric       return Result;
18630b57cec5SDimitry Andric     }
18640b57cec5SDimitry Andric 
18650b57cec5SDimitry Andric     //     T type::*
18660b57cec5SDimitry Andric     //     T T::*
18670b57cec5SDimitry Andric     //     T (type::*)()
18680b57cec5SDimitry Andric     //     type (T::*)()
18690b57cec5SDimitry Andric     //     type (type::*)(T)
18700b57cec5SDimitry Andric     //     type (T::*)(T)
18710b57cec5SDimitry Andric     //     T (type::*)(T)
18720b57cec5SDimitry Andric     //     T (T::*)()
18730b57cec5SDimitry Andric     //     T (T::*)(T)
18740b57cec5SDimitry Andric     case Type::MemberPointer: {
18750b57cec5SDimitry Andric       const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
18760b57cec5SDimitry Andric       const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
18770b57cec5SDimitry Andric       if (!MemPtrArg)
18780b57cec5SDimitry Andric         return Sema::TDK_NonDeducedMismatch;
18790b57cec5SDimitry Andric 
18800b57cec5SDimitry Andric       QualType ParamPointeeType = MemPtrParam->getPointeeType();
18810b57cec5SDimitry Andric       if (ParamPointeeType->isFunctionType())
18820b57cec5SDimitry Andric         S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
18830b57cec5SDimitry Andric                                  /*IsCtorOrDtor=*/false, Info.getLocation());
18840b57cec5SDimitry Andric       QualType ArgPointeeType = MemPtrArg->getPointeeType();
18850b57cec5SDimitry Andric       if (ArgPointeeType->isFunctionType())
18860b57cec5SDimitry Andric         S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
18870b57cec5SDimitry Andric                                  /*IsCtorOrDtor=*/false, Info.getLocation());
18880b57cec5SDimitry Andric 
18890b57cec5SDimitry Andric       if (Sema::TemplateDeductionResult Result
18900b57cec5SDimitry Andric             = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
18910b57cec5SDimitry Andric                                                  ParamPointeeType,
18920b57cec5SDimitry Andric                                                  ArgPointeeType,
18930b57cec5SDimitry Andric                                                  Info, Deduced,
18940b57cec5SDimitry Andric                                                  TDF & TDF_IgnoreQualifiers))
18950b57cec5SDimitry Andric         return Result;
18960b57cec5SDimitry Andric 
18970b57cec5SDimitry Andric       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
18980b57cec5SDimitry Andric                                            QualType(MemPtrParam->getClass(), 0),
18990b57cec5SDimitry Andric                                            QualType(MemPtrArg->getClass(), 0),
19000b57cec5SDimitry Andric                                            Info, Deduced,
19010b57cec5SDimitry Andric                                            TDF & TDF_IgnoreQualifiers);
19020b57cec5SDimitry Andric     }
19030b57cec5SDimitry Andric 
19040b57cec5SDimitry Andric     //     (clang extension)
19050b57cec5SDimitry Andric     //
19060b57cec5SDimitry Andric     //     type(^)(T)
19070b57cec5SDimitry Andric     //     T(^)()
19080b57cec5SDimitry Andric     //     T(^)(T)
19090b57cec5SDimitry Andric     case Type::BlockPointer: {
19100b57cec5SDimitry Andric       const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
19110b57cec5SDimitry Andric       const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
19120b57cec5SDimitry Andric 
19130b57cec5SDimitry Andric       if (!BlockPtrArg)
19140b57cec5SDimitry Andric         return Sema::TDK_NonDeducedMismatch;
19150b57cec5SDimitry Andric 
19160b57cec5SDimitry Andric       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
19170b57cec5SDimitry Andric                                                 BlockPtrParam->getPointeeType(),
19180b57cec5SDimitry Andric                                                 BlockPtrArg->getPointeeType(),
19190b57cec5SDimitry Andric                                                 Info, Deduced, 0);
19200b57cec5SDimitry Andric     }
19210b57cec5SDimitry Andric 
19220b57cec5SDimitry Andric     //     (clang extension)
19230b57cec5SDimitry Andric     //
19240b57cec5SDimitry Andric     //     T __attribute__(((ext_vector_type(<integral constant>))))
19250b57cec5SDimitry Andric     case Type::ExtVector: {
19260b57cec5SDimitry Andric       const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
19270b57cec5SDimitry Andric       if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
19280b57cec5SDimitry Andric         // Make sure that the vectors have the same number of elements.
19290b57cec5SDimitry Andric         if (VectorParam->getNumElements() != VectorArg->getNumElements())
19300b57cec5SDimitry Andric           return Sema::TDK_NonDeducedMismatch;
19310b57cec5SDimitry Andric 
19320b57cec5SDimitry Andric         // Perform deduction on the element types.
19330b57cec5SDimitry Andric         return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
19340b57cec5SDimitry Andric                                                   VectorParam->getElementType(),
19350b57cec5SDimitry Andric                                                   VectorArg->getElementType(),
19360b57cec5SDimitry Andric                                                   Info, Deduced, TDF);
19370b57cec5SDimitry Andric       }
19380b57cec5SDimitry Andric 
19390b57cec5SDimitry Andric       if (const DependentSizedExtVectorType *VectorArg
19400b57cec5SDimitry Andric                                 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
19410b57cec5SDimitry Andric         // We can't check the number of elements, since the argument has a
19420b57cec5SDimitry Andric         // dependent number of elements. This can only occur during partial
19430b57cec5SDimitry Andric         // ordering.
19440b57cec5SDimitry Andric 
19450b57cec5SDimitry Andric         // Perform deduction on the element types.
19460b57cec5SDimitry Andric         return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
19470b57cec5SDimitry Andric                                                   VectorParam->getElementType(),
19480b57cec5SDimitry Andric                                                   VectorArg->getElementType(),
19490b57cec5SDimitry Andric                                                   Info, Deduced, TDF);
19500b57cec5SDimitry Andric       }
19510b57cec5SDimitry Andric 
19520b57cec5SDimitry Andric       return Sema::TDK_NonDeducedMismatch;
19530b57cec5SDimitry Andric     }
19540b57cec5SDimitry Andric 
19550b57cec5SDimitry Andric     case Type::DependentVector: {
19560b57cec5SDimitry Andric       const auto *VectorParam = cast<DependentVectorType>(Param);
19570b57cec5SDimitry Andric 
19580b57cec5SDimitry Andric       if (const auto *VectorArg = dyn_cast<VectorType>(Arg)) {
19590b57cec5SDimitry Andric         // Perform deduction on the element types.
19600b57cec5SDimitry Andric         if (Sema::TemplateDeductionResult Result =
19610b57cec5SDimitry Andric                 DeduceTemplateArgumentsByTypeMatch(
19620b57cec5SDimitry Andric                     S, TemplateParams, VectorParam->getElementType(),
19630b57cec5SDimitry Andric                     VectorArg->getElementType(), Info, Deduced, TDF))
19640b57cec5SDimitry Andric           return Result;
19650b57cec5SDimitry Andric 
19660b57cec5SDimitry Andric         // Perform deduction on the vector size, if we can.
19670b57cec5SDimitry Andric         NonTypeTemplateParmDecl *NTTP =
19680b57cec5SDimitry Andric             getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
19690b57cec5SDimitry Andric         if (!NTTP)
19700b57cec5SDimitry Andric           return Sema::TDK_Success;
19710b57cec5SDimitry Andric 
19720b57cec5SDimitry Andric         llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
19730b57cec5SDimitry Andric         ArgSize = VectorArg->getNumElements();
19740b57cec5SDimitry Andric         // Note that we use the "array bound" rules here; just like in that
19750b57cec5SDimitry Andric         // case, we don't have any particular type for the vector size, but
19760b57cec5SDimitry Andric         // we can provide one if necessary.
19770b57cec5SDimitry Andric         return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
19780b57cec5SDimitry Andric                                              S.Context.UnsignedIntTy, true,
19790b57cec5SDimitry Andric                                              Info, Deduced);
19800b57cec5SDimitry Andric       }
19810b57cec5SDimitry Andric 
19820b57cec5SDimitry Andric       if (const auto *VectorArg = dyn_cast<DependentVectorType>(Arg)) {
19830b57cec5SDimitry Andric         // Perform deduction on the element types.
19840b57cec5SDimitry Andric         if (Sema::TemplateDeductionResult Result =
19850b57cec5SDimitry Andric                 DeduceTemplateArgumentsByTypeMatch(
19860b57cec5SDimitry Andric                     S, TemplateParams, VectorParam->getElementType(),
19870b57cec5SDimitry Andric                     VectorArg->getElementType(), Info, Deduced, TDF))
19880b57cec5SDimitry Andric           return Result;
19890b57cec5SDimitry Andric 
19900b57cec5SDimitry Andric         // Perform deduction on the vector size, if we can.
19910b57cec5SDimitry Andric         NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
19920b57cec5SDimitry Andric             Info, VectorParam->getSizeExpr());
19930b57cec5SDimitry Andric         if (!NTTP)
19940b57cec5SDimitry Andric           return Sema::TDK_Success;
19950b57cec5SDimitry Andric 
19960b57cec5SDimitry Andric         return DeduceNonTypeTemplateArgument(
19970b57cec5SDimitry Andric             S, TemplateParams, NTTP, VectorArg->getSizeExpr(), Info, Deduced);
19980b57cec5SDimitry Andric       }
19990b57cec5SDimitry Andric 
20000b57cec5SDimitry Andric       return Sema::TDK_NonDeducedMismatch;
20010b57cec5SDimitry Andric     }
20020b57cec5SDimitry Andric 
20030b57cec5SDimitry Andric     //     (clang extension)
20040b57cec5SDimitry Andric     //
20050b57cec5SDimitry Andric     //     T __attribute__(((ext_vector_type(N))))
20060b57cec5SDimitry Andric     case Type::DependentSizedExtVector: {
20070b57cec5SDimitry Andric       const DependentSizedExtVectorType *VectorParam
20080b57cec5SDimitry Andric         = cast<DependentSizedExtVectorType>(Param);
20090b57cec5SDimitry Andric 
20100b57cec5SDimitry Andric       if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
20110b57cec5SDimitry Andric         // Perform deduction on the element types.
20120b57cec5SDimitry Andric         if (Sema::TemplateDeductionResult Result
20130b57cec5SDimitry Andric               = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
20140b57cec5SDimitry Andric                                                   VectorParam->getElementType(),
20150b57cec5SDimitry Andric                                                    VectorArg->getElementType(),
20160b57cec5SDimitry Andric                                                    Info, Deduced, TDF))
20170b57cec5SDimitry Andric           return Result;
20180b57cec5SDimitry Andric 
20190b57cec5SDimitry Andric         // Perform deduction on the vector size, if we can.
20200b57cec5SDimitry Andric         NonTypeTemplateParmDecl *NTTP
20210b57cec5SDimitry Andric           = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
20220b57cec5SDimitry Andric         if (!NTTP)
20230b57cec5SDimitry Andric           return Sema::TDK_Success;
20240b57cec5SDimitry Andric 
20250b57cec5SDimitry Andric         llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
20260b57cec5SDimitry Andric         ArgSize = VectorArg->getNumElements();
20270b57cec5SDimitry Andric         // Note that we use the "array bound" rules here; just like in that
20280b57cec5SDimitry Andric         // case, we don't have any particular type for the vector size, but
20290b57cec5SDimitry Andric         // we can provide one if necessary.
20300b57cec5SDimitry Andric         return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
20310b57cec5SDimitry Andric                                              S.Context.IntTy, true, Info,
20320b57cec5SDimitry Andric                                              Deduced);
20330b57cec5SDimitry Andric       }
20340b57cec5SDimitry Andric 
20350b57cec5SDimitry Andric       if (const DependentSizedExtVectorType *VectorArg
20360b57cec5SDimitry Andric                                 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
20370b57cec5SDimitry Andric         // Perform deduction on the element types.
20380b57cec5SDimitry Andric         if (Sema::TemplateDeductionResult Result
20390b57cec5SDimitry Andric             = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
20400b57cec5SDimitry Andric                                                  VectorParam->getElementType(),
20410b57cec5SDimitry Andric                                                  VectorArg->getElementType(),
20420b57cec5SDimitry Andric                                                  Info, Deduced, TDF))
20430b57cec5SDimitry Andric           return Result;
20440b57cec5SDimitry Andric 
20450b57cec5SDimitry Andric         // Perform deduction on the vector size, if we can.
20460b57cec5SDimitry Andric         NonTypeTemplateParmDecl *NTTP
20470b57cec5SDimitry Andric           = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
20480b57cec5SDimitry Andric         if (!NTTP)
20490b57cec5SDimitry Andric           return Sema::TDK_Success;
20500b57cec5SDimitry Andric 
20510b57cec5SDimitry Andric         return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
20520b57cec5SDimitry Andric                                              VectorArg->getSizeExpr(),
20530b57cec5SDimitry Andric                                              Info, Deduced);
20540b57cec5SDimitry Andric       }
20550b57cec5SDimitry Andric 
20560b57cec5SDimitry Andric       return Sema::TDK_NonDeducedMismatch;
20570b57cec5SDimitry Andric     }
20580b57cec5SDimitry Andric 
20590b57cec5SDimitry Andric     //     (clang extension)
20600b57cec5SDimitry Andric     //
20615ffd83dbSDimitry Andric     //     T __attribute__((matrix_type(<integral constant>,
20625ffd83dbSDimitry Andric     //                                  <integral constant>)))
20635ffd83dbSDimitry Andric     case Type::ConstantMatrix: {
20645ffd83dbSDimitry Andric       const ConstantMatrixType *MatrixArg = dyn_cast<ConstantMatrixType>(Arg);
20655ffd83dbSDimitry Andric       if (!MatrixArg)
20665ffd83dbSDimitry Andric         return Sema::TDK_NonDeducedMismatch;
20675ffd83dbSDimitry Andric 
20685ffd83dbSDimitry Andric       const ConstantMatrixType *MatrixParam = cast<ConstantMatrixType>(Param);
20695ffd83dbSDimitry Andric       // Check that the dimensions are the same
20705ffd83dbSDimitry Andric       if (MatrixParam->getNumRows() != MatrixArg->getNumRows() ||
20715ffd83dbSDimitry Andric           MatrixParam->getNumColumns() != MatrixArg->getNumColumns()) {
20725ffd83dbSDimitry Andric         return Sema::TDK_NonDeducedMismatch;
20735ffd83dbSDimitry Andric       }
20745ffd83dbSDimitry Andric       // Perform deduction on element types.
20755ffd83dbSDimitry Andric       return DeduceTemplateArgumentsByTypeMatch(
20765ffd83dbSDimitry Andric           S, TemplateParams, MatrixParam->getElementType(),
20775ffd83dbSDimitry Andric           MatrixArg->getElementType(), Info, Deduced, TDF);
20785ffd83dbSDimitry Andric     }
20795ffd83dbSDimitry Andric 
20805ffd83dbSDimitry Andric     case Type::DependentSizedMatrix: {
20815ffd83dbSDimitry Andric       const MatrixType *MatrixArg = dyn_cast<MatrixType>(Arg);
20825ffd83dbSDimitry Andric       if (!MatrixArg)
20835ffd83dbSDimitry Andric         return Sema::TDK_NonDeducedMismatch;
20845ffd83dbSDimitry Andric 
20855ffd83dbSDimitry Andric       // Check the element type of the matrixes.
20865ffd83dbSDimitry Andric       const DependentSizedMatrixType *MatrixParam =
20875ffd83dbSDimitry Andric           cast<DependentSizedMatrixType>(Param);
20885ffd83dbSDimitry Andric       if (Sema::TemplateDeductionResult Result =
20895ffd83dbSDimitry Andric               DeduceTemplateArgumentsByTypeMatch(
20905ffd83dbSDimitry Andric                   S, TemplateParams, MatrixParam->getElementType(),
20915ffd83dbSDimitry Andric                   MatrixArg->getElementType(), Info, Deduced, TDF))
20925ffd83dbSDimitry Andric         return Result;
20935ffd83dbSDimitry Andric 
20945ffd83dbSDimitry Andric       // Try to deduce a matrix dimension.
20955ffd83dbSDimitry Andric       auto DeduceMatrixArg =
20965ffd83dbSDimitry Andric           [&S, &Info, &Deduced, &TemplateParams](
20975ffd83dbSDimitry Andric               Expr *ParamExpr, const MatrixType *Arg,
20985ffd83dbSDimitry Andric               unsigned (ConstantMatrixType::*GetArgDimension)() const,
20995ffd83dbSDimitry Andric               Expr *(DependentSizedMatrixType::*GetArgDimensionExpr)() const) {
21005ffd83dbSDimitry Andric             const auto *ArgConstMatrix = dyn_cast<ConstantMatrixType>(Arg);
21015ffd83dbSDimitry Andric             const auto *ArgDepMatrix = dyn_cast<DependentSizedMatrixType>(Arg);
21025ffd83dbSDimitry Andric             if (!ParamExpr->isValueDependent()) {
21035ffd83dbSDimitry Andric               llvm::APSInt ParamConst(
21045ffd83dbSDimitry Andric                   S.Context.getTypeSize(S.Context.getSizeType()));
21055ffd83dbSDimitry Andric               if (!ParamExpr->isIntegerConstantExpr(ParamConst, S.Context))
21065ffd83dbSDimitry Andric                 return Sema::TDK_NonDeducedMismatch;
21075ffd83dbSDimitry Andric 
21085ffd83dbSDimitry Andric               if (ArgConstMatrix) {
21095ffd83dbSDimitry Andric                 if ((ArgConstMatrix->*GetArgDimension)() == ParamConst)
21105ffd83dbSDimitry Andric                   return Sema::TDK_Success;
21115ffd83dbSDimitry Andric                 return Sema::TDK_NonDeducedMismatch;
21125ffd83dbSDimitry Andric               }
21135ffd83dbSDimitry Andric 
21145ffd83dbSDimitry Andric               Expr *ArgExpr = (ArgDepMatrix->*GetArgDimensionExpr)();
21155ffd83dbSDimitry Andric               llvm::APSInt ArgConst(
21165ffd83dbSDimitry Andric                   S.Context.getTypeSize(S.Context.getSizeType()));
21175ffd83dbSDimitry Andric               if (!ArgExpr->isValueDependent() &&
21185ffd83dbSDimitry Andric                   ArgExpr->isIntegerConstantExpr(ArgConst, S.Context) &&
21195ffd83dbSDimitry Andric                   ArgConst == ParamConst)
21205ffd83dbSDimitry Andric                 return Sema::TDK_Success;
21215ffd83dbSDimitry Andric               return Sema::TDK_NonDeducedMismatch;
21225ffd83dbSDimitry Andric             }
21235ffd83dbSDimitry Andric 
21245ffd83dbSDimitry Andric             NonTypeTemplateParmDecl *NTTP =
21255ffd83dbSDimitry Andric                 getDeducedParameterFromExpr(Info, ParamExpr);
21265ffd83dbSDimitry Andric             if (!NTTP)
21275ffd83dbSDimitry Andric               return Sema::TDK_Success;
21285ffd83dbSDimitry Andric 
21295ffd83dbSDimitry Andric             if (ArgConstMatrix) {
21305ffd83dbSDimitry Andric               llvm::APSInt ArgConst(
21315ffd83dbSDimitry Andric                   S.Context.getTypeSize(S.Context.getSizeType()));
21325ffd83dbSDimitry Andric               ArgConst = (ArgConstMatrix->*GetArgDimension)();
21335ffd83dbSDimitry Andric               return DeduceNonTypeTemplateArgument(
21345ffd83dbSDimitry Andric                   S, TemplateParams, NTTP, ArgConst, S.Context.getSizeType(),
21355ffd83dbSDimitry Andric                   /*ArrayBound=*/true, Info, Deduced);
21365ffd83dbSDimitry Andric             }
21375ffd83dbSDimitry Andric 
21385ffd83dbSDimitry Andric             return DeduceNonTypeTemplateArgument(
21395ffd83dbSDimitry Andric                 S, TemplateParams, NTTP, (ArgDepMatrix->*GetArgDimensionExpr)(),
21405ffd83dbSDimitry Andric                 Info, Deduced);
21415ffd83dbSDimitry Andric           };
21425ffd83dbSDimitry Andric 
21435ffd83dbSDimitry Andric       auto Result = DeduceMatrixArg(MatrixParam->getRowExpr(), MatrixArg,
21445ffd83dbSDimitry Andric                                     &ConstantMatrixType::getNumRows,
21455ffd83dbSDimitry Andric                                     &DependentSizedMatrixType::getRowExpr);
21465ffd83dbSDimitry Andric       if (Result)
21475ffd83dbSDimitry Andric         return Result;
21485ffd83dbSDimitry Andric 
21495ffd83dbSDimitry Andric       return DeduceMatrixArg(MatrixParam->getColumnExpr(), MatrixArg,
21505ffd83dbSDimitry Andric                              &ConstantMatrixType::getNumColumns,
21515ffd83dbSDimitry Andric                              &DependentSizedMatrixType::getColumnExpr);
21525ffd83dbSDimitry Andric     }
21535ffd83dbSDimitry Andric 
21545ffd83dbSDimitry Andric     //     (clang extension)
21555ffd83dbSDimitry Andric     //
21560b57cec5SDimitry Andric     //     T __attribute__(((address_space(N))))
21570b57cec5SDimitry Andric     case Type::DependentAddressSpace: {
21580b57cec5SDimitry Andric       const DependentAddressSpaceType *AddressSpaceParam =
21590b57cec5SDimitry Andric           cast<DependentAddressSpaceType>(Param);
21600b57cec5SDimitry Andric 
21610b57cec5SDimitry Andric       if (const DependentAddressSpaceType *AddressSpaceArg =
21620b57cec5SDimitry Andric               dyn_cast<DependentAddressSpaceType>(Arg)) {
21630b57cec5SDimitry Andric         // Perform deduction on the pointer type.
21640b57cec5SDimitry Andric         if (Sema::TemplateDeductionResult Result =
21650b57cec5SDimitry Andric                 DeduceTemplateArgumentsByTypeMatch(
21660b57cec5SDimitry Andric                     S, TemplateParams, AddressSpaceParam->getPointeeType(),
21670b57cec5SDimitry Andric                     AddressSpaceArg->getPointeeType(), Info, Deduced, TDF))
21680b57cec5SDimitry Andric           return Result;
21690b57cec5SDimitry Andric 
21700b57cec5SDimitry Andric         // Perform deduction on the address space, if we can.
21710b57cec5SDimitry Andric         NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
21720b57cec5SDimitry Andric             Info, AddressSpaceParam->getAddrSpaceExpr());
21730b57cec5SDimitry Andric         if (!NTTP)
21740b57cec5SDimitry Andric           return Sema::TDK_Success;
21750b57cec5SDimitry Andric 
21760b57cec5SDimitry Andric         return DeduceNonTypeTemplateArgument(
21770b57cec5SDimitry Andric             S, TemplateParams, NTTP, AddressSpaceArg->getAddrSpaceExpr(), Info,
21780b57cec5SDimitry Andric             Deduced);
21790b57cec5SDimitry Andric       }
21800b57cec5SDimitry Andric 
21810b57cec5SDimitry Andric       if (isTargetAddressSpace(Arg.getAddressSpace())) {
21820b57cec5SDimitry Andric         llvm::APSInt ArgAddressSpace(S.Context.getTypeSize(S.Context.IntTy),
21830b57cec5SDimitry Andric                                      false);
21840b57cec5SDimitry Andric         ArgAddressSpace = toTargetAddressSpace(Arg.getAddressSpace());
21850b57cec5SDimitry Andric 
21860b57cec5SDimitry Andric         // Perform deduction on the pointer types.
21870b57cec5SDimitry Andric         if (Sema::TemplateDeductionResult Result =
21880b57cec5SDimitry Andric                 DeduceTemplateArgumentsByTypeMatch(
21890b57cec5SDimitry Andric                     S, TemplateParams, AddressSpaceParam->getPointeeType(),
21900b57cec5SDimitry Andric                     S.Context.removeAddrSpaceQualType(Arg), Info, Deduced, TDF))
21910b57cec5SDimitry Andric           return Result;
21920b57cec5SDimitry Andric 
21930b57cec5SDimitry Andric         // Perform deduction on the address space, if we can.
21940b57cec5SDimitry Andric         NonTypeTemplateParmDecl *NTTP = getDeducedParameterFromExpr(
21950b57cec5SDimitry Andric             Info, AddressSpaceParam->getAddrSpaceExpr());
21960b57cec5SDimitry Andric         if (!NTTP)
21970b57cec5SDimitry Andric           return Sema::TDK_Success;
21980b57cec5SDimitry Andric 
21990b57cec5SDimitry Andric         return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
22000b57cec5SDimitry Andric                                              ArgAddressSpace, S.Context.IntTy,
22010b57cec5SDimitry Andric                                              true, Info, Deduced);
22020b57cec5SDimitry Andric       }
22030b57cec5SDimitry Andric 
22040b57cec5SDimitry Andric       return Sema::TDK_NonDeducedMismatch;
22050b57cec5SDimitry Andric     }
22065ffd83dbSDimitry Andric     case Type::DependentExtInt: {
22075ffd83dbSDimitry Andric       const auto *IntParam = cast<DependentExtIntType>(Param);
22085ffd83dbSDimitry Andric 
22095ffd83dbSDimitry Andric       if (const auto *IntArg = dyn_cast<ExtIntType>(Arg)){
22105ffd83dbSDimitry Andric         if (IntParam->isUnsigned() != IntArg->isUnsigned())
22115ffd83dbSDimitry Andric           return Sema::TDK_NonDeducedMismatch;
22125ffd83dbSDimitry Andric 
22135ffd83dbSDimitry Andric         NonTypeTemplateParmDecl *NTTP =
22145ffd83dbSDimitry Andric             getDeducedParameterFromExpr(Info, IntParam->getNumBitsExpr());
22155ffd83dbSDimitry Andric         if (!NTTP)
22165ffd83dbSDimitry Andric           return Sema::TDK_Success;
22175ffd83dbSDimitry Andric 
22185ffd83dbSDimitry Andric         llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
22195ffd83dbSDimitry Andric         ArgSize = IntArg->getNumBits();
22205ffd83dbSDimitry Andric 
22215ffd83dbSDimitry Andric         return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
22225ffd83dbSDimitry Andric                                              S.Context.IntTy, true, Info,
22235ffd83dbSDimitry Andric                                              Deduced);
22245ffd83dbSDimitry Andric       }
22255ffd83dbSDimitry Andric 
22265ffd83dbSDimitry Andric       if (const auto *IntArg = dyn_cast<DependentExtIntType>(Arg)) {
22275ffd83dbSDimitry Andric         if (IntParam->isUnsigned() != IntArg->isUnsigned())
22285ffd83dbSDimitry Andric           return Sema::TDK_NonDeducedMismatch;
22295ffd83dbSDimitry Andric         return Sema::TDK_Success;
22305ffd83dbSDimitry Andric       }
22315ffd83dbSDimitry Andric       return Sema::TDK_NonDeducedMismatch;
22325ffd83dbSDimitry Andric     }
22330b57cec5SDimitry Andric 
22340b57cec5SDimitry Andric     case Type::TypeOfExpr:
22350b57cec5SDimitry Andric     case Type::TypeOf:
22360b57cec5SDimitry Andric     case Type::DependentName:
22370b57cec5SDimitry Andric     case Type::UnresolvedUsing:
22380b57cec5SDimitry Andric     case Type::Decltype:
22390b57cec5SDimitry Andric     case Type::UnaryTransform:
22400b57cec5SDimitry Andric     case Type::Auto:
22410b57cec5SDimitry Andric     case Type::DeducedTemplateSpecialization:
22420b57cec5SDimitry Andric     case Type::DependentTemplateSpecialization:
22430b57cec5SDimitry Andric     case Type::PackExpansion:
22440b57cec5SDimitry Andric     case Type::Pipe:
22450b57cec5SDimitry Andric       // No template argument deduction for these types
22460b57cec5SDimitry Andric       return Sema::TDK_Success;
22470b57cec5SDimitry Andric   }
22480b57cec5SDimitry Andric 
22490b57cec5SDimitry Andric   llvm_unreachable("Invalid Type Class!");
22500b57cec5SDimitry Andric }
22510b57cec5SDimitry Andric 
22520b57cec5SDimitry Andric static Sema::TemplateDeductionResult
22530b57cec5SDimitry Andric DeduceTemplateArguments(Sema &S,
22540b57cec5SDimitry Andric                         TemplateParameterList *TemplateParams,
22550b57cec5SDimitry Andric                         const TemplateArgument &Param,
22560b57cec5SDimitry Andric                         TemplateArgument Arg,
22570b57cec5SDimitry Andric                         TemplateDeductionInfo &Info,
22580b57cec5SDimitry Andric                         SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
22590b57cec5SDimitry Andric   // If the template argument is a pack expansion, perform template argument
22600b57cec5SDimitry Andric   // deduction against the pattern of that expansion. This only occurs during
22610b57cec5SDimitry Andric   // partial ordering.
22620b57cec5SDimitry Andric   if (Arg.isPackExpansion())
22630b57cec5SDimitry Andric     Arg = Arg.getPackExpansionPattern();
22640b57cec5SDimitry Andric 
22650b57cec5SDimitry Andric   switch (Param.getKind()) {
22660b57cec5SDimitry Andric   case TemplateArgument::Null:
22670b57cec5SDimitry Andric     llvm_unreachable("Null template argument in parameter list");
22680b57cec5SDimitry Andric 
22690b57cec5SDimitry Andric   case TemplateArgument::Type:
22700b57cec5SDimitry Andric     if (Arg.getKind() == TemplateArgument::Type)
22710b57cec5SDimitry Andric       return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
22720b57cec5SDimitry Andric                                                 Param.getAsType(),
22730b57cec5SDimitry Andric                                                 Arg.getAsType(),
22740b57cec5SDimitry Andric                                                 Info, Deduced, 0);
22750b57cec5SDimitry Andric     Info.FirstArg = Param;
22760b57cec5SDimitry Andric     Info.SecondArg = Arg;
22770b57cec5SDimitry Andric     return Sema::TDK_NonDeducedMismatch;
22780b57cec5SDimitry Andric 
22790b57cec5SDimitry Andric   case TemplateArgument::Template:
22800b57cec5SDimitry Andric     if (Arg.getKind() == TemplateArgument::Template)
22810b57cec5SDimitry Andric       return DeduceTemplateArguments(S, TemplateParams,
22820b57cec5SDimitry Andric                                      Param.getAsTemplate(),
22830b57cec5SDimitry Andric                                      Arg.getAsTemplate(), Info, Deduced);
22840b57cec5SDimitry Andric     Info.FirstArg = Param;
22850b57cec5SDimitry Andric     Info.SecondArg = Arg;
22860b57cec5SDimitry Andric     return Sema::TDK_NonDeducedMismatch;
22870b57cec5SDimitry Andric 
22880b57cec5SDimitry Andric   case TemplateArgument::TemplateExpansion:
22890b57cec5SDimitry Andric     llvm_unreachable("caller should handle pack expansions");
22900b57cec5SDimitry Andric 
22910b57cec5SDimitry Andric   case TemplateArgument::Declaration:
22920b57cec5SDimitry Andric     if (Arg.getKind() == TemplateArgument::Declaration &&
22930b57cec5SDimitry Andric         isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
22940b57cec5SDimitry Andric       return Sema::TDK_Success;
22950b57cec5SDimitry Andric 
22960b57cec5SDimitry Andric     Info.FirstArg = Param;
22970b57cec5SDimitry Andric     Info.SecondArg = Arg;
22980b57cec5SDimitry Andric     return Sema::TDK_NonDeducedMismatch;
22990b57cec5SDimitry Andric 
23000b57cec5SDimitry Andric   case TemplateArgument::NullPtr:
23010b57cec5SDimitry Andric     if (Arg.getKind() == TemplateArgument::NullPtr &&
23020b57cec5SDimitry Andric         S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
23030b57cec5SDimitry Andric       return Sema::TDK_Success;
23040b57cec5SDimitry Andric 
23050b57cec5SDimitry Andric     Info.FirstArg = Param;
23060b57cec5SDimitry Andric     Info.SecondArg = Arg;
23070b57cec5SDimitry Andric     return Sema::TDK_NonDeducedMismatch;
23080b57cec5SDimitry Andric 
23090b57cec5SDimitry Andric   case TemplateArgument::Integral:
23100b57cec5SDimitry Andric     if (Arg.getKind() == TemplateArgument::Integral) {
23110b57cec5SDimitry Andric       if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
23120b57cec5SDimitry Andric         return Sema::TDK_Success;
23130b57cec5SDimitry Andric 
23140b57cec5SDimitry Andric       Info.FirstArg = Param;
23150b57cec5SDimitry Andric       Info.SecondArg = Arg;
23160b57cec5SDimitry Andric       return Sema::TDK_NonDeducedMismatch;
23170b57cec5SDimitry Andric     }
23180b57cec5SDimitry Andric 
23190b57cec5SDimitry Andric     if (Arg.getKind() == TemplateArgument::Expression) {
23200b57cec5SDimitry Andric       Info.FirstArg = Param;
23210b57cec5SDimitry Andric       Info.SecondArg = Arg;
23220b57cec5SDimitry Andric       return Sema::TDK_NonDeducedMismatch;
23230b57cec5SDimitry Andric     }
23240b57cec5SDimitry Andric 
23250b57cec5SDimitry Andric     Info.FirstArg = Param;
23260b57cec5SDimitry Andric     Info.SecondArg = Arg;
23270b57cec5SDimitry Andric     return Sema::TDK_NonDeducedMismatch;
23280b57cec5SDimitry Andric 
23290b57cec5SDimitry Andric   case TemplateArgument::Expression:
23300b57cec5SDimitry Andric     if (NonTypeTemplateParmDecl *NTTP
23310b57cec5SDimitry Andric           = getDeducedParameterFromExpr(Info, Param.getAsExpr())) {
23320b57cec5SDimitry Andric       if (Arg.getKind() == TemplateArgument::Integral)
23330b57cec5SDimitry Andric         return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
23340b57cec5SDimitry Andric                                              Arg.getAsIntegral(),
23350b57cec5SDimitry Andric                                              Arg.getIntegralType(),
23360b57cec5SDimitry Andric                                              /*ArrayBound=*/false,
23370b57cec5SDimitry Andric                                              Info, Deduced);
23380b57cec5SDimitry Andric       if (Arg.getKind() == TemplateArgument::NullPtr)
23390b57cec5SDimitry Andric         return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
23400b57cec5SDimitry Andric                                              Arg.getNullPtrType(),
23410b57cec5SDimitry Andric                                              Info, Deduced);
23420b57cec5SDimitry Andric       if (Arg.getKind() == TemplateArgument::Expression)
23430b57cec5SDimitry Andric         return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
23440b57cec5SDimitry Andric                                              Arg.getAsExpr(), Info, Deduced);
23450b57cec5SDimitry Andric       if (Arg.getKind() == TemplateArgument::Declaration)
23460b57cec5SDimitry Andric         return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
23470b57cec5SDimitry Andric                                              Arg.getAsDecl(),
23480b57cec5SDimitry Andric                                              Arg.getParamTypeForDecl(),
23490b57cec5SDimitry Andric                                              Info, Deduced);
23500b57cec5SDimitry Andric 
23510b57cec5SDimitry Andric       Info.FirstArg = Param;
23520b57cec5SDimitry Andric       Info.SecondArg = Arg;
23530b57cec5SDimitry Andric       return Sema::TDK_NonDeducedMismatch;
23540b57cec5SDimitry Andric     }
23550b57cec5SDimitry Andric 
23560b57cec5SDimitry Andric     // Can't deduce anything, but that's okay.
23570b57cec5SDimitry Andric     return Sema::TDK_Success;
23580b57cec5SDimitry Andric 
23590b57cec5SDimitry Andric   case TemplateArgument::Pack:
23600b57cec5SDimitry Andric     llvm_unreachable("Argument packs should be expanded by the caller!");
23610b57cec5SDimitry Andric   }
23620b57cec5SDimitry Andric 
23630b57cec5SDimitry Andric   llvm_unreachable("Invalid TemplateArgument Kind!");
23640b57cec5SDimitry Andric }
23650b57cec5SDimitry Andric 
23660b57cec5SDimitry Andric /// Determine whether there is a template argument to be used for
23670b57cec5SDimitry Andric /// deduction.
23680b57cec5SDimitry Andric ///
23690b57cec5SDimitry Andric /// This routine "expands" argument packs in-place, overriding its input
23700b57cec5SDimitry Andric /// parameters so that \c Args[ArgIdx] will be the available template argument.
23710b57cec5SDimitry Andric ///
23720b57cec5SDimitry Andric /// \returns true if there is another template argument (which will be at
23730b57cec5SDimitry Andric /// \c Args[ArgIdx]), false otherwise.
23740b57cec5SDimitry Andric static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
23750b57cec5SDimitry Andric                                             unsigned &ArgIdx) {
23760b57cec5SDimitry Andric   if (ArgIdx == Args.size())
23770b57cec5SDimitry Andric     return false;
23780b57cec5SDimitry Andric 
23790b57cec5SDimitry Andric   const TemplateArgument &Arg = Args[ArgIdx];
23800b57cec5SDimitry Andric   if (Arg.getKind() != TemplateArgument::Pack)
23810b57cec5SDimitry Andric     return true;
23820b57cec5SDimitry Andric 
23830b57cec5SDimitry Andric   assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
23840b57cec5SDimitry Andric   Args = Arg.pack_elements();
23850b57cec5SDimitry Andric   ArgIdx = 0;
23860b57cec5SDimitry Andric   return ArgIdx < Args.size();
23870b57cec5SDimitry Andric }
23880b57cec5SDimitry Andric 
23890b57cec5SDimitry Andric /// Determine whether the given set of template arguments has a pack
23900b57cec5SDimitry Andric /// expansion that is not the last template argument.
23910b57cec5SDimitry Andric static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
23920b57cec5SDimitry Andric   bool FoundPackExpansion = false;
23930b57cec5SDimitry Andric   for (const auto &A : Args) {
23940b57cec5SDimitry Andric     if (FoundPackExpansion)
23950b57cec5SDimitry Andric       return true;
23960b57cec5SDimitry Andric 
23970b57cec5SDimitry Andric     if (A.getKind() == TemplateArgument::Pack)
23980b57cec5SDimitry Andric       return hasPackExpansionBeforeEnd(A.pack_elements());
23990b57cec5SDimitry Andric 
24000b57cec5SDimitry Andric     // FIXME: If this is a fixed-arity pack expansion from an outer level of
24010b57cec5SDimitry Andric     // templates, it should not be treated as a pack expansion.
24020b57cec5SDimitry Andric     if (A.isPackExpansion())
24030b57cec5SDimitry Andric       FoundPackExpansion = true;
24040b57cec5SDimitry Andric   }
24050b57cec5SDimitry Andric 
24060b57cec5SDimitry Andric   return false;
24070b57cec5SDimitry Andric }
24080b57cec5SDimitry Andric 
24090b57cec5SDimitry Andric static Sema::TemplateDeductionResult
24100b57cec5SDimitry Andric DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
24110b57cec5SDimitry Andric                         ArrayRef<TemplateArgument> Params,
24120b57cec5SDimitry Andric                         ArrayRef<TemplateArgument> Args,
24130b57cec5SDimitry Andric                         TemplateDeductionInfo &Info,
24140b57cec5SDimitry Andric                         SmallVectorImpl<DeducedTemplateArgument> &Deduced,
24150b57cec5SDimitry Andric                         bool NumberOfArgumentsMustMatch) {
24160b57cec5SDimitry Andric   // C++0x [temp.deduct.type]p9:
24170b57cec5SDimitry Andric   //   If the template argument list of P contains a pack expansion that is not
24180b57cec5SDimitry Andric   //   the last template argument, the entire template argument list is a
24190b57cec5SDimitry Andric   //   non-deduced context.
24200b57cec5SDimitry Andric   if (hasPackExpansionBeforeEnd(Params))
24210b57cec5SDimitry Andric     return Sema::TDK_Success;
24220b57cec5SDimitry Andric 
24230b57cec5SDimitry Andric   // C++0x [temp.deduct.type]p9:
24240b57cec5SDimitry Andric   //   If P has a form that contains <T> or <i>, then each argument Pi of the
24250b57cec5SDimitry Andric   //   respective template argument list P is compared with the corresponding
24260b57cec5SDimitry Andric   //   argument Ai of the corresponding template argument list of A.
24270b57cec5SDimitry Andric   unsigned ArgIdx = 0, ParamIdx = 0;
24280b57cec5SDimitry Andric   for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) {
24290b57cec5SDimitry Andric     if (!Params[ParamIdx].isPackExpansion()) {
24300b57cec5SDimitry Andric       // The simple case: deduce template arguments by matching Pi and Ai.
24310b57cec5SDimitry Andric 
24320b57cec5SDimitry Andric       // Check whether we have enough arguments.
24330b57cec5SDimitry Andric       if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
24340b57cec5SDimitry Andric         return NumberOfArgumentsMustMatch
24350b57cec5SDimitry Andric                    ? Sema::TDK_MiscellaneousDeductionFailure
24360b57cec5SDimitry Andric                    : Sema::TDK_Success;
24370b57cec5SDimitry Andric 
24380b57cec5SDimitry Andric       // C++1z [temp.deduct.type]p9:
24390b57cec5SDimitry Andric       //   During partial ordering, if Ai was originally a pack expansion [and]
24400b57cec5SDimitry Andric       //   Pi is not a pack expansion, template argument deduction fails.
24410b57cec5SDimitry Andric       if (Args[ArgIdx].isPackExpansion())
24420b57cec5SDimitry Andric         return Sema::TDK_MiscellaneousDeductionFailure;
24430b57cec5SDimitry Andric 
24440b57cec5SDimitry Andric       // Perform deduction for this Pi/Ai pair.
24450b57cec5SDimitry Andric       if (Sema::TemplateDeductionResult Result
24460b57cec5SDimitry Andric             = DeduceTemplateArguments(S, TemplateParams,
24470b57cec5SDimitry Andric                                       Params[ParamIdx], Args[ArgIdx],
24480b57cec5SDimitry Andric                                       Info, Deduced))
24490b57cec5SDimitry Andric         return Result;
24500b57cec5SDimitry Andric 
24510b57cec5SDimitry Andric       // Move to the next argument.
24520b57cec5SDimitry Andric       ++ArgIdx;
24530b57cec5SDimitry Andric       continue;
24540b57cec5SDimitry Andric     }
24550b57cec5SDimitry Andric 
24560b57cec5SDimitry Andric     // The parameter is a pack expansion.
24570b57cec5SDimitry Andric 
24580b57cec5SDimitry Andric     // C++0x [temp.deduct.type]p9:
24590b57cec5SDimitry Andric     //   If Pi is a pack expansion, then the pattern of Pi is compared with
24600b57cec5SDimitry Andric     //   each remaining argument in the template argument list of A. Each
24610b57cec5SDimitry Andric     //   comparison deduces template arguments for subsequent positions in the
24620b57cec5SDimitry Andric     //   template parameter packs expanded by Pi.
24630b57cec5SDimitry Andric     TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
24640b57cec5SDimitry Andric 
24650b57cec5SDimitry Andric     // Prepare to deduce the packs within the pattern.
24660b57cec5SDimitry Andric     PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
24670b57cec5SDimitry Andric 
24680b57cec5SDimitry Andric     // Keep track of the deduced template arguments for each parameter pack
24690b57cec5SDimitry Andric     // expanded by this pack expansion (the outer index) and for each
24700b57cec5SDimitry Andric     // template argument (the inner SmallVectors).
24710b57cec5SDimitry Andric     for (; hasTemplateArgumentForDeduction(Args, ArgIdx) &&
24720b57cec5SDimitry Andric            PackScope.hasNextElement();
24730b57cec5SDimitry Andric          ++ArgIdx) {
24740b57cec5SDimitry Andric       // Deduce template arguments from the pattern.
24750b57cec5SDimitry Andric       if (Sema::TemplateDeductionResult Result
24760b57cec5SDimitry Andric             = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
24770b57cec5SDimitry Andric                                       Info, Deduced))
24780b57cec5SDimitry Andric         return Result;
24790b57cec5SDimitry Andric 
24800b57cec5SDimitry Andric       PackScope.nextPackElement();
24810b57cec5SDimitry Andric     }
24820b57cec5SDimitry Andric 
24830b57cec5SDimitry Andric     // Build argument packs for each of the parameter packs expanded by this
24840b57cec5SDimitry Andric     // pack expansion.
24850b57cec5SDimitry Andric     if (auto Result = PackScope.finish())
24860b57cec5SDimitry Andric       return Result;
24870b57cec5SDimitry Andric   }
24880b57cec5SDimitry Andric 
24890b57cec5SDimitry Andric   return Sema::TDK_Success;
24900b57cec5SDimitry Andric }
24910b57cec5SDimitry Andric 
24920b57cec5SDimitry Andric static Sema::TemplateDeductionResult
24930b57cec5SDimitry Andric DeduceTemplateArguments(Sema &S,
24940b57cec5SDimitry Andric                         TemplateParameterList *TemplateParams,
24950b57cec5SDimitry Andric                         const TemplateArgumentList &ParamList,
24960b57cec5SDimitry Andric                         const TemplateArgumentList &ArgList,
24970b57cec5SDimitry Andric                         TemplateDeductionInfo &Info,
24980b57cec5SDimitry Andric                         SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
24990b57cec5SDimitry Andric   return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
25000b57cec5SDimitry Andric                                  ArgList.asArray(), Info, Deduced,
25010b57cec5SDimitry Andric                                  /*NumberOfArgumentsMustMatch*/false);
25020b57cec5SDimitry Andric }
25030b57cec5SDimitry Andric 
25040b57cec5SDimitry Andric /// Determine whether two template arguments are the same.
25050b57cec5SDimitry Andric static bool isSameTemplateArg(ASTContext &Context,
25060b57cec5SDimitry Andric                               TemplateArgument X,
25070b57cec5SDimitry Andric                               const TemplateArgument &Y,
25080b57cec5SDimitry Andric                               bool PackExpansionMatchesPack = false) {
25090b57cec5SDimitry Andric   // If we're checking deduced arguments (X) against original arguments (Y),
25100b57cec5SDimitry Andric   // we will have flattened packs to non-expansions in X.
25110b57cec5SDimitry Andric   if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
25120b57cec5SDimitry Andric     X = X.getPackExpansionPattern();
25130b57cec5SDimitry Andric 
25140b57cec5SDimitry Andric   if (X.getKind() != Y.getKind())
25150b57cec5SDimitry Andric     return false;
25160b57cec5SDimitry Andric 
25170b57cec5SDimitry Andric   switch (X.getKind()) {
25180b57cec5SDimitry Andric     case TemplateArgument::Null:
25190b57cec5SDimitry Andric       llvm_unreachable("Comparing NULL template argument");
25200b57cec5SDimitry Andric 
25210b57cec5SDimitry Andric     case TemplateArgument::Type:
25220b57cec5SDimitry Andric       return Context.getCanonicalType(X.getAsType()) ==
25230b57cec5SDimitry Andric              Context.getCanonicalType(Y.getAsType());
25240b57cec5SDimitry Andric 
25250b57cec5SDimitry Andric     case TemplateArgument::Declaration:
25260b57cec5SDimitry Andric       return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
25270b57cec5SDimitry Andric 
25280b57cec5SDimitry Andric     case TemplateArgument::NullPtr:
25290b57cec5SDimitry Andric       return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
25300b57cec5SDimitry Andric 
25310b57cec5SDimitry Andric     case TemplateArgument::Template:
25320b57cec5SDimitry Andric     case TemplateArgument::TemplateExpansion:
25330b57cec5SDimitry Andric       return Context.getCanonicalTemplateName(
25340b57cec5SDimitry Andric                     X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
25350b57cec5SDimitry Andric              Context.getCanonicalTemplateName(
25360b57cec5SDimitry Andric                     Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
25370b57cec5SDimitry Andric 
25380b57cec5SDimitry Andric     case TemplateArgument::Integral:
25390b57cec5SDimitry Andric       return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
25400b57cec5SDimitry Andric 
25410b57cec5SDimitry Andric     case TemplateArgument::Expression: {
25420b57cec5SDimitry Andric       llvm::FoldingSetNodeID XID, YID;
25430b57cec5SDimitry Andric       X.getAsExpr()->Profile(XID, Context, true);
25440b57cec5SDimitry Andric       Y.getAsExpr()->Profile(YID, Context, true);
25450b57cec5SDimitry Andric       return XID == YID;
25460b57cec5SDimitry Andric     }
25470b57cec5SDimitry Andric 
25480b57cec5SDimitry Andric     case TemplateArgument::Pack:
25490b57cec5SDimitry Andric       if (X.pack_size() != Y.pack_size())
25500b57cec5SDimitry Andric         return false;
25510b57cec5SDimitry Andric 
25520b57cec5SDimitry Andric       for (TemplateArgument::pack_iterator XP = X.pack_begin(),
25530b57cec5SDimitry Andric                                         XPEnd = X.pack_end(),
25540b57cec5SDimitry Andric                                            YP = Y.pack_begin();
25550b57cec5SDimitry Andric            XP != XPEnd; ++XP, ++YP)
25560b57cec5SDimitry Andric         if (!isSameTemplateArg(Context, *XP, *YP, PackExpansionMatchesPack))
25570b57cec5SDimitry Andric           return false;
25580b57cec5SDimitry Andric 
25590b57cec5SDimitry Andric       return true;
25600b57cec5SDimitry Andric   }
25610b57cec5SDimitry Andric 
25620b57cec5SDimitry Andric   llvm_unreachable("Invalid TemplateArgument Kind!");
25630b57cec5SDimitry Andric }
25640b57cec5SDimitry Andric 
25650b57cec5SDimitry Andric /// Allocate a TemplateArgumentLoc where all locations have
25660b57cec5SDimitry Andric /// been initialized to the given location.
25670b57cec5SDimitry Andric ///
25680b57cec5SDimitry Andric /// \param Arg The template argument we are producing template argument
25690b57cec5SDimitry Andric /// location information for.
25700b57cec5SDimitry Andric ///
25710b57cec5SDimitry Andric /// \param NTTPType For a declaration template argument, the type of
25720b57cec5SDimitry Andric /// the non-type template parameter that corresponds to this template
25730b57cec5SDimitry Andric /// argument. Can be null if no type sugar is available to add to the
25740b57cec5SDimitry Andric /// type from the template argument.
25750b57cec5SDimitry Andric ///
25760b57cec5SDimitry Andric /// \param Loc The source location to use for the resulting template
25770b57cec5SDimitry Andric /// argument.
25780b57cec5SDimitry Andric TemplateArgumentLoc
25790b57cec5SDimitry Andric Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
25800b57cec5SDimitry Andric                                     QualType NTTPType, SourceLocation Loc) {
25810b57cec5SDimitry Andric   switch (Arg.getKind()) {
25820b57cec5SDimitry Andric   case TemplateArgument::Null:
25830b57cec5SDimitry Andric     llvm_unreachable("Can't get a NULL template argument here");
25840b57cec5SDimitry Andric 
25850b57cec5SDimitry Andric   case TemplateArgument::Type:
25860b57cec5SDimitry Andric     return TemplateArgumentLoc(
25870b57cec5SDimitry Andric         Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
25880b57cec5SDimitry Andric 
25890b57cec5SDimitry Andric   case TemplateArgument::Declaration: {
25900b57cec5SDimitry Andric     if (NTTPType.isNull())
25910b57cec5SDimitry Andric       NTTPType = Arg.getParamTypeForDecl();
25920b57cec5SDimitry Andric     Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
25930b57cec5SDimitry Andric                   .getAs<Expr>();
25940b57cec5SDimitry Andric     return TemplateArgumentLoc(TemplateArgument(E), E);
25950b57cec5SDimitry Andric   }
25960b57cec5SDimitry Andric 
25970b57cec5SDimitry Andric   case TemplateArgument::NullPtr: {
25980b57cec5SDimitry Andric     if (NTTPType.isNull())
25990b57cec5SDimitry Andric       NTTPType = Arg.getNullPtrType();
26000b57cec5SDimitry Andric     Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
26010b57cec5SDimitry Andric                   .getAs<Expr>();
26020b57cec5SDimitry Andric     return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
26030b57cec5SDimitry Andric                                E);
26040b57cec5SDimitry Andric   }
26050b57cec5SDimitry Andric 
26060b57cec5SDimitry Andric   case TemplateArgument::Integral: {
26070b57cec5SDimitry Andric     Expr *E =
26080b57cec5SDimitry Andric         BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
26090b57cec5SDimitry Andric     return TemplateArgumentLoc(TemplateArgument(E), E);
26100b57cec5SDimitry Andric   }
26110b57cec5SDimitry Andric 
26120b57cec5SDimitry Andric     case TemplateArgument::Template:
26130b57cec5SDimitry Andric     case TemplateArgument::TemplateExpansion: {
26140b57cec5SDimitry Andric       NestedNameSpecifierLocBuilder Builder;
261513138422SDimitry Andric       TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
26160b57cec5SDimitry Andric       if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
26170b57cec5SDimitry Andric         Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
26180b57cec5SDimitry Andric       else if (QualifiedTemplateName *QTN =
26190b57cec5SDimitry Andric                    Template.getAsQualifiedTemplateName())
26200b57cec5SDimitry Andric         Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
26210b57cec5SDimitry Andric 
26220b57cec5SDimitry Andric       if (Arg.getKind() == TemplateArgument::Template)
26230b57cec5SDimitry Andric         return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
26240b57cec5SDimitry Andric                                    Loc);
26250b57cec5SDimitry Andric 
26260b57cec5SDimitry Andric       return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
26270b57cec5SDimitry Andric                                  Loc, Loc);
26280b57cec5SDimitry Andric     }
26290b57cec5SDimitry Andric 
26300b57cec5SDimitry Andric   case TemplateArgument::Expression:
26310b57cec5SDimitry Andric     return TemplateArgumentLoc(Arg, Arg.getAsExpr());
26320b57cec5SDimitry Andric 
26330b57cec5SDimitry Andric   case TemplateArgument::Pack:
26340b57cec5SDimitry Andric     return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
26350b57cec5SDimitry Andric   }
26360b57cec5SDimitry Andric 
26370b57cec5SDimitry Andric   llvm_unreachable("Invalid TemplateArgument Kind!");
26380b57cec5SDimitry Andric }
26390b57cec5SDimitry Andric 
2640480093f4SDimitry Andric TemplateArgumentLoc
264113138422SDimitry Andric Sema::getIdentityTemplateArgumentLoc(NamedDecl *TemplateParm,
2642480093f4SDimitry Andric                                      SourceLocation Location) {
2643480093f4SDimitry Andric   return getTrivialTemplateArgumentLoc(
264413138422SDimitry Andric       Context.getInjectedTemplateArg(TemplateParm), QualType(), Location);
2645480093f4SDimitry Andric }
2646480093f4SDimitry Andric 
26470b57cec5SDimitry Andric /// Convert the given deduced template argument and add it to the set of
26480b57cec5SDimitry Andric /// fully-converted template arguments.
26490b57cec5SDimitry Andric static bool
26500b57cec5SDimitry Andric ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
26510b57cec5SDimitry Andric                                DeducedTemplateArgument Arg,
26520b57cec5SDimitry Andric                                NamedDecl *Template,
26530b57cec5SDimitry Andric                                TemplateDeductionInfo &Info,
26540b57cec5SDimitry Andric                                bool IsDeduced,
26550b57cec5SDimitry Andric                                SmallVectorImpl<TemplateArgument> &Output) {
26560b57cec5SDimitry Andric   auto ConvertArg = [&](DeducedTemplateArgument Arg,
26570b57cec5SDimitry Andric                         unsigned ArgumentPackIndex) {
26580b57cec5SDimitry Andric     // Convert the deduced template argument into a template
26590b57cec5SDimitry Andric     // argument that we can check, almost as if the user had written
26600b57cec5SDimitry Andric     // the template argument explicitly.
26610b57cec5SDimitry Andric     TemplateArgumentLoc ArgLoc =
26620b57cec5SDimitry Andric         S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
26630b57cec5SDimitry Andric 
26640b57cec5SDimitry Andric     // Check the template argument, converting it as necessary.
26650b57cec5SDimitry Andric     return S.CheckTemplateArgument(
26660b57cec5SDimitry Andric         Param, ArgLoc, Template, Template->getLocation(),
26670b57cec5SDimitry Andric         Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
26680b57cec5SDimitry Andric         IsDeduced
26690b57cec5SDimitry Andric             ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
26700b57cec5SDimitry Andric                                               : Sema::CTAK_Deduced)
26710b57cec5SDimitry Andric             : Sema::CTAK_Specified);
26720b57cec5SDimitry Andric   };
26730b57cec5SDimitry Andric 
26740b57cec5SDimitry Andric   if (Arg.getKind() == TemplateArgument::Pack) {
26750b57cec5SDimitry Andric     // This is a template argument pack, so check each of its arguments against
26760b57cec5SDimitry Andric     // the template parameter.
26770b57cec5SDimitry Andric     SmallVector<TemplateArgument, 2> PackedArgsBuilder;
26780b57cec5SDimitry Andric     for (const auto &P : Arg.pack_elements()) {
26790b57cec5SDimitry Andric       // When converting the deduced template argument, append it to the
26800b57cec5SDimitry Andric       // general output list. We need to do this so that the template argument
26810b57cec5SDimitry Andric       // checking logic has all of the prior template arguments available.
26820b57cec5SDimitry Andric       DeducedTemplateArgument InnerArg(P);
26830b57cec5SDimitry Andric       InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
26840b57cec5SDimitry Andric       assert(InnerArg.getKind() != TemplateArgument::Pack &&
26850b57cec5SDimitry Andric              "deduced nested pack");
26860b57cec5SDimitry Andric       if (P.isNull()) {
26870b57cec5SDimitry Andric         // We deduced arguments for some elements of this pack, but not for
26880b57cec5SDimitry Andric         // all of them. This happens if we get a conditionally-non-deduced
26890b57cec5SDimitry Andric         // context in a pack expansion (such as an overload set in one of the
26900b57cec5SDimitry Andric         // arguments).
26910b57cec5SDimitry Andric         S.Diag(Param->getLocation(),
26920b57cec5SDimitry Andric                diag::err_template_arg_deduced_incomplete_pack)
26930b57cec5SDimitry Andric           << Arg << Param;
26940b57cec5SDimitry Andric         return true;
26950b57cec5SDimitry Andric       }
26960b57cec5SDimitry Andric       if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
26970b57cec5SDimitry Andric         return true;
26980b57cec5SDimitry Andric 
26990b57cec5SDimitry Andric       // Move the converted template argument into our argument pack.
27000b57cec5SDimitry Andric       PackedArgsBuilder.push_back(Output.pop_back_val());
27010b57cec5SDimitry Andric     }
27020b57cec5SDimitry Andric 
27030b57cec5SDimitry Andric     // If the pack is empty, we still need to substitute into the parameter
27040b57cec5SDimitry Andric     // itself, in case that substitution fails.
27050b57cec5SDimitry Andric     if (PackedArgsBuilder.empty()) {
27060b57cec5SDimitry Andric       LocalInstantiationScope Scope(S);
27070b57cec5SDimitry Andric       TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
27080b57cec5SDimitry Andric       MultiLevelTemplateArgumentList Args(TemplateArgs);
27090b57cec5SDimitry Andric 
27100b57cec5SDimitry Andric       if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
27110b57cec5SDimitry Andric         Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
27120b57cec5SDimitry Andric                                          NTTP, Output,
27130b57cec5SDimitry Andric                                          Template->getSourceRange());
27140b57cec5SDimitry Andric         if (Inst.isInvalid() ||
27150b57cec5SDimitry Andric             S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
27160b57cec5SDimitry Andric                         NTTP->getDeclName()).isNull())
27170b57cec5SDimitry Andric           return true;
27180b57cec5SDimitry Andric       } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
27190b57cec5SDimitry Andric         Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
27200b57cec5SDimitry Andric                                          TTP, Output,
27210b57cec5SDimitry Andric                                          Template->getSourceRange());
27220b57cec5SDimitry Andric         if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
27230b57cec5SDimitry Andric           return true;
27240b57cec5SDimitry Andric       }
27250b57cec5SDimitry Andric       // For type parameters, no substitution is ever required.
27260b57cec5SDimitry Andric     }
27270b57cec5SDimitry Andric 
27280b57cec5SDimitry Andric     // Create the resulting argument pack.
27290b57cec5SDimitry Andric     Output.push_back(
27300b57cec5SDimitry Andric         TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
27310b57cec5SDimitry Andric     return false;
27320b57cec5SDimitry Andric   }
27330b57cec5SDimitry Andric 
27340b57cec5SDimitry Andric   return ConvertArg(Arg, 0);
27350b57cec5SDimitry Andric }
27360b57cec5SDimitry Andric 
27370b57cec5SDimitry Andric // FIXME: This should not be a template, but
27380b57cec5SDimitry Andric // ClassTemplatePartialSpecializationDecl sadly does not derive from
27390b57cec5SDimitry Andric // TemplateDecl.
27400b57cec5SDimitry Andric template<typename TemplateDeclT>
27410b57cec5SDimitry Andric static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
27420b57cec5SDimitry Andric     Sema &S, TemplateDeclT *Template, bool IsDeduced,
27430b57cec5SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
27440b57cec5SDimitry Andric     TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
27450b57cec5SDimitry Andric     LocalInstantiationScope *CurrentInstantiationScope = nullptr,
27460b57cec5SDimitry Andric     unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
27470b57cec5SDimitry Andric   TemplateParameterList *TemplateParams = Template->getTemplateParameters();
27480b57cec5SDimitry Andric 
27490b57cec5SDimitry Andric   for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
27500b57cec5SDimitry Andric     NamedDecl *Param = TemplateParams->getParam(I);
27510b57cec5SDimitry Andric 
27520b57cec5SDimitry Andric     // C++0x [temp.arg.explicit]p3:
27530b57cec5SDimitry Andric     //    A trailing template parameter pack (14.5.3) not otherwise deduced will
27540b57cec5SDimitry Andric     //    be deduced to an empty sequence of template arguments.
27550b57cec5SDimitry Andric     // FIXME: Where did the word "trailing" come from?
27560b57cec5SDimitry Andric     if (Deduced[I].isNull() && Param->isTemplateParameterPack()) {
2757480093f4SDimitry Andric       if (auto Result =
2758480093f4SDimitry Andric               PackDeductionScope(S, TemplateParams, Deduced, Info, I).finish())
27590b57cec5SDimitry Andric         return Result;
27600b57cec5SDimitry Andric     }
27610b57cec5SDimitry Andric 
27620b57cec5SDimitry Andric     if (!Deduced[I].isNull()) {
27630b57cec5SDimitry Andric       if (I < NumAlreadyConverted) {
27640b57cec5SDimitry Andric         // We may have had explicitly-specified template arguments for a
27650b57cec5SDimitry Andric         // template parameter pack (that may or may not have been extended
27660b57cec5SDimitry Andric         // via additional deduced arguments).
27670b57cec5SDimitry Andric         if (Param->isParameterPack() && CurrentInstantiationScope &&
27680b57cec5SDimitry Andric             CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
27690b57cec5SDimitry Andric           // Forget the partially-substituted pack; its substitution is now
27700b57cec5SDimitry Andric           // complete.
27710b57cec5SDimitry Andric           CurrentInstantiationScope->ResetPartiallySubstitutedPack();
27720b57cec5SDimitry Andric           // We still need to check the argument in case it was extended by
27730b57cec5SDimitry Andric           // deduction.
27740b57cec5SDimitry Andric         } else {
27750b57cec5SDimitry Andric           // We have already fully type-checked and converted this
27760b57cec5SDimitry Andric           // argument, because it was explicitly-specified. Just record the
27770b57cec5SDimitry Andric           // presence of this argument.
27780b57cec5SDimitry Andric           Builder.push_back(Deduced[I]);
27790b57cec5SDimitry Andric           continue;
27800b57cec5SDimitry Andric         }
27810b57cec5SDimitry Andric       }
27820b57cec5SDimitry Andric 
27830b57cec5SDimitry Andric       // We may have deduced this argument, so it still needs to be
27840b57cec5SDimitry Andric       // checked and converted.
27850b57cec5SDimitry Andric       if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
27860b57cec5SDimitry Andric                                          IsDeduced, Builder)) {
27870b57cec5SDimitry Andric         Info.Param = makeTemplateParameter(Param);
27880b57cec5SDimitry Andric         // FIXME: These template arguments are temporary. Free them!
27890b57cec5SDimitry Andric         Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
27900b57cec5SDimitry Andric         return Sema::TDK_SubstitutionFailure;
27910b57cec5SDimitry Andric       }
27920b57cec5SDimitry Andric 
27930b57cec5SDimitry Andric       continue;
27940b57cec5SDimitry Andric     }
27950b57cec5SDimitry Andric 
27960b57cec5SDimitry Andric     // Substitute into the default template argument, if available.
27970b57cec5SDimitry Andric     bool HasDefaultArg = false;
27980b57cec5SDimitry Andric     TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
27990b57cec5SDimitry Andric     if (!TD) {
28000b57cec5SDimitry Andric       assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
28010b57cec5SDimitry Andric              isa<VarTemplatePartialSpecializationDecl>(Template));
28020b57cec5SDimitry Andric       return Sema::TDK_Incomplete;
28030b57cec5SDimitry Andric     }
28040b57cec5SDimitry Andric 
28050b57cec5SDimitry Andric     TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
28060b57cec5SDimitry Andric         TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
28070b57cec5SDimitry Andric         HasDefaultArg);
28080b57cec5SDimitry Andric 
28090b57cec5SDimitry Andric     // If there was no default argument, deduction is incomplete.
28100b57cec5SDimitry Andric     if (DefArg.getArgument().isNull()) {
28110b57cec5SDimitry Andric       Info.Param = makeTemplateParameter(
28120b57cec5SDimitry Andric           const_cast<NamedDecl *>(TemplateParams->getParam(I)));
28130b57cec5SDimitry Andric       Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
28140b57cec5SDimitry Andric       if (PartialOverloading) break;
28150b57cec5SDimitry Andric 
28160b57cec5SDimitry Andric       return HasDefaultArg ? Sema::TDK_SubstitutionFailure
28170b57cec5SDimitry Andric                            : Sema::TDK_Incomplete;
28180b57cec5SDimitry Andric     }
28190b57cec5SDimitry Andric 
28200b57cec5SDimitry Andric     // Check whether we can actually use the default argument.
28210b57cec5SDimitry Andric     if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
28220b57cec5SDimitry Andric                                 TD->getSourceRange().getEnd(), 0, Builder,
28230b57cec5SDimitry Andric                                 Sema::CTAK_Specified)) {
28240b57cec5SDimitry Andric       Info.Param = makeTemplateParameter(
28250b57cec5SDimitry Andric                          const_cast<NamedDecl *>(TemplateParams->getParam(I)));
28260b57cec5SDimitry Andric       // FIXME: These template arguments are temporary. Free them!
28270b57cec5SDimitry Andric       Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
28280b57cec5SDimitry Andric       return Sema::TDK_SubstitutionFailure;
28290b57cec5SDimitry Andric     }
28300b57cec5SDimitry Andric 
28310b57cec5SDimitry Andric     // If we get here, we successfully used the default template argument.
28320b57cec5SDimitry Andric   }
28330b57cec5SDimitry Andric 
28340b57cec5SDimitry Andric   return Sema::TDK_Success;
28350b57cec5SDimitry Andric }
28360b57cec5SDimitry Andric 
28370b57cec5SDimitry Andric static DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
28380b57cec5SDimitry Andric   if (auto *DC = dyn_cast<DeclContext>(D))
28390b57cec5SDimitry Andric     return DC;
28400b57cec5SDimitry Andric   return D->getDeclContext();
28410b57cec5SDimitry Andric }
28420b57cec5SDimitry Andric 
28430b57cec5SDimitry Andric template<typename T> struct IsPartialSpecialization {
28440b57cec5SDimitry Andric   static constexpr bool value = false;
28450b57cec5SDimitry Andric };
28460b57cec5SDimitry Andric template<>
28470b57cec5SDimitry Andric struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
28480b57cec5SDimitry Andric   static constexpr bool value = true;
28490b57cec5SDimitry Andric };
28500b57cec5SDimitry Andric template<>
28510b57cec5SDimitry Andric struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
28520b57cec5SDimitry Andric   static constexpr bool value = true;
28530b57cec5SDimitry Andric };
28540b57cec5SDimitry Andric 
2855480093f4SDimitry Andric template<typename TemplateDeclT>
2856480093f4SDimitry Andric static Sema::TemplateDeductionResult
2857480093f4SDimitry Andric CheckDeducedArgumentConstraints(Sema& S, TemplateDeclT *Template,
2858480093f4SDimitry Andric                                 ArrayRef<TemplateArgument> DeducedArgs,
2859480093f4SDimitry Andric                                 TemplateDeductionInfo& Info) {
2860480093f4SDimitry Andric   llvm::SmallVector<const Expr *, 3> AssociatedConstraints;
2861480093f4SDimitry Andric   Template->getAssociatedConstraints(AssociatedConstraints);
2862480093f4SDimitry Andric   if (S.CheckConstraintSatisfaction(Template, AssociatedConstraints,
2863480093f4SDimitry Andric                                     DeducedArgs, Info.getLocation(),
2864480093f4SDimitry Andric                                     Info.AssociatedConstraintsSatisfaction) ||
2865480093f4SDimitry Andric       !Info.AssociatedConstraintsSatisfaction.IsSatisfied) {
2866480093f4SDimitry Andric     Info.reset(TemplateArgumentList::CreateCopy(S.Context, DeducedArgs));
2867480093f4SDimitry Andric     return Sema::TDK_ConstraintsNotSatisfied;
2868480093f4SDimitry Andric   }
2869480093f4SDimitry Andric   return Sema::TDK_Success;
2870480093f4SDimitry Andric }
2871480093f4SDimitry Andric 
28720b57cec5SDimitry Andric /// Complete template argument deduction for a partial specialization.
28730b57cec5SDimitry Andric template <typename T>
28745ffd83dbSDimitry Andric static std::enable_if_t<IsPartialSpecialization<T>::value,
28755ffd83dbSDimitry Andric                         Sema::TemplateDeductionResult>
28760b57cec5SDimitry Andric FinishTemplateArgumentDeduction(
28770b57cec5SDimitry Andric     Sema &S, T *Partial, bool IsPartialOrdering,
28780b57cec5SDimitry Andric     const TemplateArgumentList &TemplateArgs,
28790b57cec5SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
28800b57cec5SDimitry Andric     TemplateDeductionInfo &Info) {
28810b57cec5SDimitry Andric   // Unevaluated SFINAE context.
28820b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
28830b57cec5SDimitry Andric       S, Sema::ExpressionEvaluationContext::Unevaluated);
28840b57cec5SDimitry Andric   Sema::SFINAETrap Trap(S);
28850b57cec5SDimitry Andric 
28860b57cec5SDimitry Andric   Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
28870b57cec5SDimitry Andric 
28880b57cec5SDimitry Andric   // C++ [temp.deduct.type]p2:
28890b57cec5SDimitry Andric   //   [...] or if any template argument remains neither deduced nor
28900b57cec5SDimitry Andric   //   explicitly specified, template argument deduction fails.
28910b57cec5SDimitry Andric   SmallVector<TemplateArgument, 4> Builder;
28920b57cec5SDimitry Andric   if (auto Result = ConvertDeducedTemplateArguments(
28930b57cec5SDimitry Andric           S, Partial, IsPartialOrdering, Deduced, Info, Builder))
28940b57cec5SDimitry Andric     return Result;
28950b57cec5SDimitry Andric 
28960b57cec5SDimitry Andric   // Form the template argument list from the deduced template arguments.
28970b57cec5SDimitry Andric   TemplateArgumentList *DeducedArgumentList
28980b57cec5SDimitry Andric     = TemplateArgumentList::CreateCopy(S.Context, Builder);
28990b57cec5SDimitry Andric 
29000b57cec5SDimitry Andric   Info.reset(DeducedArgumentList);
29010b57cec5SDimitry Andric 
29020b57cec5SDimitry Andric   // Substitute the deduced template arguments into the template
29030b57cec5SDimitry Andric   // arguments of the class template partial specialization, and
29040b57cec5SDimitry Andric   // verify that the instantiated template arguments are both valid
29050b57cec5SDimitry Andric   // and are equivalent to the template arguments originally provided
29060b57cec5SDimitry Andric   // to the class template.
29070b57cec5SDimitry Andric   LocalInstantiationScope InstScope(S);
29080b57cec5SDimitry Andric   auto *Template = Partial->getSpecializedTemplate();
29090b57cec5SDimitry Andric   const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
29100b57cec5SDimitry Andric       Partial->getTemplateArgsAsWritten();
29110b57cec5SDimitry Andric   const TemplateArgumentLoc *PartialTemplateArgs =
29120b57cec5SDimitry Andric       PartialTemplArgInfo->getTemplateArgs();
29130b57cec5SDimitry Andric 
29140b57cec5SDimitry Andric   TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
29150b57cec5SDimitry Andric                                     PartialTemplArgInfo->RAngleLoc);
29160b57cec5SDimitry Andric 
29170b57cec5SDimitry Andric   if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
29180b57cec5SDimitry Andric               InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
29190b57cec5SDimitry Andric     unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
29200b57cec5SDimitry Andric     if (ParamIdx >= Partial->getTemplateParameters()->size())
29210b57cec5SDimitry Andric       ParamIdx = Partial->getTemplateParameters()->size() - 1;
29220b57cec5SDimitry Andric 
29230b57cec5SDimitry Andric     Decl *Param = const_cast<NamedDecl *>(
29240b57cec5SDimitry Andric         Partial->getTemplateParameters()->getParam(ParamIdx));
29250b57cec5SDimitry Andric     Info.Param = makeTemplateParameter(Param);
29260b57cec5SDimitry Andric     Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
29270b57cec5SDimitry Andric     return Sema::TDK_SubstitutionFailure;
29280b57cec5SDimitry Andric   }
29290b57cec5SDimitry Andric 
2930480093f4SDimitry Andric   bool ConstraintsNotSatisfied;
29310b57cec5SDimitry Andric   SmallVector<TemplateArgument, 4> ConvertedInstArgs;
29320b57cec5SDimitry Andric   if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2933480093f4SDimitry Andric                                   false, ConvertedInstArgs,
2934480093f4SDimitry Andric                                   /*UpdateArgsWithConversions=*/true,
2935480093f4SDimitry Andric                                   &ConstraintsNotSatisfied))
2936480093f4SDimitry Andric     return ConstraintsNotSatisfied ? Sema::TDK_ConstraintsNotSatisfied :
2937480093f4SDimitry Andric                                      Sema::TDK_SubstitutionFailure;
29380b57cec5SDimitry Andric 
29390b57cec5SDimitry Andric   TemplateParameterList *TemplateParams = Template->getTemplateParameters();
29400b57cec5SDimitry Andric   for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
29410b57cec5SDimitry Andric     TemplateArgument InstArg = ConvertedInstArgs.data()[I];
29420b57cec5SDimitry Andric     if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
29430b57cec5SDimitry Andric       Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
29440b57cec5SDimitry Andric       Info.FirstArg = TemplateArgs[I];
29450b57cec5SDimitry Andric       Info.SecondArg = InstArg;
29460b57cec5SDimitry Andric       return Sema::TDK_NonDeducedMismatch;
29470b57cec5SDimitry Andric     }
29480b57cec5SDimitry Andric   }
29490b57cec5SDimitry Andric 
29500b57cec5SDimitry Andric   if (Trap.hasErrorOccurred())
29510b57cec5SDimitry Andric     return Sema::TDK_SubstitutionFailure;
29520b57cec5SDimitry Andric 
2953480093f4SDimitry Andric   if (auto Result = CheckDeducedArgumentConstraints(S, Partial, Builder, Info))
2954480093f4SDimitry Andric     return Result;
2955480093f4SDimitry Andric 
29560b57cec5SDimitry Andric   return Sema::TDK_Success;
29570b57cec5SDimitry Andric }
29580b57cec5SDimitry Andric 
29590b57cec5SDimitry Andric /// Complete template argument deduction for a class or variable template,
29600b57cec5SDimitry Andric /// when partial ordering against a partial specialization.
29610b57cec5SDimitry Andric // FIXME: Factor out duplication with partial specialization version above.
29620b57cec5SDimitry Andric static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
29630b57cec5SDimitry Andric     Sema &S, TemplateDecl *Template, bool PartialOrdering,
29640b57cec5SDimitry Andric     const TemplateArgumentList &TemplateArgs,
29650b57cec5SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
29660b57cec5SDimitry Andric     TemplateDeductionInfo &Info) {
29670b57cec5SDimitry Andric   // Unevaluated SFINAE context.
29680b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
29690b57cec5SDimitry Andric       S, Sema::ExpressionEvaluationContext::Unevaluated);
29700b57cec5SDimitry Andric   Sema::SFINAETrap Trap(S);
29710b57cec5SDimitry Andric 
29720b57cec5SDimitry Andric   Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
29730b57cec5SDimitry Andric 
29740b57cec5SDimitry Andric   // C++ [temp.deduct.type]p2:
29750b57cec5SDimitry Andric   //   [...] or if any template argument remains neither deduced nor
29760b57cec5SDimitry Andric   //   explicitly specified, template argument deduction fails.
29770b57cec5SDimitry Andric   SmallVector<TemplateArgument, 4> Builder;
29780b57cec5SDimitry Andric   if (auto Result = ConvertDeducedTemplateArguments(
29790b57cec5SDimitry Andric           S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder))
29800b57cec5SDimitry Andric     return Result;
29810b57cec5SDimitry Andric 
29820b57cec5SDimitry Andric   // Check that we produced the correct argument list.
29830b57cec5SDimitry Andric   TemplateParameterList *TemplateParams = Template->getTemplateParameters();
29840b57cec5SDimitry Andric   for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
29850b57cec5SDimitry Andric     TemplateArgument InstArg = Builder[I];
29860b57cec5SDimitry Andric     if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
29870b57cec5SDimitry Andric                            /*PackExpansionMatchesPack*/true)) {
29880b57cec5SDimitry Andric       Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
29890b57cec5SDimitry Andric       Info.FirstArg = TemplateArgs[I];
29900b57cec5SDimitry Andric       Info.SecondArg = InstArg;
29910b57cec5SDimitry Andric       return Sema::TDK_NonDeducedMismatch;
29920b57cec5SDimitry Andric     }
29930b57cec5SDimitry Andric   }
29940b57cec5SDimitry Andric 
29950b57cec5SDimitry Andric   if (Trap.hasErrorOccurred())
29960b57cec5SDimitry Andric     return Sema::TDK_SubstitutionFailure;
29970b57cec5SDimitry Andric 
2998480093f4SDimitry Andric   if (auto Result = CheckDeducedArgumentConstraints(S, Template, Builder,
2999480093f4SDimitry Andric                                                     Info))
3000480093f4SDimitry Andric     return Result;
3001480093f4SDimitry Andric 
30020b57cec5SDimitry Andric   return Sema::TDK_Success;
30030b57cec5SDimitry Andric }
30040b57cec5SDimitry Andric 
30050b57cec5SDimitry Andric /// Perform template argument deduction to determine whether
30060b57cec5SDimitry Andric /// the given template arguments match the given class template
30070b57cec5SDimitry Andric /// partial specialization per C++ [temp.class.spec.match].
30080b57cec5SDimitry Andric Sema::TemplateDeductionResult
30090b57cec5SDimitry Andric Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
30100b57cec5SDimitry Andric                               const TemplateArgumentList &TemplateArgs,
30110b57cec5SDimitry Andric                               TemplateDeductionInfo &Info) {
30120b57cec5SDimitry Andric   if (Partial->isInvalidDecl())
30130b57cec5SDimitry Andric     return TDK_Invalid;
30140b57cec5SDimitry Andric 
30150b57cec5SDimitry Andric   // C++ [temp.class.spec.match]p2:
30160b57cec5SDimitry Andric   //   A partial specialization matches a given actual template
30170b57cec5SDimitry Andric   //   argument list if the template arguments of the partial
30180b57cec5SDimitry Andric   //   specialization can be deduced from the actual template argument
30190b57cec5SDimitry Andric   //   list (14.8.2).
30200b57cec5SDimitry Andric 
30210b57cec5SDimitry Andric   // Unevaluated SFINAE context.
30220b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
30230b57cec5SDimitry Andric       *this, Sema::ExpressionEvaluationContext::Unevaluated);
30240b57cec5SDimitry Andric   SFINAETrap Trap(*this);
30250b57cec5SDimitry Andric 
30260b57cec5SDimitry Andric   SmallVector<DeducedTemplateArgument, 4> Deduced;
30270b57cec5SDimitry Andric   Deduced.resize(Partial->getTemplateParameters()->size());
30280b57cec5SDimitry Andric   if (TemplateDeductionResult Result
30290b57cec5SDimitry Andric         = ::DeduceTemplateArguments(*this,
30300b57cec5SDimitry Andric                                     Partial->getTemplateParameters(),
30310b57cec5SDimitry Andric                                     Partial->getTemplateArgs(),
30320b57cec5SDimitry Andric                                     TemplateArgs, Info, Deduced))
30330b57cec5SDimitry Andric     return Result;
30340b57cec5SDimitry Andric 
30350b57cec5SDimitry Andric   SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
30360b57cec5SDimitry Andric   InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
30370b57cec5SDimitry Andric                              Info);
30380b57cec5SDimitry Andric   if (Inst.isInvalid())
30390b57cec5SDimitry Andric     return TDK_InstantiationDepth;
30400b57cec5SDimitry Andric 
30410b57cec5SDimitry Andric   if (Trap.hasErrorOccurred())
30420b57cec5SDimitry Andric     return Sema::TDK_SubstitutionFailure;
30430b57cec5SDimitry Andric 
30445ffd83dbSDimitry Andric   TemplateDeductionResult Result;
30455ffd83dbSDimitry Andric   runWithSufficientStackSpace(Info.getLocation(), [&] {
30465ffd83dbSDimitry Andric     Result = ::FinishTemplateArgumentDeduction(*this, Partial,
30475ffd83dbSDimitry Andric                                                /*IsPartialOrdering=*/false,
30485ffd83dbSDimitry Andric                                                TemplateArgs, Deduced, Info);
30495ffd83dbSDimitry Andric   });
30505ffd83dbSDimitry Andric   return Result;
30510b57cec5SDimitry Andric }
30520b57cec5SDimitry Andric 
30530b57cec5SDimitry Andric /// Perform template argument deduction to determine whether
30540b57cec5SDimitry Andric /// the given template arguments match the given variable template
30550b57cec5SDimitry Andric /// partial specialization per C++ [temp.class.spec.match].
30560b57cec5SDimitry Andric Sema::TemplateDeductionResult
30570b57cec5SDimitry Andric Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
30580b57cec5SDimitry Andric                               const TemplateArgumentList &TemplateArgs,
30590b57cec5SDimitry Andric                               TemplateDeductionInfo &Info) {
30600b57cec5SDimitry Andric   if (Partial->isInvalidDecl())
30610b57cec5SDimitry Andric     return TDK_Invalid;
30620b57cec5SDimitry Andric 
30630b57cec5SDimitry Andric   // C++ [temp.class.spec.match]p2:
30640b57cec5SDimitry Andric   //   A partial specialization matches a given actual template
30650b57cec5SDimitry Andric   //   argument list if the template arguments of the partial
30660b57cec5SDimitry Andric   //   specialization can be deduced from the actual template argument
30670b57cec5SDimitry Andric   //   list (14.8.2).
30680b57cec5SDimitry Andric 
30690b57cec5SDimitry Andric   // Unevaluated SFINAE context.
30700b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
30710b57cec5SDimitry Andric       *this, Sema::ExpressionEvaluationContext::Unevaluated);
30720b57cec5SDimitry Andric   SFINAETrap Trap(*this);
30730b57cec5SDimitry Andric 
30740b57cec5SDimitry Andric   SmallVector<DeducedTemplateArgument, 4> Deduced;
30750b57cec5SDimitry Andric   Deduced.resize(Partial->getTemplateParameters()->size());
30760b57cec5SDimitry Andric   if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
30770b57cec5SDimitry Andric           *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
30780b57cec5SDimitry Andric           TemplateArgs, Info, Deduced))
30790b57cec5SDimitry Andric     return Result;
30800b57cec5SDimitry Andric 
30810b57cec5SDimitry Andric   SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
30820b57cec5SDimitry Andric   InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
30830b57cec5SDimitry Andric                              Info);
30840b57cec5SDimitry Andric   if (Inst.isInvalid())
30850b57cec5SDimitry Andric     return TDK_InstantiationDepth;
30860b57cec5SDimitry Andric 
30870b57cec5SDimitry Andric   if (Trap.hasErrorOccurred())
30880b57cec5SDimitry Andric     return Sema::TDK_SubstitutionFailure;
30890b57cec5SDimitry Andric 
30905ffd83dbSDimitry Andric   TemplateDeductionResult Result;
30915ffd83dbSDimitry Andric   runWithSufficientStackSpace(Info.getLocation(), [&] {
30925ffd83dbSDimitry Andric     Result = ::FinishTemplateArgumentDeduction(*this, Partial,
30935ffd83dbSDimitry Andric                                                /*IsPartialOrdering=*/false,
30945ffd83dbSDimitry Andric                                                TemplateArgs, Deduced, Info);
30955ffd83dbSDimitry Andric   });
30965ffd83dbSDimitry Andric   return Result;
30970b57cec5SDimitry Andric }
30980b57cec5SDimitry Andric 
30990b57cec5SDimitry Andric /// Determine whether the given type T is a simple-template-id type.
31000b57cec5SDimitry Andric static bool isSimpleTemplateIdType(QualType T) {
31010b57cec5SDimitry Andric   if (const TemplateSpecializationType *Spec
31020b57cec5SDimitry Andric         = T->getAs<TemplateSpecializationType>())
31030b57cec5SDimitry Andric     return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
31040b57cec5SDimitry Andric 
31050b57cec5SDimitry Andric   // C++17 [temp.local]p2:
31060b57cec5SDimitry Andric   //   the injected-class-name [...] is equivalent to the template-name followed
31070b57cec5SDimitry Andric   //   by the template-arguments of the class template specialization or partial
31080b57cec5SDimitry Andric   //   specialization enclosed in <>
31090b57cec5SDimitry Andric   // ... which means it's equivalent to a simple-template-id.
31100b57cec5SDimitry Andric   //
31110b57cec5SDimitry Andric   // This only arises during class template argument deduction for a copy
31120b57cec5SDimitry Andric   // deduction candidate, where it permits slicing.
31130b57cec5SDimitry Andric   if (T->getAs<InjectedClassNameType>())
31140b57cec5SDimitry Andric     return true;
31150b57cec5SDimitry Andric 
31160b57cec5SDimitry Andric   return false;
31170b57cec5SDimitry Andric }
31180b57cec5SDimitry Andric 
31190b57cec5SDimitry Andric /// Substitute the explicitly-provided template arguments into the
31200b57cec5SDimitry Andric /// given function template according to C++ [temp.arg.explicit].
31210b57cec5SDimitry Andric ///
31220b57cec5SDimitry Andric /// \param FunctionTemplate the function template into which the explicit
31230b57cec5SDimitry Andric /// template arguments will be substituted.
31240b57cec5SDimitry Andric ///
31250b57cec5SDimitry Andric /// \param ExplicitTemplateArgs the explicitly-specified template
31260b57cec5SDimitry Andric /// arguments.
31270b57cec5SDimitry Andric ///
31280b57cec5SDimitry Andric /// \param Deduced the deduced template arguments, which will be populated
31290b57cec5SDimitry Andric /// with the converted and checked explicit template arguments.
31300b57cec5SDimitry Andric ///
31310b57cec5SDimitry Andric /// \param ParamTypes will be populated with the instantiated function
31320b57cec5SDimitry Andric /// parameters.
31330b57cec5SDimitry Andric ///
31340b57cec5SDimitry Andric /// \param FunctionType if non-NULL, the result type of the function template
31350b57cec5SDimitry Andric /// will also be instantiated and the pointed-to value will be updated with
31360b57cec5SDimitry Andric /// the instantiated function type.
31370b57cec5SDimitry Andric ///
31380b57cec5SDimitry Andric /// \param Info if substitution fails for any reason, this object will be
31390b57cec5SDimitry Andric /// populated with more information about the failure.
31400b57cec5SDimitry Andric ///
31410b57cec5SDimitry Andric /// \returns TDK_Success if substitution was successful, or some failure
31420b57cec5SDimitry Andric /// condition.
31430b57cec5SDimitry Andric Sema::TemplateDeductionResult
31440b57cec5SDimitry Andric Sema::SubstituteExplicitTemplateArguments(
31450b57cec5SDimitry Andric                                       FunctionTemplateDecl *FunctionTemplate,
31460b57cec5SDimitry Andric                                TemplateArgumentListInfo &ExplicitTemplateArgs,
31470b57cec5SDimitry Andric                        SmallVectorImpl<DeducedTemplateArgument> &Deduced,
31480b57cec5SDimitry Andric                                  SmallVectorImpl<QualType> &ParamTypes,
31490b57cec5SDimitry Andric                                           QualType *FunctionType,
31500b57cec5SDimitry Andric                                           TemplateDeductionInfo &Info) {
31510b57cec5SDimitry Andric   FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
31520b57cec5SDimitry Andric   TemplateParameterList *TemplateParams
31530b57cec5SDimitry Andric     = FunctionTemplate->getTemplateParameters();
31540b57cec5SDimitry Andric 
31550b57cec5SDimitry Andric   if (ExplicitTemplateArgs.size() == 0) {
31560b57cec5SDimitry Andric     // No arguments to substitute; just copy over the parameter types and
31570b57cec5SDimitry Andric     // fill in the function type.
31580b57cec5SDimitry Andric     for (auto P : Function->parameters())
31590b57cec5SDimitry Andric       ParamTypes.push_back(P->getType());
31600b57cec5SDimitry Andric 
31610b57cec5SDimitry Andric     if (FunctionType)
31620b57cec5SDimitry Andric       *FunctionType = Function->getType();
31630b57cec5SDimitry Andric     return TDK_Success;
31640b57cec5SDimitry Andric   }
31650b57cec5SDimitry Andric 
31660b57cec5SDimitry Andric   // Unevaluated SFINAE context.
31670b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
31680b57cec5SDimitry Andric       *this, Sema::ExpressionEvaluationContext::Unevaluated);
31690b57cec5SDimitry Andric   SFINAETrap Trap(*this);
31700b57cec5SDimitry Andric 
31710b57cec5SDimitry Andric   // C++ [temp.arg.explicit]p3:
31720b57cec5SDimitry Andric   //   Template arguments that are present shall be specified in the
31730b57cec5SDimitry Andric   //   declaration order of their corresponding template-parameters. The
31740b57cec5SDimitry Andric   //   template argument list shall not specify more template-arguments than
31750b57cec5SDimitry Andric   //   there are corresponding template-parameters.
31760b57cec5SDimitry Andric   SmallVector<TemplateArgument, 4> Builder;
31770b57cec5SDimitry Andric 
31780b57cec5SDimitry Andric   // Enter a new template instantiation context where we check the
31790b57cec5SDimitry Andric   // explicitly-specified template arguments against this function template,
31800b57cec5SDimitry Andric   // and then substitute them into the function parameter types.
31810b57cec5SDimitry Andric   SmallVector<TemplateArgument, 4> DeducedArgs;
31820b57cec5SDimitry Andric   InstantiatingTemplate Inst(
31830b57cec5SDimitry Andric       *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
31840b57cec5SDimitry Andric       CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
31850b57cec5SDimitry Andric   if (Inst.isInvalid())
31860b57cec5SDimitry Andric     return TDK_InstantiationDepth;
31870b57cec5SDimitry Andric 
31880b57cec5SDimitry Andric   if (CheckTemplateArgumentList(FunctionTemplate, SourceLocation(),
31890b57cec5SDimitry Andric                                 ExplicitTemplateArgs, true, Builder, false) ||
31900b57cec5SDimitry Andric       Trap.hasErrorOccurred()) {
31910b57cec5SDimitry Andric     unsigned Index = Builder.size();
31920b57cec5SDimitry Andric     if (Index >= TemplateParams->size())
31930b57cec5SDimitry Andric       return TDK_SubstitutionFailure;
31940b57cec5SDimitry Andric     Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
31950b57cec5SDimitry Andric     return TDK_InvalidExplicitArguments;
31960b57cec5SDimitry Andric   }
31970b57cec5SDimitry Andric 
31980b57cec5SDimitry Andric   // Form the template argument list from the explicitly-specified
31990b57cec5SDimitry Andric   // template arguments.
32000b57cec5SDimitry Andric   TemplateArgumentList *ExplicitArgumentList
32010b57cec5SDimitry Andric     = TemplateArgumentList::CreateCopy(Context, Builder);
32020b57cec5SDimitry Andric   Info.setExplicitArgs(ExplicitArgumentList);
32030b57cec5SDimitry Andric 
32040b57cec5SDimitry Andric   // Template argument deduction and the final substitution should be
32050b57cec5SDimitry Andric   // done in the context of the templated declaration.  Explicit
32060b57cec5SDimitry Andric   // argument substitution, on the other hand, needs to happen in the
32070b57cec5SDimitry Andric   // calling context.
32080b57cec5SDimitry Andric   ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
32090b57cec5SDimitry Andric 
32100b57cec5SDimitry Andric   // If we deduced template arguments for a template parameter pack,
32110b57cec5SDimitry Andric   // note that the template argument pack is partially substituted and record
32120b57cec5SDimitry Andric   // the explicit template arguments. They'll be used as part of deduction
32130b57cec5SDimitry Andric   // for this template parameter pack.
32140b57cec5SDimitry Andric   unsigned PartiallySubstitutedPackIndex = -1u;
32150b57cec5SDimitry Andric   if (!Builder.empty()) {
32160b57cec5SDimitry Andric     const TemplateArgument &Arg = Builder.back();
32170b57cec5SDimitry Andric     if (Arg.getKind() == TemplateArgument::Pack) {
32180b57cec5SDimitry Andric       auto *Param = TemplateParams->getParam(Builder.size() - 1);
32190b57cec5SDimitry Andric       // If this is a fully-saturated fixed-size pack, it should be
32200b57cec5SDimitry Andric       // fully-substituted, not partially-substituted.
32210b57cec5SDimitry Andric       Optional<unsigned> Expansions = getExpandedPackSize(Param);
32220b57cec5SDimitry Andric       if (!Expansions || Arg.pack_size() < *Expansions) {
32230b57cec5SDimitry Andric         PartiallySubstitutedPackIndex = Builder.size() - 1;
32240b57cec5SDimitry Andric         CurrentInstantiationScope->SetPartiallySubstitutedPack(
32250b57cec5SDimitry Andric             Param, Arg.pack_begin(), Arg.pack_size());
32260b57cec5SDimitry Andric       }
32270b57cec5SDimitry Andric     }
32280b57cec5SDimitry Andric   }
32290b57cec5SDimitry Andric 
32300b57cec5SDimitry Andric   const FunctionProtoType *Proto
32310b57cec5SDimitry Andric     = Function->getType()->getAs<FunctionProtoType>();
32320b57cec5SDimitry Andric   assert(Proto && "Function template does not have a prototype?");
32330b57cec5SDimitry Andric 
32340b57cec5SDimitry Andric   // Isolate our substituted parameters from our caller.
32350b57cec5SDimitry Andric   LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
32360b57cec5SDimitry Andric 
32370b57cec5SDimitry Andric   ExtParameterInfoBuilder ExtParamInfos;
32380b57cec5SDimitry Andric 
32390b57cec5SDimitry Andric   // Instantiate the types of each of the function parameters given the
32400b57cec5SDimitry Andric   // explicitly-specified template arguments. If the function has a trailing
32410b57cec5SDimitry Andric   // return type, substitute it after the arguments to ensure we substitute
32420b57cec5SDimitry Andric   // in lexical order.
32430b57cec5SDimitry Andric   if (Proto->hasTrailingReturn()) {
32440b57cec5SDimitry Andric     if (SubstParmTypes(Function->getLocation(), Function->parameters(),
32450b57cec5SDimitry Andric                        Proto->getExtParameterInfosOrNull(),
32460b57cec5SDimitry Andric                        MultiLevelTemplateArgumentList(*ExplicitArgumentList),
32470b57cec5SDimitry Andric                        ParamTypes, /*params*/ nullptr, ExtParamInfos))
32480b57cec5SDimitry Andric       return TDK_SubstitutionFailure;
32490b57cec5SDimitry Andric   }
32500b57cec5SDimitry Andric 
32510b57cec5SDimitry Andric   // Instantiate the return type.
32520b57cec5SDimitry Andric   QualType ResultType;
32530b57cec5SDimitry Andric   {
32540b57cec5SDimitry Andric     // C++11 [expr.prim.general]p3:
32550b57cec5SDimitry Andric     //   If a declaration declares a member function or member function
32560b57cec5SDimitry Andric     //   template of a class X, the expression this is a prvalue of type
32570b57cec5SDimitry Andric     //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
32580b57cec5SDimitry Andric     //   and the end of the function-definition, member-declarator, or
32590b57cec5SDimitry Andric     //   declarator.
32600b57cec5SDimitry Andric     Qualifiers ThisTypeQuals;
32610b57cec5SDimitry Andric     CXXRecordDecl *ThisContext = nullptr;
32620b57cec5SDimitry Andric     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
32630b57cec5SDimitry Andric       ThisContext = Method->getParent();
32640b57cec5SDimitry Andric       ThisTypeQuals = Method->getMethodQualifiers();
32650b57cec5SDimitry Andric     }
32660b57cec5SDimitry Andric 
32670b57cec5SDimitry Andric     CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
32680b57cec5SDimitry Andric                                getLangOpts().CPlusPlus11);
32690b57cec5SDimitry Andric 
32700b57cec5SDimitry Andric     ResultType =
32710b57cec5SDimitry Andric         SubstType(Proto->getReturnType(),
32720b57cec5SDimitry Andric                   MultiLevelTemplateArgumentList(*ExplicitArgumentList),
32730b57cec5SDimitry Andric                   Function->getTypeSpecStartLoc(), Function->getDeclName());
32740b57cec5SDimitry Andric     if (ResultType.isNull() || Trap.hasErrorOccurred())
32750b57cec5SDimitry Andric       return TDK_SubstitutionFailure;
3276a7dea167SDimitry Andric     // CUDA: Kernel function must have 'void' return type.
3277a7dea167SDimitry Andric     if (getLangOpts().CUDA)
3278a7dea167SDimitry Andric       if (Function->hasAttr<CUDAGlobalAttr>() && !ResultType->isVoidType()) {
3279a7dea167SDimitry Andric         Diag(Function->getLocation(), diag::err_kern_type_not_void_return)
3280a7dea167SDimitry Andric             << Function->getType() << Function->getSourceRange();
3281a7dea167SDimitry Andric         return TDK_SubstitutionFailure;
3282a7dea167SDimitry Andric       }
32830b57cec5SDimitry Andric   }
32840b57cec5SDimitry Andric 
32850b57cec5SDimitry Andric   // Instantiate the types of each of the function parameters given the
32860b57cec5SDimitry Andric   // explicitly-specified template arguments if we didn't do so earlier.
32870b57cec5SDimitry Andric   if (!Proto->hasTrailingReturn() &&
32880b57cec5SDimitry Andric       SubstParmTypes(Function->getLocation(), Function->parameters(),
32890b57cec5SDimitry Andric                      Proto->getExtParameterInfosOrNull(),
32900b57cec5SDimitry Andric                      MultiLevelTemplateArgumentList(*ExplicitArgumentList),
32910b57cec5SDimitry Andric                      ParamTypes, /*params*/ nullptr, ExtParamInfos))
32920b57cec5SDimitry Andric     return TDK_SubstitutionFailure;
32930b57cec5SDimitry Andric 
32940b57cec5SDimitry Andric   if (FunctionType) {
32950b57cec5SDimitry Andric     auto EPI = Proto->getExtProtoInfo();
32960b57cec5SDimitry Andric     EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
32970b57cec5SDimitry Andric 
32980b57cec5SDimitry Andric     // In C++1z onwards, exception specifications are part of the function type,
32990b57cec5SDimitry Andric     // so substitution into the type must also substitute into the exception
33000b57cec5SDimitry Andric     // specification.
33010b57cec5SDimitry Andric     SmallVector<QualType, 4> ExceptionStorage;
33020b57cec5SDimitry Andric     if (getLangOpts().CPlusPlus17 &&
33030b57cec5SDimitry Andric         SubstExceptionSpec(
33040b57cec5SDimitry Andric             Function->getLocation(), EPI.ExceptionSpec, ExceptionStorage,
33050b57cec5SDimitry Andric             MultiLevelTemplateArgumentList(*ExplicitArgumentList)))
33060b57cec5SDimitry Andric       return TDK_SubstitutionFailure;
33070b57cec5SDimitry Andric 
33080b57cec5SDimitry Andric     *FunctionType = BuildFunctionType(ResultType, ParamTypes,
33090b57cec5SDimitry Andric                                       Function->getLocation(),
33100b57cec5SDimitry Andric                                       Function->getDeclName(),
33110b57cec5SDimitry Andric                                       EPI);
33120b57cec5SDimitry Andric     if (FunctionType->isNull() || Trap.hasErrorOccurred())
33130b57cec5SDimitry Andric       return TDK_SubstitutionFailure;
33140b57cec5SDimitry Andric   }
33150b57cec5SDimitry Andric 
33160b57cec5SDimitry Andric   // C++ [temp.arg.explicit]p2:
33170b57cec5SDimitry Andric   //   Trailing template arguments that can be deduced (14.8.2) may be
33180b57cec5SDimitry Andric   //   omitted from the list of explicit template-arguments. If all of the
33190b57cec5SDimitry Andric   //   template arguments can be deduced, they may all be omitted; in this
33200b57cec5SDimitry Andric   //   case, the empty template argument list <> itself may also be omitted.
33210b57cec5SDimitry Andric   //
33220b57cec5SDimitry Andric   // Take all of the explicitly-specified arguments and put them into
33230b57cec5SDimitry Andric   // the set of deduced template arguments. The partially-substituted
33240b57cec5SDimitry Andric   // parameter pack, however, will be set to NULL since the deduction
33250b57cec5SDimitry Andric   // mechanism handles the partially-substituted argument pack directly.
33260b57cec5SDimitry Andric   Deduced.reserve(TemplateParams->size());
33270b57cec5SDimitry Andric   for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
33280b57cec5SDimitry Andric     const TemplateArgument &Arg = ExplicitArgumentList->get(I);
33290b57cec5SDimitry Andric     if (I == PartiallySubstitutedPackIndex)
33300b57cec5SDimitry Andric       Deduced.push_back(DeducedTemplateArgument());
33310b57cec5SDimitry Andric     else
33320b57cec5SDimitry Andric       Deduced.push_back(Arg);
33330b57cec5SDimitry Andric   }
33340b57cec5SDimitry Andric 
33350b57cec5SDimitry Andric   return TDK_Success;
33360b57cec5SDimitry Andric }
33370b57cec5SDimitry Andric 
33380b57cec5SDimitry Andric /// Check whether the deduced argument type for a call to a function
33390b57cec5SDimitry Andric /// template matches the actual argument type per C++ [temp.deduct.call]p4.
33400b57cec5SDimitry Andric static Sema::TemplateDeductionResult
33410b57cec5SDimitry Andric CheckOriginalCallArgDeduction(Sema &S, TemplateDeductionInfo &Info,
33420b57cec5SDimitry Andric                               Sema::OriginalCallArg OriginalArg,
33430b57cec5SDimitry Andric                               QualType DeducedA) {
33440b57cec5SDimitry Andric   ASTContext &Context = S.Context;
33450b57cec5SDimitry Andric 
33460b57cec5SDimitry Andric   auto Failed = [&]() -> Sema::TemplateDeductionResult {
33470b57cec5SDimitry Andric     Info.FirstArg = TemplateArgument(DeducedA);
33480b57cec5SDimitry Andric     Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
33490b57cec5SDimitry Andric     Info.CallArgIndex = OriginalArg.ArgIdx;
33500b57cec5SDimitry Andric     return OriginalArg.DecomposedParam ? Sema::TDK_DeducedMismatchNested
33510b57cec5SDimitry Andric                                        : Sema::TDK_DeducedMismatch;
33520b57cec5SDimitry Andric   };
33530b57cec5SDimitry Andric 
33540b57cec5SDimitry Andric   QualType A = OriginalArg.OriginalArgType;
33550b57cec5SDimitry Andric   QualType OriginalParamType = OriginalArg.OriginalParamType;
33560b57cec5SDimitry Andric 
33570b57cec5SDimitry Andric   // Check for type equality (top-level cv-qualifiers are ignored).
33580b57cec5SDimitry Andric   if (Context.hasSameUnqualifiedType(A, DeducedA))
33590b57cec5SDimitry Andric     return Sema::TDK_Success;
33600b57cec5SDimitry Andric 
33610b57cec5SDimitry Andric   // Strip off references on the argument types; they aren't needed for
33620b57cec5SDimitry Andric   // the following checks.
33630b57cec5SDimitry Andric   if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
33640b57cec5SDimitry Andric     DeducedA = DeducedARef->getPointeeType();
33650b57cec5SDimitry Andric   if (const ReferenceType *ARef = A->getAs<ReferenceType>())
33660b57cec5SDimitry Andric     A = ARef->getPointeeType();
33670b57cec5SDimitry Andric 
33680b57cec5SDimitry Andric   // C++ [temp.deduct.call]p4:
33690b57cec5SDimitry Andric   //   [...] However, there are three cases that allow a difference:
33700b57cec5SDimitry Andric   //     - If the original P is a reference type, the deduced A (i.e., the
33710b57cec5SDimitry Andric   //       type referred to by the reference) can be more cv-qualified than
33720b57cec5SDimitry Andric   //       the transformed A.
33730b57cec5SDimitry Andric   if (const ReferenceType *OriginalParamRef
33740b57cec5SDimitry Andric       = OriginalParamType->getAs<ReferenceType>()) {
33750b57cec5SDimitry Andric     // We don't want to keep the reference around any more.
33760b57cec5SDimitry Andric     OriginalParamType = OriginalParamRef->getPointeeType();
33770b57cec5SDimitry Andric 
33780b57cec5SDimitry Andric     // FIXME: Resolve core issue (no number yet): if the original P is a
33790b57cec5SDimitry Andric     // reference type and the transformed A is function type "noexcept F",
33800b57cec5SDimitry Andric     // the deduced A can be F.
33810b57cec5SDimitry Andric     QualType Tmp;
33820b57cec5SDimitry Andric     if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
33830b57cec5SDimitry Andric       return Sema::TDK_Success;
33840b57cec5SDimitry Andric 
33850b57cec5SDimitry Andric     Qualifiers AQuals = A.getQualifiers();
33860b57cec5SDimitry Andric     Qualifiers DeducedAQuals = DeducedA.getQualifiers();
33870b57cec5SDimitry Andric 
33880b57cec5SDimitry Andric     // Under Objective-C++ ARC, the deduced type may have implicitly
33890b57cec5SDimitry Andric     // been given strong or (when dealing with a const reference)
33900b57cec5SDimitry Andric     // unsafe_unretained lifetime. If so, update the original
33910b57cec5SDimitry Andric     // qualifiers to include this lifetime.
33920b57cec5SDimitry Andric     if (S.getLangOpts().ObjCAutoRefCount &&
33930b57cec5SDimitry Andric         ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
33940b57cec5SDimitry Andric           AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
33950b57cec5SDimitry Andric          (DeducedAQuals.hasConst() &&
33960b57cec5SDimitry Andric           DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
33970b57cec5SDimitry Andric       AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
33980b57cec5SDimitry Andric     }
33990b57cec5SDimitry Andric 
34000b57cec5SDimitry Andric     if (AQuals == DeducedAQuals) {
34010b57cec5SDimitry Andric       // Qualifiers match; there's nothing to do.
34020b57cec5SDimitry Andric     } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
34030b57cec5SDimitry Andric       return Failed();
34040b57cec5SDimitry Andric     } else {
34050b57cec5SDimitry Andric       // Qualifiers are compatible, so have the argument type adopt the
34060b57cec5SDimitry Andric       // deduced argument type's qualifiers as if we had performed the
34070b57cec5SDimitry Andric       // qualification conversion.
34080b57cec5SDimitry Andric       A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
34090b57cec5SDimitry Andric     }
34100b57cec5SDimitry Andric   }
34110b57cec5SDimitry Andric 
34120b57cec5SDimitry Andric   //    - The transformed A can be another pointer or pointer to member
34130b57cec5SDimitry Andric   //      type that can be converted to the deduced A via a function pointer
34140b57cec5SDimitry Andric   //      conversion and/or a qualification conversion.
34150b57cec5SDimitry Andric   //
34160b57cec5SDimitry Andric   // Also allow conversions which merely strip __attribute__((noreturn)) from
34170b57cec5SDimitry Andric   // function types (recursively).
34180b57cec5SDimitry Andric   bool ObjCLifetimeConversion = false;
34190b57cec5SDimitry Andric   QualType ResultTy;
34200b57cec5SDimitry Andric   if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
34210b57cec5SDimitry Andric       (S.IsQualificationConversion(A, DeducedA, false,
34220b57cec5SDimitry Andric                                    ObjCLifetimeConversion) ||
34230b57cec5SDimitry Andric        S.IsFunctionConversion(A, DeducedA, ResultTy)))
34240b57cec5SDimitry Andric     return Sema::TDK_Success;
34250b57cec5SDimitry Andric 
34260b57cec5SDimitry Andric   //    - If P is a class and P has the form simple-template-id, then the
34270b57cec5SDimitry Andric   //      transformed A can be a derived class of the deduced A. [...]
34280b57cec5SDimitry Andric   //     [...] Likewise, if P is a pointer to a class of the form
34290b57cec5SDimitry Andric   //      simple-template-id, the transformed A can be a pointer to a
34300b57cec5SDimitry Andric   //      derived class pointed to by the deduced A.
34310b57cec5SDimitry Andric   if (const PointerType *OriginalParamPtr
34320b57cec5SDimitry Andric       = OriginalParamType->getAs<PointerType>()) {
34330b57cec5SDimitry Andric     if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
34340b57cec5SDimitry Andric       if (const PointerType *APtr = A->getAs<PointerType>()) {
34350b57cec5SDimitry Andric         if (A->getPointeeType()->isRecordType()) {
34360b57cec5SDimitry Andric           OriginalParamType = OriginalParamPtr->getPointeeType();
34370b57cec5SDimitry Andric           DeducedA = DeducedAPtr->getPointeeType();
34380b57cec5SDimitry Andric           A = APtr->getPointeeType();
34390b57cec5SDimitry Andric         }
34400b57cec5SDimitry Andric       }
34410b57cec5SDimitry Andric     }
34420b57cec5SDimitry Andric   }
34430b57cec5SDimitry Andric 
34440b57cec5SDimitry Andric   if (Context.hasSameUnqualifiedType(A, DeducedA))
34450b57cec5SDimitry Andric     return Sema::TDK_Success;
34460b57cec5SDimitry Andric 
34470b57cec5SDimitry Andric   if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
34480b57cec5SDimitry Andric       S.IsDerivedFrom(Info.getLocation(), A, DeducedA))
34490b57cec5SDimitry Andric     return Sema::TDK_Success;
34500b57cec5SDimitry Andric 
34510b57cec5SDimitry Andric   return Failed();
34520b57cec5SDimitry Andric }
34530b57cec5SDimitry Andric 
34540b57cec5SDimitry Andric /// Find the pack index for a particular parameter index in an instantiation of
34550b57cec5SDimitry Andric /// a function template with specific arguments.
34560b57cec5SDimitry Andric ///
34570b57cec5SDimitry Andric /// \return The pack index for whichever pack produced this parameter, or -1
34580b57cec5SDimitry Andric ///         if this was not produced by a parameter. Intended to be used as the
34590b57cec5SDimitry Andric ///         ArgumentPackSubstitutionIndex for further substitutions.
34600b57cec5SDimitry Andric // FIXME: We should track this in OriginalCallArgs so we don't need to
34610b57cec5SDimitry Andric // reconstruct it here.
34620b57cec5SDimitry Andric static unsigned getPackIndexForParam(Sema &S,
34630b57cec5SDimitry Andric                                      FunctionTemplateDecl *FunctionTemplate,
34640b57cec5SDimitry Andric                                      const MultiLevelTemplateArgumentList &Args,
34650b57cec5SDimitry Andric                                      unsigned ParamIdx) {
34660b57cec5SDimitry Andric   unsigned Idx = 0;
34670b57cec5SDimitry Andric   for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
34680b57cec5SDimitry Andric     if (PD->isParameterPack()) {
34690b57cec5SDimitry Andric       unsigned NumExpansions =
34700b57cec5SDimitry Andric           S.getNumArgumentsInExpansion(PD->getType(), Args).getValueOr(1);
34710b57cec5SDimitry Andric       if (Idx + NumExpansions > ParamIdx)
34720b57cec5SDimitry Andric         return ParamIdx - Idx;
34730b57cec5SDimitry Andric       Idx += NumExpansions;
34740b57cec5SDimitry Andric     } else {
34750b57cec5SDimitry Andric       if (Idx == ParamIdx)
34760b57cec5SDimitry Andric         return -1; // Not a pack expansion
34770b57cec5SDimitry Andric       ++Idx;
34780b57cec5SDimitry Andric     }
34790b57cec5SDimitry Andric   }
34800b57cec5SDimitry Andric 
34810b57cec5SDimitry Andric   llvm_unreachable("parameter index would not be produced from template");
34820b57cec5SDimitry Andric }
34830b57cec5SDimitry Andric 
34840b57cec5SDimitry Andric /// Finish template argument deduction for a function template,
34850b57cec5SDimitry Andric /// checking the deduced template arguments for completeness and forming
34860b57cec5SDimitry Andric /// the function template specialization.
34870b57cec5SDimitry Andric ///
34880b57cec5SDimitry Andric /// \param OriginalCallArgs If non-NULL, the original call arguments against
34890b57cec5SDimitry Andric /// which the deduced argument types should be compared.
34900b57cec5SDimitry Andric Sema::TemplateDeductionResult Sema::FinishTemplateArgumentDeduction(
34910b57cec5SDimitry Andric     FunctionTemplateDecl *FunctionTemplate,
34920b57cec5SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
34930b57cec5SDimitry Andric     unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
34940b57cec5SDimitry Andric     TemplateDeductionInfo &Info,
34950b57cec5SDimitry Andric     SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
34960b57cec5SDimitry Andric     bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
34970b57cec5SDimitry Andric   // Unevaluated SFINAE context.
34980b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
34990b57cec5SDimitry Andric       *this, Sema::ExpressionEvaluationContext::Unevaluated);
35000b57cec5SDimitry Andric   SFINAETrap Trap(*this);
35010b57cec5SDimitry Andric 
35020b57cec5SDimitry Andric   // Enter a new template instantiation context while we instantiate the
35030b57cec5SDimitry Andric   // actual function declaration.
35040b57cec5SDimitry Andric   SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
35050b57cec5SDimitry Andric   InstantiatingTemplate Inst(
35060b57cec5SDimitry Andric       *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
35070b57cec5SDimitry Andric       CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info);
35080b57cec5SDimitry Andric   if (Inst.isInvalid())
35090b57cec5SDimitry Andric     return TDK_InstantiationDepth;
35100b57cec5SDimitry Andric 
35110b57cec5SDimitry Andric   ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
35120b57cec5SDimitry Andric 
35130b57cec5SDimitry Andric   // C++ [temp.deduct.type]p2:
35140b57cec5SDimitry Andric   //   [...] or if any template argument remains neither deduced nor
35150b57cec5SDimitry Andric   //   explicitly specified, template argument deduction fails.
35160b57cec5SDimitry Andric   SmallVector<TemplateArgument, 4> Builder;
35170b57cec5SDimitry Andric   if (auto Result = ConvertDeducedTemplateArguments(
35180b57cec5SDimitry Andric           *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder,
35190b57cec5SDimitry Andric           CurrentInstantiationScope, NumExplicitlySpecified,
35200b57cec5SDimitry Andric           PartialOverloading))
35210b57cec5SDimitry Andric     return Result;
35220b57cec5SDimitry Andric 
35230b57cec5SDimitry Andric   // C++ [temp.deduct.call]p10: [DR1391]
35240b57cec5SDimitry Andric   //   If deduction succeeds for all parameters that contain
35250b57cec5SDimitry Andric   //   template-parameters that participate in template argument deduction,
35260b57cec5SDimitry Andric   //   and all template arguments are explicitly specified, deduced, or
35270b57cec5SDimitry Andric   //   obtained from default template arguments, remaining parameters are then
35280b57cec5SDimitry Andric   //   compared with the corresponding arguments. For each remaining parameter
35290b57cec5SDimitry Andric   //   P with a type that was non-dependent before substitution of any
35300b57cec5SDimitry Andric   //   explicitly-specified template arguments, if the corresponding argument
35310b57cec5SDimitry Andric   //   A cannot be implicitly converted to P, deduction fails.
35320b57cec5SDimitry Andric   if (CheckNonDependent())
35330b57cec5SDimitry Andric     return TDK_NonDependentConversionFailure;
35340b57cec5SDimitry Andric 
35350b57cec5SDimitry Andric   // Form the template argument list from the deduced template arguments.
35360b57cec5SDimitry Andric   TemplateArgumentList *DeducedArgumentList
35370b57cec5SDimitry Andric     = TemplateArgumentList::CreateCopy(Context, Builder);
35380b57cec5SDimitry Andric   Info.reset(DeducedArgumentList);
35390b57cec5SDimitry Andric 
35400b57cec5SDimitry Andric   // Substitute the deduced template arguments into the function template
35410b57cec5SDimitry Andric   // declaration to produce the function template specialization.
35420b57cec5SDimitry Andric   DeclContext *Owner = FunctionTemplate->getDeclContext();
35430b57cec5SDimitry Andric   if (FunctionTemplate->getFriendObjectKind())
35440b57cec5SDimitry Andric     Owner = FunctionTemplate->getLexicalDeclContext();
35450b57cec5SDimitry Andric   MultiLevelTemplateArgumentList SubstArgs(*DeducedArgumentList);
35460b57cec5SDimitry Andric   Specialization = cast_or_null<FunctionDecl>(
35470b57cec5SDimitry Andric       SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, SubstArgs));
35480b57cec5SDimitry Andric   if (!Specialization || Specialization->isInvalidDecl())
35490b57cec5SDimitry Andric     return TDK_SubstitutionFailure;
35500b57cec5SDimitry Andric 
35510b57cec5SDimitry Andric   assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
35520b57cec5SDimitry Andric          FunctionTemplate->getCanonicalDecl());
35530b57cec5SDimitry Andric 
35540b57cec5SDimitry Andric   // If the template argument list is owned by the function template
35550b57cec5SDimitry Andric   // specialization, release it.
35560b57cec5SDimitry Andric   if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
35570b57cec5SDimitry Andric       !Trap.hasErrorOccurred())
35580b57cec5SDimitry Andric     Info.take();
35590b57cec5SDimitry Andric 
35600b57cec5SDimitry Andric   // There may have been an error that did not prevent us from constructing a
35610b57cec5SDimitry Andric   // declaration. Mark the declaration invalid and return with a substitution
35620b57cec5SDimitry Andric   // failure.
35630b57cec5SDimitry Andric   if (Trap.hasErrorOccurred()) {
35640b57cec5SDimitry Andric     Specialization->setInvalidDecl(true);
35650b57cec5SDimitry Andric     return TDK_SubstitutionFailure;
35660b57cec5SDimitry Andric   }
35670b57cec5SDimitry Andric 
3568480093f4SDimitry Andric   // C++2a [temp.deduct]p5
3569480093f4SDimitry Andric   //   [...] When all template arguments have been deduced [...] all uses of
3570480093f4SDimitry Andric   //   template parameters [...] are replaced with the corresponding deduced
3571480093f4SDimitry Andric   //   or default argument values.
3572480093f4SDimitry Andric   //   [...] If the function template has associated constraints
3573480093f4SDimitry Andric   //   ([temp.constr.decl]), those constraints are checked for satisfaction
3574480093f4SDimitry Andric   //   ([temp.constr.constr]). If the constraints are not satisfied, type
3575480093f4SDimitry Andric   //   deduction fails.
357613138422SDimitry Andric   if (!PartialOverloading ||
357713138422SDimitry Andric       (Builder.size() == FunctionTemplate->getTemplateParameters()->size())) {
3578480093f4SDimitry Andric     if (CheckInstantiatedFunctionTemplateConstraints(Info.getLocation(),
3579480093f4SDimitry Andric             Specialization, Builder, Info.AssociatedConstraintsSatisfaction))
3580480093f4SDimitry Andric       return TDK_MiscellaneousDeductionFailure;
3581480093f4SDimitry Andric 
3582480093f4SDimitry Andric     if (!Info.AssociatedConstraintsSatisfaction.IsSatisfied) {
3583480093f4SDimitry Andric       Info.reset(TemplateArgumentList::CreateCopy(Context, Builder));
3584480093f4SDimitry Andric       return TDK_ConstraintsNotSatisfied;
3585480093f4SDimitry Andric     }
358613138422SDimitry Andric   }
3587480093f4SDimitry Andric 
35880b57cec5SDimitry Andric   if (OriginalCallArgs) {
35890b57cec5SDimitry Andric     // C++ [temp.deduct.call]p4:
35900b57cec5SDimitry Andric     //   In general, the deduction process attempts to find template argument
35910b57cec5SDimitry Andric     //   values that will make the deduced A identical to A (after the type A
35920b57cec5SDimitry Andric     //   is transformed as described above). [...]
35930b57cec5SDimitry Andric     llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
35940b57cec5SDimitry Andric     for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
35950b57cec5SDimitry Andric       OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
35960b57cec5SDimitry Andric 
35970b57cec5SDimitry Andric       auto ParamIdx = OriginalArg.ArgIdx;
35980b57cec5SDimitry Andric       if (ParamIdx >= Specialization->getNumParams())
35990b57cec5SDimitry Andric         // FIXME: This presumably means a pack ended up smaller than we
36000b57cec5SDimitry Andric         // expected while deducing. Should this not result in deduction
36010b57cec5SDimitry Andric         // failure? Can it even happen?
36020b57cec5SDimitry Andric         continue;
36030b57cec5SDimitry Andric 
36040b57cec5SDimitry Andric       QualType DeducedA;
36050b57cec5SDimitry Andric       if (!OriginalArg.DecomposedParam) {
36060b57cec5SDimitry Andric         // P is one of the function parameters, just look up its substituted
36070b57cec5SDimitry Andric         // type.
36080b57cec5SDimitry Andric         DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
36090b57cec5SDimitry Andric       } else {
36100b57cec5SDimitry Andric         // P is a decomposed element of a parameter corresponding to a
36110b57cec5SDimitry Andric         // braced-init-list argument. Substitute back into P to find the
36120b57cec5SDimitry Andric         // deduced A.
36130b57cec5SDimitry Andric         QualType &CacheEntry =
36140b57cec5SDimitry Andric             DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
36150b57cec5SDimitry Andric         if (CacheEntry.isNull()) {
36160b57cec5SDimitry Andric           ArgumentPackSubstitutionIndexRAII PackIndex(
36170b57cec5SDimitry Andric               *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
36180b57cec5SDimitry Andric                                           ParamIdx));
36190b57cec5SDimitry Andric           CacheEntry =
36200b57cec5SDimitry Andric               SubstType(OriginalArg.OriginalParamType, SubstArgs,
36210b57cec5SDimitry Andric                         Specialization->getTypeSpecStartLoc(),
36220b57cec5SDimitry Andric                         Specialization->getDeclName());
36230b57cec5SDimitry Andric         }
36240b57cec5SDimitry Andric         DeducedA = CacheEntry;
36250b57cec5SDimitry Andric       }
36260b57cec5SDimitry Andric 
36270b57cec5SDimitry Andric       if (auto TDK =
36280b57cec5SDimitry Andric               CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA))
36290b57cec5SDimitry Andric         return TDK;
36300b57cec5SDimitry Andric     }
36310b57cec5SDimitry Andric   }
36320b57cec5SDimitry Andric 
36330b57cec5SDimitry Andric   // If we suppressed any diagnostics while performing template argument
36340b57cec5SDimitry Andric   // deduction, and if we haven't already instantiated this declaration,
36350b57cec5SDimitry Andric   // keep track of these diagnostics. They'll be emitted if this specialization
36360b57cec5SDimitry Andric   // is actually used.
36370b57cec5SDimitry Andric   if (Info.diag_begin() != Info.diag_end()) {
36380b57cec5SDimitry Andric     SuppressedDiagnosticsMap::iterator
36390b57cec5SDimitry Andric       Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
36400b57cec5SDimitry Andric     if (Pos == SuppressedDiagnostics.end())
36410b57cec5SDimitry Andric         SuppressedDiagnostics[Specialization->getCanonicalDecl()]
36420b57cec5SDimitry Andric           .append(Info.diag_begin(), Info.diag_end());
36430b57cec5SDimitry Andric   }
36440b57cec5SDimitry Andric 
36450b57cec5SDimitry Andric   return TDK_Success;
36460b57cec5SDimitry Andric }
36470b57cec5SDimitry Andric 
36480b57cec5SDimitry Andric /// Gets the type of a function for template-argument-deducton
36490b57cec5SDimitry Andric /// purposes when it's considered as part of an overload set.
36500b57cec5SDimitry Andric static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
36510b57cec5SDimitry Andric                                   FunctionDecl *Fn) {
36520b57cec5SDimitry Andric   // We may need to deduce the return type of the function now.
36530b57cec5SDimitry Andric   if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
36540b57cec5SDimitry Andric       S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
36550b57cec5SDimitry Andric     return {};
36560b57cec5SDimitry Andric 
36570b57cec5SDimitry Andric   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
36580b57cec5SDimitry Andric     if (Method->isInstance()) {
36590b57cec5SDimitry Andric       // An instance method that's referenced in a form that doesn't
36600b57cec5SDimitry Andric       // look like a member pointer is just invalid.
36610b57cec5SDimitry Andric       if (!R.HasFormOfMemberPointer)
36620b57cec5SDimitry Andric         return {};
36630b57cec5SDimitry Andric 
36640b57cec5SDimitry Andric       return S.Context.getMemberPointerType(Fn->getType(),
36650b57cec5SDimitry Andric                S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
36660b57cec5SDimitry Andric     }
36670b57cec5SDimitry Andric 
36680b57cec5SDimitry Andric   if (!R.IsAddressOfOperand) return Fn->getType();
36690b57cec5SDimitry Andric   return S.Context.getPointerType(Fn->getType());
36700b57cec5SDimitry Andric }
36710b57cec5SDimitry Andric 
36720b57cec5SDimitry Andric /// Apply the deduction rules for overload sets.
36730b57cec5SDimitry Andric ///
36740b57cec5SDimitry Andric /// \return the null type if this argument should be treated as an
36750b57cec5SDimitry Andric /// undeduced context
36760b57cec5SDimitry Andric static QualType
36770b57cec5SDimitry Andric ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
36780b57cec5SDimitry Andric                             Expr *Arg, QualType ParamType,
36790b57cec5SDimitry Andric                             bool ParamWasReference) {
36800b57cec5SDimitry Andric 
36810b57cec5SDimitry Andric   OverloadExpr::FindResult R = OverloadExpr::find(Arg);
36820b57cec5SDimitry Andric 
36830b57cec5SDimitry Andric   OverloadExpr *Ovl = R.Expression;
36840b57cec5SDimitry Andric 
36850b57cec5SDimitry Andric   // C++0x [temp.deduct.call]p4
36860b57cec5SDimitry Andric   unsigned TDF = 0;
36870b57cec5SDimitry Andric   if (ParamWasReference)
36880b57cec5SDimitry Andric     TDF |= TDF_ParamWithReferenceType;
36890b57cec5SDimitry Andric   if (R.IsAddressOfOperand)
36900b57cec5SDimitry Andric     TDF |= TDF_IgnoreQualifiers;
36910b57cec5SDimitry Andric 
36920b57cec5SDimitry Andric   // C++0x [temp.deduct.call]p6:
36930b57cec5SDimitry Andric   //   When P is a function type, pointer to function type, or pointer
36940b57cec5SDimitry Andric   //   to member function type:
36950b57cec5SDimitry Andric 
36960b57cec5SDimitry Andric   if (!ParamType->isFunctionType() &&
36970b57cec5SDimitry Andric       !ParamType->isFunctionPointerType() &&
36980b57cec5SDimitry Andric       !ParamType->isMemberFunctionPointerType()) {
36990b57cec5SDimitry Andric     if (Ovl->hasExplicitTemplateArgs()) {
37000b57cec5SDimitry Andric       // But we can still look for an explicit specialization.
37010b57cec5SDimitry Andric       if (FunctionDecl *ExplicitSpec
37020b57cec5SDimitry Andric             = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
37030b57cec5SDimitry Andric         return GetTypeOfFunction(S, R, ExplicitSpec);
37040b57cec5SDimitry Andric     }
37050b57cec5SDimitry Andric 
37060b57cec5SDimitry Andric     DeclAccessPair DAP;
37070b57cec5SDimitry Andric     if (FunctionDecl *Viable =
3708480093f4SDimitry Andric             S.resolveAddressOfSingleOverloadCandidate(Arg, DAP))
37090b57cec5SDimitry Andric       return GetTypeOfFunction(S, R, Viable);
37100b57cec5SDimitry Andric 
37110b57cec5SDimitry Andric     return {};
37120b57cec5SDimitry Andric   }
37130b57cec5SDimitry Andric 
37140b57cec5SDimitry Andric   // Gather the explicit template arguments, if any.
37150b57cec5SDimitry Andric   TemplateArgumentListInfo ExplicitTemplateArgs;
37160b57cec5SDimitry Andric   if (Ovl->hasExplicitTemplateArgs())
37170b57cec5SDimitry Andric     Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
37180b57cec5SDimitry Andric   QualType Match;
37190b57cec5SDimitry Andric   for (UnresolvedSetIterator I = Ovl->decls_begin(),
37200b57cec5SDimitry Andric          E = Ovl->decls_end(); I != E; ++I) {
37210b57cec5SDimitry Andric     NamedDecl *D = (*I)->getUnderlyingDecl();
37220b57cec5SDimitry Andric 
37230b57cec5SDimitry Andric     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
37240b57cec5SDimitry Andric       //   - If the argument is an overload set containing one or more
37250b57cec5SDimitry Andric       //     function templates, the parameter is treated as a
37260b57cec5SDimitry Andric       //     non-deduced context.
37270b57cec5SDimitry Andric       if (!Ovl->hasExplicitTemplateArgs())
37280b57cec5SDimitry Andric         return {};
37290b57cec5SDimitry Andric 
37300b57cec5SDimitry Andric       // Otherwise, see if we can resolve a function type
37310b57cec5SDimitry Andric       FunctionDecl *Specialization = nullptr;
37320b57cec5SDimitry Andric       TemplateDeductionInfo Info(Ovl->getNameLoc());
37330b57cec5SDimitry Andric       if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
37340b57cec5SDimitry Andric                                     Specialization, Info))
37350b57cec5SDimitry Andric         continue;
37360b57cec5SDimitry Andric 
37370b57cec5SDimitry Andric       D = Specialization;
37380b57cec5SDimitry Andric     }
37390b57cec5SDimitry Andric 
37400b57cec5SDimitry Andric     FunctionDecl *Fn = cast<FunctionDecl>(D);
37410b57cec5SDimitry Andric     QualType ArgType = GetTypeOfFunction(S, R, Fn);
37420b57cec5SDimitry Andric     if (ArgType.isNull()) continue;
37430b57cec5SDimitry Andric 
37440b57cec5SDimitry Andric     // Function-to-pointer conversion.
37450b57cec5SDimitry Andric     if (!ParamWasReference && ParamType->isPointerType() &&
37460b57cec5SDimitry Andric         ArgType->isFunctionType())
37470b57cec5SDimitry Andric       ArgType = S.Context.getPointerType(ArgType);
37480b57cec5SDimitry Andric 
37490b57cec5SDimitry Andric     //   - If the argument is an overload set (not containing function
37500b57cec5SDimitry Andric     //     templates), trial argument deduction is attempted using each
37510b57cec5SDimitry Andric     //     of the members of the set. If deduction succeeds for only one
37520b57cec5SDimitry Andric     //     of the overload set members, that member is used as the
37530b57cec5SDimitry Andric     //     argument value for the deduction. If deduction succeeds for
37540b57cec5SDimitry Andric     //     more than one member of the overload set the parameter is
37550b57cec5SDimitry Andric     //     treated as a non-deduced context.
37560b57cec5SDimitry Andric 
37570b57cec5SDimitry Andric     // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
37580b57cec5SDimitry Andric     //   Type deduction is done independently for each P/A pair, and
37590b57cec5SDimitry Andric     //   the deduced template argument values are then combined.
37600b57cec5SDimitry Andric     // So we do not reject deductions which were made elsewhere.
37610b57cec5SDimitry Andric     SmallVector<DeducedTemplateArgument, 8>
37620b57cec5SDimitry Andric       Deduced(TemplateParams->size());
37630b57cec5SDimitry Andric     TemplateDeductionInfo Info(Ovl->getNameLoc());
37640b57cec5SDimitry Andric     Sema::TemplateDeductionResult Result
37650b57cec5SDimitry Andric       = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
37660b57cec5SDimitry Andric                                            ArgType, Info, Deduced, TDF);
37670b57cec5SDimitry Andric     if (Result) continue;
37680b57cec5SDimitry Andric     if (!Match.isNull())
37690b57cec5SDimitry Andric       return {};
37700b57cec5SDimitry Andric     Match = ArgType;
37710b57cec5SDimitry Andric   }
37720b57cec5SDimitry Andric 
37730b57cec5SDimitry Andric   return Match;
37740b57cec5SDimitry Andric }
37750b57cec5SDimitry Andric 
37760b57cec5SDimitry Andric /// Perform the adjustments to the parameter and argument types
37770b57cec5SDimitry Andric /// described in C++ [temp.deduct.call].
37780b57cec5SDimitry Andric ///
37790b57cec5SDimitry Andric /// \returns true if the caller should not attempt to perform any template
37800b57cec5SDimitry Andric /// argument deduction based on this P/A pair because the argument is an
37810b57cec5SDimitry Andric /// overloaded function set that could not be resolved.
37820b57cec5SDimitry Andric static bool AdjustFunctionParmAndArgTypesForDeduction(
37830b57cec5SDimitry Andric     Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
37840b57cec5SDimitry Andric     QualType &ParamType, QualType &ArgType, Expr *Arg, unsigned &TDF) {
37850b57cec5SDimitry Andric   // C++0x [temp.deduct.call]p3:
37860b57cec5SDimitry Andric   //   If P is a cv-qualified type, the top level cv-qualifiers of P's type
37870b57cec5SDimitry Andric   //   are ignored for type deduction.
37880b57cec5SDimitry Andric   if (ParamType.hasQualifiers())
37890b57cec5SDimitry Andric     ParamType = ParamType.getUnqualifiedType();
37900b57cec5SDimitry Andric 
37910b57cec5SDimitry Andric   //   [...] If P is a reference type, the type referred to by P is
37920b57cec5SDimitry Andric   //   used for type deduction.
37930b57cec5SDimitry Andric   const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
37940b57cec5SDimitry Andric   if (ParamRefType)
37950b57cec5SDimitry Andric     ParamType = ParamRefType->getPointeeType();
37960b57cec5SDimitry Andric 
37970b57cec5SDimitry Andric   // Overload sets usually make this parameter an undeduced context,
37980b57cec5SDimitry Andric   // but there are sometimes special circumstances.  Typically
37990b57cec5SDimitry Andric   // involving a template-id-expr.
38000b57cec5SDimitry Andric   if (ArgType == S.Context.OverloadTy) {
38010b57cec5SDimitry Andric     ArgType = ResolveOverloadForDeduction(S, TemplateParams,
38020b57cec5SDimitry Andric                                           Arg, ParamType,
38030b57cec5SDimitry Andric                                           ParamRefType != nullptr);
38040b57cec5SDimitry Andric     if (ArgType.isNull())
38050b57cec5SDimitry Andric       return true;
38060b57cec5SDimitry Andric   }
38070b57cec5SDimitry Andric 
38080b57cec5SDimitry Andric   if (ParamRefType) {
38090b57cec5SDimitry Andric     // If the argument has incomplete array type, try to complete its type.
38100b57cec5SDimitry Andric     if (ArgType->isIncompleteArrayType()) {
38110b57cec5SDimitry Andric       S.completeExprArrayBound(Arg);
38120b57cec5SDimitry Andric       ArgType = Arg->getType();
38130b57cec5SDimitry Andric     }
38140b57cec5SDimitry Andric 
38150b57cec5SDimitry Andric     // C++1z [temp.deduct.call]p3:
38160b57cec5SDimitry Andric     //   If P is a forwarding reference and the argument is an lvalue, the type
38170b57cec5SDimitry Andric     //   "lvalue reference to A" is used in place of A for type deduction.
38180b57cec5SDimitry Andric     if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
38190b57cec5SDimitry Andric         Arg->isLValue())
38200b57cec5SDimitry Andric       ArgType = S.Context.getLValueReferenceType(ArgType);
38210b57cec5SDimitry Andric   } else {
38220b57cec5SDimitry Andric     // C++ [temp.deduct.call]p2:
38230b57cec5SDimitry Andric     //   If P is not a reference type:
38240b57cec5SDimitry Andric     //   - If A is an array type, the pointer type produced by the
38250b57cec5SDimitry Andric     //     array-to-pointer standard conversion (4.2) is used in place of
38260b57cec5SDimitry Andric     //     A for type deduction; otherwise,
38270b57cec5SDimitry Andric     if (ArgType->isArrayType())
38280b57cec5SDimitry Andric       ArgType = S.Context.getArrayDecayedType(ArgType);
38290b57cec5SDimitry Andric     //   - If A is a function type, the pointer type produced by the
38300b57cec5SDimitry Andric     //     function-to-pointer standard conversion (4.3) is used in place
38310b57cec5SDimitry Andric     //     of A for type deduction; otherwise,
38320b57cec5SDimitry Andric     else if (ArgType->isFunctionType())
38330b57cec5SDimitry Andric       ArgType = S.Context.getPointerType(ArgType);
38340b57cec5SDimitry Andric     else {
38350b57cec5SDimitry Andric       // - If A is a cv-qualified type, the top level cv-qualifiers of A's
38360b57cec5SDimitry Andric       //   type are ignored for type deduction.
38370b57cec5SDimitry Andric       ArgType = ArgType.getUnqualifiedType();
38380b57cec5SDimitry Andric     }
38390b57cec5SDimitry Andric   }
38400b57cec5SDimitry Andric 
38410b57cec5SDimitry Andric   // C++0x [temp.deduct.call]p4:
38420b57cec5SDimitry Andric   //   In general, the deduction process attempts to find template argument
38430b57cec5SDimitry Andric   //   values that will make the deduced A identical to A (after the type A
38440b57cec5SDimitry Andric   //   is transformed as described above). [...]
38450b57cec5SDimitry Andric   TDF = TDF_SkipNonDependent;
38460b57cec5SDimitry Andric 
38470b57cec5SDimitry Andric   //     - If the original P is a reference type, the deduced A (i.e., the
38480b57cec5SDimitry Andric   //       type referred to by the reference) can be more cv-qualified than
38490b57cec5SDimitry Andric   //       the transformed A.
38500b57cec5SDimitry Andric   if (ParamRefType)
38510b57cec5SDimitry Andric     TDF |= TDF_ParamWithReferenceType;
38520b57cec5SDimitry Andric   //     - The transformed A can be another pointer or pointer to member
38530b57cec5SDimitry Andric   //       type that can be converted to the deduced A via a qualification
38540b57cec5SDimitry Andric   //       conversion (4.4).
38550b57cec5SDimitry Andric   if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
38560b57cec5SDimitry Andric       ArgType->isObjCObjectPointerType())
38570b57cec5SDimitry Andric     TDF |= TDF_IgnoreQualifiers;
38580b57cec5SDimitry Andric   //     - If P is a class and P has the form simple-template-id, then the
38590b57cec5SDimitry Andric   //       transformed A can be a derived class of the deduced A. Likewise,
38600b57cec5SDimitry Andric   //       if P is a pointer to a class of the form simple-template-id, the
38610b57cec5SDimitry Andric   //       transformed A can be a pointer to a derived class pointed to by
38620b57cec5SDimitry Andric   //       the deduced A.
38630b57cec5SDimitry Andric   if (isSimpleTemplateIdType(ParamType) ||
38640b57cec5SDimitry Andric       (isa<PointerType>(ParamType) &&
38650b57cec5SDimitry Andric        isSimpleTemplateIdType(
38660b57cec5SDimitry Andric                               ParamType->getAs<PointerType>()->getPointeeType())))
38670b57cec5SDimitry Andric     TDF |= TDF_DerivedClass;
38680b57cec5SDimitry Andric 
38690b57cec5SDimitry Andric   return false;
38700b57cec5SDimitry Andric }
38710b57cec5SDimitry Andric 
38720b57cec5SDimitry Andric static bool
38730b57cec5SDimitry Andric hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
38740b57cec5SDimitry Andric                                QualType T);
38750b57cec5SDimitry Andric 
38760b57cec5SDimitry Andric static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
38770b57cec5SDimitry Andric     Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
38780b57cec5SDimitry Andric     QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
38790b57cec5SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
38800b57cec5SDimitry Andric     SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
38810b57cec5SDimitry Andric     bool DecomposedParam, unsigned ArgIdx, unsigned TDF);
38820b57cec5SDimitry Andric 
38830b57cec5SDimitry Andric /// Attempt template argument deduction from an initializer list
38840b57cec5SDimitry Andric ///        deemed to be an argument in a function call.
38850b57cec5SDimitry Andric static Sema::TemplateDeductionResult DeduceFromInitializerList(
38860b57cec5SDimitry Andric     Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
38870b57cec5SDimitry Andric     InitListExpr *ILE, TemplateDeductionInfo &Info,
38880b57cec5SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
38890b57cec5SDimitry Andric     SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
38900b57cec5SDimitry Andric     unsigned TDF) {
38910b57cec5SDimitry Andric   // C++ [temp.deduct.call]p1: (CWG 1591)
38920b57cec5SDimitry Andric   //   If removing references and cv-qualifiers from P gives
38930b57cec5SDimitry Andric   //   std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
38940b57cec5SDimitry Andric   //   a non-empty initializer list, then deduction is performed instead for
38950b57cec5SDimitry Andric   //   each element of the initializer list, taking P0 as a function template
38960b57cec5SDimitry Andric   //   parameter type and the initializer element as its argument
38970b57cec5SDimitry Andric   //
38980b57cec5SDimitry Andric   // We've already removed references and cv-qualifiers here.
38990b57cec5SDimitry Andric   if (!ILE->getNumInits())
39000b57cec5SDimitry Andric     return Sema::TDK_Success;
39010b57cec5SDimitry Andric 
39020b57cec5SDimitry Andric   QualType ElTy;
39030b57cec5SDimitry Andric   auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
39040b57cec5SDimitry Andric   if (ArrTy)
39050b57cec5SDimitry Andric     ElTy = ArrTy->getElementType();
39060b57cec5SDimitry Andric   else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
39070b57cec5SDimitry Andric     //   Otherwise, an initializer list argument causes the parameter to be
39080b57cec5SDimitry Andric     //   considered a non-deduced context
39090b57cec5SDimitry Andric     return Sema::TDK_Success;
39100b57cec5SDimitry Andric   }
39110b57cec5SDimitry Andric 
3912a7dea167SDimitry Andric   // Resolving a core issue: a braced-init-list containing any designators is
3913a7dea167SDimitry Andric   // a non-deduced context.
3914a7dea167SDimitry Andric   for (Expr *E : ILE->inits())
3915a7dea167SDimitry Andric     if (isa<DesignatedInitExpr>(E))
3916a7dea167SDimitry Andric       return Sema::TDK_Success;
3917a7dea167SDimitry Andric 
39180b57cec5SDimitry Andric   // Deduction only needs to be done for dependent types.
39190b57cec5SDimitry Andric   if (ElTy->isDependentType()) {
39200b57cec5SDimitry Andric     for (Expr *E : ILE->inits()) {
39210b57cec5SDimitry Andric       if (auto Result = DeduceTemplateArgumentsFromCallArgument(
39220b57cec5SDimitry Andric               S, TemplateParams, 0, ElTy, E, Info, Deduced, OriginalCallArgs, true,
39230b57cec5SDimitry Andric               ArgIdx, TDF))
39240b57cec5SDimitry Andric         return Result;
39250b57cec5SDimitry Andric     }
39260b57cec5SDimitry Andric   }
39270b57cec5SDimitry Andric 
39280b57cec5SDimitry Andric   //   in the P0[N] case, if N is a non-type template parameter, N is deduced
39290b57cec5SDimitry Andric   //   from the length of the initializer list.
39300b57cec5SDimitry Andric   if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
39310b57cec5SDimitry Andric     // Determine the array bound is something we can deduce.
39320b57cec5SDimitry Andric     if (NonTypeTemplateParmDecl *NTTP =
39330b57cec5SDimitry Andric             getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
39340b57cec5SDimitry Andric       // We can perform template argument deduction for the given non-type
39350b57cec5SDimitry Andric       // template parameter.
39360b57cec5SDimitry Andric       // C++ [temp.deduct.type]p13:
39370b57cec5SDimitry Andric       //   The type of N in the type T[N] is std::size_t.
39380b57cec5SDimitry Andric       QualType T = S.Context.getSizeType();
39390b57cec5SDimitry Andric       llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
39400b57cec5SDimitry Andric       if (auto Result = DeduceNonTypeTemplateArgument(
39410b57cec5SDimitry Andric               S, TemplateParams, NTTP, llvm::APSInt(Size), T,
39420b57cec5SDimitry Andric               /*ArrayBound=*/true, Info, Deduced))
39430b57cec5SDimitry Andric         return Result;
39440b57cec5SDimitry Andric     }
39450b57cec5SDimitry Andric   }
39460b57cec5SDimitry Andric 
39470b57cec5SDimitry Andric   return Sema::TDK_Success;
39480b57cec5SDimitry Andric }
39490b57cec5SDimitry Andric 
39500b57cec5SDimitry Andric /// Perform template argument deduction per [temp.deduct.call] for a
39510b57cec5SDimitry Andric ///        single parameter / argument pair.
39520b57cec5SDimitry Andric static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
39530b57cec5SDimitry Andric     Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
39540b57cec5SDimitry Andric     QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
39550b57cec5SDimitry Andric     SmallVectorImpl<DeducedTemplateArgument> &Deduced,
39560b57cec5SDimitry Andric     SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
39570b57cec5SDimitry Andric     bool DecomposedParam, unsigned ArgIdx, unsigned TDF) {
39580b57cec5SDimitry Andric   QualType ArgType = Arg->getType();
39590b57cec5SDimitry Andric   QualType OrigParamType = ParamType;
39600b57cec5SDimitry Andric 
39610b57cec5SDimitry Andric   //   If P is a reference type [...]
39620b57cec5SDimitry Andric   //   If P is a cv-qualified type [...]
39630b57cec5SDimitry Andric   if (AdjustFunctionParmAndArgTypesForDeduction(
39640b57cec5SDimitry Andric           S, TemplateParams, FirstInnerIndex, ParamType, ArgType, Arg, TDF))
39650b57cec5SDimitry Andric     return Sema::TDK_Success;
39660b57cec5SDimitry Andric 
39670b57cec5SDimitry Andric   //   If [...] the argument is a non-empty initializer list [...]
39680b57cec5SDimitry Andric   if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg))
39690b57cec5SDimitry Andric     return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
39700b57cec5SDimitry Andric                                      Deduced, OriginalCallArgs, ArgIdx, TDF);
39710b57cec5SDimitry Andric 
39720b57cec5SDimitry Andric   //   [...] the deduction process attempts to find template argument values
39730b57cec5SDimitry Andric   //   that will make the deduced A identical to A
39740b57cec5SDimitry Andric   //
39750b57cec5SDimitry Andric   // Keep track of the argument type and corresponding parameter index,
39760b57cec5SDimitry Andric   // so we can check for compatibility between the deduced A and A.
39770b57cec5SDimitry Andric   OriginalCallArgs.push_back(
39780b57cec5SDimitry Andric       Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
39790b57cec5SDimitry Andric   return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
39800b57cec5SDimitry Andric                                             ArgType, Info, Deduced, TDF);
39810b57cec5SDimitry Andric }
39820b57cec5SDimitry Andric 
39830b57cec5SDimitry Andric /// Perform template argument deduction from a function call
39840b57cec5SDimitry Andric /// (C++ [temp.deduct.call]).
39850b57cec5SDimitry Andric ///
39860b57cec5SDimitry Andric /// \param FunctionTemplate the function template for which we are performing
39870b57cec5SDimitry Andric /// template argument deduction.
39880b57cec5SDimitry Andric ///
39890b57cec5SDimitry Andric /// \param ExplicitTemplateArgs the explicit template arguments provided
39900b57cec5SDimitry Andric /// for this call.
39910b57cec5SDimitry Andric ///
39920b57cec5SDimitry Andric /// \param Args the function call arguments
39930b57cec5SDimitry Andric ///
39940b57cec5SDimitry Andric /// \param Specialization if template argument deduction was successful,
39950b57cec5SDimitry Andric /// this will be set to the function template specialization produced by
39960b57cec5SDimitry Andric /// template argument deduction.
39970b57cec5SDimitry Andric ///
39980b57cec5SDimitry Andric /// \param Info the argument will be updated to provide additional information
39990b57cec5SDimitry Andric /// about template argument deduction.
40000b57cec5SDimitry Andric ///
40010b57cec5SDimitry Andric /// \param CheckNonDependent A callback to invoke to check conversions for
40020b57cec5SDimitry Andric /// non-dependent parameters, between deduction and substitution, per DR1391.
40030b57cec5SDimitry Andric /// If this returns true, substitution will be skipped and we return
40040b57cec5SDimitry Andric /// TDK_NonDependentConversionFailure. The callback is passed the parameter
40050b57cec5SDimitry Andric /// types (after substituting explicit template arguments).
40060b57cec5SDimitry Andric ///
40070b57cec5SDimitry Andric /// \returns the result of template argument deduction.
40080b57cec5SDimitry Andric Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
40090b57cec5SDimitry Andric     FunctionTemplateDecl *FunctionTemplate,
40100b57cec5SDimitry Andric     TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
40110b57cec5SDimitry Andric     FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
40120b57cec5SDimitry Andric     bool PartialOverloading,
40130b57cec5SDimitry Andric     llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
40140b57cec5SDimitry Andric   if (FunctionTemplate->isInvalidDecl())
40150b57cec5SDimitry Andric     return TDK_Invalid;
40160b57cec5SDimitry Andric 
40170b57cec5SDimitry Andric   FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
40180b57cec5SDimitry Andric   unsigned NumParams = Function->getNumParams();
40190b57cec5SDimitry Andric 
40200b57cec5SDimitry Andric   unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
40210b57cec5SDimitry Andric 
40220b57cec5SDimitry Andric   // C++ [temp.deduct.call]p1:
40230b57cec5SDimitry Andric   //   Template argument deduction is done by comparing each function template
40240b57cec5SDimitry Andric   //   parameter type (call it P) with the type of the corresponding argument
40250b57cec5SDimitry Andric   //   of the call (call it A) as described below.
40260b57cec5SDimitry Andric   if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
40270b57cec5SDimitry Andric     return TDK_TooFewArguments;
40280b57cec5SDimitry Andric   else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
4029a7dea167SDimitry Andric     const auto *Proto = Function->getType()->castAs<FunctionProtoType>();
40300b57cec5SDimitry Andric     if (Proto->isTemplateVariadic())
40310b57cec5SDimitry Andric       /* Do nothing */;
40320b57cec5SDimitry Andric     else if (!Proto->isVariadic())
40330b57cec5SDimitry Andric       return TDK_TooManyArguments;
40340b57cec5SDimitry Andric   }
40350b57cec5SDimitry Andric 
40360b57cec5SDimitry Andric   // The types of the parameters from which we will perform template argument
40370b57cec5SDimitry Andric   // deduction.
40380b57cec5SDimitry Andric   LocalInstantiationScope InstScope(*this);
40390b57cec5SDimitry Andric   TemplateParameterList *TemplateParams
40400b57cec5SDimitry Andric     = FunctionTemplate->getTemplateParameters();
40410b57cec5SDimitry Andric   SmallVector<DeducedTemplateArgument, 4> Deduced;
40420b57cec5SDimitry Andric   SmallVector<QualType, 8> ParamTypes;
40430b57cec5SDimitry Andric   unsigned NumExplicitlySpecified = 0;
40440b57cec5SDimitry Andric   if (ExplicitTemplateArgs) {
40455ffd83dbSDimitry Andric     TemplateDeductionResult Result;
40465ffd83dbSDimitry Andric     runWithSufficientStackSpace(Info.getLocation(), [&] {
40475ffd83dbSDimitry Andric       Result = SubstituteExplicitTemplateArguments(
40485ffd83dbSDimitry Andric           FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes, nullptr,
40490b57cec5SDimitry Andric           Info);
40505ffd83dbSDimitry Andric     });
40510b57cec5SDimitry Andric     if (Result)
40520b57cec5SDimitry Andric       return Result;
40530b57cec5SDimitry Andric 
40540b57cec5SDimitry Andric     NumExplicitlySpecified = Deduced.size();
40550b57cec5SDimitry Andric   } else {
40560b57cec5SDimitry Andric     // Just fill in the parameter types from the function declaration.
40570b57cec5SDimitry Andric     for (unsigned I = 0; I != NumParams; ++I)
40580b57cec5SDimitry Andric       ParamTypes.push_back(Function->getParamDecl(I)->getType());
40590b57cec5SDimitry Andric   }
40600b57cec5SDimitry Andric 
40610b57cec5SDimitry Andric   SmallVector<OriginalCallArg, 8> OriginalCallArgs;
40620b57cec5SDimitry Andric 
40630b57cec5SDimitry Andric   // Deduce an argument of type ParamType from an expression with index ArgIdx.
40640b57cec5SDimitry Andric   auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx) {
40650b57cec5SDimitry Andric     // C++ [demp.deduct.call]p1: (DR1391)
40660b57cec5SDimitry Andric     //   Template argument deduction is done by comparing each function template
40670b57cec5SDimitry Andric     //   parameter that contains template-parameters that participate in
40680b57cec5SDimitry Andric     //   template argument deduction ...
40690b57cec5SDimitry Andric     if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
40700b57cec5SDimitry Andric       return Sema::TDK_Success;
40710b57cec5SDimitry Andric 
40720b57cec5SDimitry Andric     //   ... with the type of the corresponding argument
40730b57cec5SDimitry Andric     return DeduceTemplateArgumentsFromCallArgument(
40740b57cec5SDimitry Andric         *this, TemplateParams, FirstInnerIndex, ParamType, Args[ArgIdx], Info, Deduced,
40750b57cec5SDimitry Andric         OriginalCallArgs, /*Decomposed*/false, ArgIdx, /*TDF*/ 0);
40760b57cec5SDimitry Andric   };
40770b57cec5SDimitry Andric 
40780b57cec5SDimitry Andric   // Deduce template arguments from the function parameters.
40790b57cec5SDimitry Andric   Deduced.resize(TemplateParams->size());
40800b57cec5SDimitry Andric   SmallVector<QualType, 8> ParamTypesForArgChecking;
40810b57cec5SDimitry Andric   for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
40820b57cec5SDimitry Andric        ParamIdx != NumParamTypes; ++ParamIdx) {
40830b57cec5SDimitry Andric     QualType ParamType = ParamTypes[ParamIdx];
40840b57cec5SDimitry Andric 
40850b57cec5SDimitry Andric     const PackExpansionType *ParamExpansion =
40860b57cec5SDimitry Andric         dyn_cast<PackExpansionType>(ParamType);
40870b57cec5SDimitry Andric     if (!ParamExpansion) {
40880b57cec5SDimitry Andric       // Simple case: matching a function parameter to a function argument.
40890b57cec5SDimitry Andric       if (ArgIdx >= Args.size())
40900b57cec5SDimitry Andric         break;
40910b57cec5SDimitry Andric 
40920b57cec5SDimitry Andric       ParamTypesForArgChecking.push_back(ParamType);
40930b57cec5SDimitry Andric       if (auto Result = DeduceCallArgument(ParamType, ArgIdx++))
40940b57cec5SDimitry Andric         return Result;
40950b57cec5SDimitry Andric 
40960b57cec5SDimitry Andric       continue;
40970b57cec5SDimitry Andric     }
40980b57cec5SDimitry Andric 
40990b57cec5SDimitry Andric     QualType ParamPattern = ParamExpansion->getPattern();
41000b57cec5SDimitry Andric     PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
41010b57cec5SDimitry Andric                                  ParamPattern);
41020b57cec5SDimitry Andric 
41030b57cec5SDimitry Andric     // C++0x [temp.deduct.call]p1:
41040b57cec5SDimitry Andric     //   For a function parameter pack that occurs at the end of the
41050b57cec5SDimitry Andric     //   parameter-declaration-list, the type A of each remaining argument of
41060b57cec5SDimitry Andric     //   the call is compared with the type P of the declarator-id of the
41070b57cec5SDimitry Andric     //   function parameter pack. Each comparison deduces template arguments
41080b57cec5SDimitry Andric     //   for subsequent positions in the template parameter packs expanded by
41090b57cec5SDimitry Andric     //   the function parameter pack. When a function parameter pack appears
41100b57cec5SDimitry Andric     //   in a non-deduced context [not at the end of the list], the type of
41110b57cec5SDimitry Andric     //   that parameter pack is never deduced.
41120b57cec5SDimitry Andric     //
41130b57cec5SDimitry Andric     // FIXME: The above rule allows the size of the parameter pack to change
41140b57cec5SDimitry Andric     // after we skip it (in the non-deduced case). That makes no sense, so
41150b57cec5SDimitry Andric     // we instead notionally deduce the pack against N arguments, where N is
41160b57cec5SDimitry Andric     // the length of the explicitly-specified pack if it's expanded by the
41170b57cec5SDimitry Andric     // parameter pack and 0 otherwise, and we treat each deduction as a
41180b57cec5SDimitry Andric     // non-deduced context.
41190b57cec5SDimitry Andric     if (ParamIdx + 1 == NumParamTypes || PackScope.hasFixedArity()) {
41200b57cec5SDimitry Andric       for (; ArgIdx < Args.size() && PackScope.hasNextElement();
41210b57cec5SDimitry Andric            PackScope.nextPackElement(), ++ArgIdx) {
41220b57cec5SDimitry Andric         ParamTypesForArgChecking.push_back(ParamPattern);
41230b57cec5SDimitry Andric         if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx))
41240b57cec5SDimitry Andric           return Result;
41250b57cec5SDimitry Andric       }
41260b57cec5SDimitry Andric     } else {
41270b57cec5SDimitry Andric       // If the parameter type contains an explicitly-specified pack that we
41280b57cec5SDimitry Andric       // could not expand, skip the number of parameters notionally created
41290b57cec5SDimitry Andric       // by the expansion.
41300b57cec5SDimitry Andric       Optional<unsigned> NumExpansions = ParamExpansion->getNumExpansions();
41310b57cec5SDimitry Andric       if (NumExpansions && !PackScope.isPartiallyExpanded()) {
41320b57cec5SDimitry Andric         for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
41330b57cec5SDimitry Andric              ++I, ++ArgIdx) {
41340b57cec5SDimitry Andric           ParamTypesForArgChecking.push_back(ParamPattern);
41350b57cec5SDimitry Andric           // FIXME: Should we add OriginalCallArgs for these? What if the
41360b57cec5SDimitry Andric           // corresponding argument is a list?
41370b57cec5SDimitry Andric           PackScope.nextPackElement();
41380b57cec5SDimitry Andric         }
41390b57cec5SDimitry Andric       }
41400b57cec5SDimitry Andric     }
41410b57cec5SDimitry Andric 
41420b57cec5SDimitry Andric     // Build argument packs for each of the parameter packs expanded by this
41430b57cec5SDimitry Andric     // pack expansion.
41440b57cec5SDimitry Andric     if (auto Result = PackScope.finish())
41450b57cec5SDimitry Andric       return Result;
41460b57cec5SDimitry Andric   }
41470b57cec5SDimitry Andric 
41480b57cec5SDimitry Andric   // Capture the context in which the function call is made. This is the context
41490b57cec5SDimitry Andric   // that is needed when the accessibility of template arguments is checked.
41500b57cec5SDimitry Andric   DeclContext *CallingCtx = CurContext;
41510b57cec5SDimitry Andric 
41525ffd83dbSDimitry Andric   TemplateDeductionResult Result;
41535ffd83dbSDimitry Andric   runWithSufficientStackSpace(Info.getLocation(), [&] {
41545ffd83dbSDimitry Andric     Result = FinishTemplateArgumentDeduction(
41550b57cec5SDimitry Andric         FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
41560b57cec5SDimitry Andric         &OriginalCallArgs, PartialOverloading, [&, CallingCtx]() {
41570b57cec5SDimitry Andric           ContextRAII SavedContext(*this, CallingCtx);
41580b57cec5SDimitry Andric           return CheckNonDependent(ParamTypesForArgChecking);
41590b57cec5SDimitry Andric         });
41605ffd83dbSDimitry Andric   });
41615ffd83dbSDimitry Andric   return Result;
41620b57cec5SDimitry Andric }
41630b57cec5SDimitry Andric 
41640b57cec5SDimitry Andric QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
41650b57cec5SDimitry Andric                                    QualType FunctionType,
41660b57cec5SDimitry Andric                                    bool AdjustExceptionSpec) {
41670b57cec5SDimitry Andric   if (ArgFunctionType.isNull())
41680b57cec5SDimitry Andric     return ArgFunctionType;
41690b57cec5SDimitry Andric 
4170a7dea167SDimitry Andric   const auto *FunctionTypeP = FunctionType->castAs<FunctionProtoType>();
4171a7dea167SDimitry Andric   const auto *ArgFunctionTypeP = ArgFunctionType->castAs<FunctionProtoType>();
41720b57cec5SDimitry Andric   FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
41730b57cec5SDimitry Andric   bool Rebuild = false;
41740b57cec5SDimitry Andric 
41750b57cec5SDimitry Andric   CallingConv CC = FunctionTypeP->getCallConv();
41760b57cec5SDimitry Andric   if (EPI.ExtInfo.getCC() != CC) {
41770b57cec5SDimitry Andric     EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
41780b57cec5SDimitry Andric     Rebuild = true;
41790b57cec5SDimitry Andric   }
41800b57cec5SDimitry Andric 
41810b57cec5SDimitry Andric   bool NoReturn = FunctionTypeP->getNoReturnAttr();
41820b57cec5SDimitry Andric   if (EPI.ExtInfo.getNoReturn() != NoReturn) {
41830b57cec5SDimitry Andric     EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
41840b57cec5SDimitry Andric     Rebuild = true;
41850b57cec5SDimitry Andric   }
41860b57cec5SDimitry Andric 
41870b57cec5SDimitry Andric   if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
41880b57cec5SDimitry Andric                               ArgFunctionTypeP->hasExceptionSpec())) {
41890b57cec5SDimitry Andric     EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
41900b57cec5SDimitry Andric     Rebuild = true;
41910b57cec5SDimitry Andric   }
41920b57cec5SDimitry Andric 
41930b57cec5SDimitry Andric   if (!Rebuild)
41940b57cec5SDimitry Andric     return ArgFunctionType;
41950b57cec5SDimitry Andric 
41960b57cec5SDimitry Andric   return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
41970b57cec5SDimitry Andric                                  ArgFunctionTypeP->getParamTypes(), EPI);
41980b57cec5SDimitry Andric }
41990b57cec5SDimitry Andric 
42000b57cec5SDimitry Andric /// Deduce template arguments when taking the address of a function
42010b57cec5SDimitry Andric /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
42020b57cec5SDimitry Andric /// a template.
42030b57cec5SDimitry Andric ///
42040b57cec5SDimitry Andric /// \param FunctionTemplate the function template for which we are performing
42050b57cec5SDimitry Andric /// template argument deduction.
42060b57cec5SDimitry Andric ///
42070b57cec5SDimitry Andric /// \param ExplicitTemplateArgs the explicitly-specified template
42080b57cec5SDimitry Andric /// arguments.
42090b57cec5SDimitry Andric ///
42100b57cec5SDimitry Andric /// \param ArgFunctionType the function type that will be used as the
42110b57cec5SDimitry Andric /// "argument" type (A) when performing template argument deduction from the
42120b57cec5SDimitry Andric /// function template's function type. This type may be NULL, if there is no
42130b57cec5SDimitry Andric /// argument type to compare against, in C++0x [temp.arg.explicit]p3.
42140b57cec5SDimitry Andric ///
42150b57cec5SDimitry Andric /// \param Specialization if template argument deduction was successful,
42160b57cec5SDimitry Andric /// this will be set to the function template specialization produced by
42170b57cec5SDimitry Andric /// template argument deduction.
42180b57cec5SDimitry Andric ///
42190b57cec5SDimitry Andric /// \param Info the argument will be updated to provide additional information
42200b57cec5SDimitry Andric /// about template argument deduction.
42210b57cec5SDimitry Andric ///
42220b57cec5SDimitry Andric /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
42230b57cec5SDimitry Andric /// the address of a function template per [temp.deduct.funcaddr] and
42240b57cec5SDimitry Andric /// [over.over]. If \c false, we are looking up a function template
42250b57cec5SDimitry Andric /// specialization based on its signature, per [temp.deduct.decl].
42260b57cec5SDimitry Andric ///
42270b57cec5SDimitry Andric /// \returns the result of template argument deduction.
42280b57cec5SDimitry Andric Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
42290b57cec5SDimitry Andric     FunctionTemplateDecl *FunctionTemplate,
42300b57cec5SDimitry Andric     TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
42310b57cec5SDimitry Andric     FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
42320b57cec5SDimitry Andric     bool IsAddressOfFunction) {
42330b57cec5SDimitry Andric   if (FunctionTemplate->isInvalidDecl())
42340b57cec5SDimitry Andric     return TDK_Invalid;
42350b57cec5SDimitry Andric 
42360b57cec5SDimitry Andric   FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
42370b57cec5SDimitry Andric   TemplateParameterList *TemplateParams
42380b57cec5SDimitry Andric     = FunctionTemplate->getTemplateParameters();
42390b57cec5SDimitry Andric   QualType FunctionType = Function->getType();
42400b57cec5SDimitry Andric 
42410b57cec5SDimitry Andric   // Substitute any explicit template arguments.
42420b57cec5SDimitry Andric   LocalInstantiationScope InstScope(*this);
42430b57cec5SDimitry Andric   SmallVector<DeducedTemplateArgument, 4> Deduced;
42440b57cec5SDimitry Andric   unsigned NumExplicitlySpecified = 0;
42450b57cec5SDimitry Andric   SmallVector<QualType, 4> ParamTypes;
42460b57cec5SDimitry Andric   if (ExplicitTemplateArgs) {
42475ffd83dbSDimitry Andric     TemplateDeductionResult Result;
42485ffd83dbSDimitry Andric     runWithSufficientStackSpace(Info.getLocation(), [&] {
42495ffd83dbSDimitry Andric       Result = SubstituteExplicitTemplateArguments(
42505ffd83dbSDimitry Andric           FunctionTemplate, *ExplicitTemplateArgs, Deduced, ParamTypes,
42515ffd83dbSDimitry Andric           &FunctionType, Info);
42525ffd83dbSDimitry Andric     });
42535ffd83dbSDimitry Andric     if (Result)
42540b57cec5SDimitry Andric       return Result;
42550b57cec5SDimitry Andric 
42560b57cec5SDimitry Andric     NumExplicitlySpecified = Deduced.size();
42570b57cec5SDimitry Andric   }
42580b57cec5SDimitry Andric 
42590b57cec5SDimitry Andric   // When taking the address of a function, we require convertibility of
42600b57cec5SDimitry Andric   // the resulting function type. Otherwise, we allow arbitrary mismatches
42610b57cec5SDimitry Andric   // of calling convention and noreturn.
42620b57cec5SDimitry Andric   if (!IsAddressOfFunction)
42630b57cec5SDimitry Andric     ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
42640b57cec5SDimitry Andric                                           /*AdjustExceptionSpec*/false);
42650b57cec5SDimitry Andric 
42660b57cec5SDimitry Andric   // Unevaluated SFINAE context.
42670b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
42680b57cec5SDimitry Andric       *this, Sema::ExpressionEvaluationContext::Unevaluated);
42690b57cec5SDimitry Andric   SFINAETrap Trap(*this);
42700b57cec5SDimitry Andric 
42710b57cec5SDimitry Andric   Deduced.resize(TemplateParams->size());
42720b57cec5SDimitry Andric 
42730b57cec5SDimitry Andric   // If the function has a deduced return type, substitute it for a dependent
42740b57cec5SDimitry Andric   // type so that we treat it as a non-deduced context in what follows. If we
42750b57cec5SDimitry Andric   // are looking up by signature, the signature type should also have a deduced
42760b57cec5SDimitry Andric   // return type, which we instead expect to exactly match.
42770b57cec5SDimitry Andric   bool HasDeducedReturnType = false;
42780b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
42790b57cec5SDimitry Andric       Function->getReturnType()->getContainedAutoType()) {
42800b57cec5SDimitry Andric     FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
42810b57cec5SDimitry Andric     HasDeducedReturnType = true;
42820b57cec5SDimitry Andric   }
42830b57cec5SDimitry Andric 
42840b57cec5SDimitry Andric   if (!ArgFunctionType.isNull()) {
42850b57cec5SDimitry Andric     unsigned TDF =
42860b57cec5SDimitry Andric         TDF_TopLevelParameterTypeList | TDF_AllowCompatibleFunctionType;
42870b57cec5SDimitry Andric     // Deduce template arguments from the function type.
42880b57cec5SDimitry Andric     if (TemplateDeductionResult Result
42890b57cec5SDimitry Andric           = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
42900b57cec5SDimitry Andric                                                FunctionType, ArgFunctionType,
42910b57cec5SDimitry Andric                                                Info, Deduced, TDF))
42920b57cec5SDimitry Andric       return Result;
42930b57cec5SDimitry Andric   }
42940b57cec5SDimitry Andric 
42955ffd83dbSDimitry Andric   TemplateDeductionResult Result;
42965ffd83dbSDimitry Andric   runWithSufficientStackSpace(Info.getLocation(), [&] {
42975ffd83dbSDimitry Andric     Result = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
42980b57cec5SDimitry Andric                                              NumExplicitlySpecified,
42995ffd83dbSDimitry Andric                                              Specialization, Info);
43005ffd83dbSDimitry Andric   });
43015ffd83dbSDimitry Andric   if (Result)
43020b57cec5SDimitry Andric     return Result;
43030b57cec5SDimitry Andric 
43040b57cec5SDimitry Andric   // If the function has a deduced return type, deduce it now, so we can check
43050b57cec5SDimitry Andric   // that the deduced function type matches the requested type.
43060b57cec5SDimitry Andric   if (HasDeducedReturnType &&
43070b57cec5SDimitry Andric       Specialization->getReturnType()->isUndeducedType() &&
43080b57cec5SDimitry Andric       DeduceReturnType(Specialization, Info.getLocation(), false))
43090b57cec5SDimitry Andric     return TDK_MiscellaneousDeductionFailure;
43100b57cec5SDimitry Andric 
43110b57cec5SDimitry Andric   // If the function has a dependent exception specification, resolve it now,
43120b57cec5SDimitry Andric   // so we can check that the exception specification matches.
43130b57cec5SDimitry Andric   auto *SpecializationFPT =
43140b57cec5SDimitry Andric       Specialization->getType()->castAs<FunctionProtoType>();
43150b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus17 &&
43160b57cec5SDimitry Andric       isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
43170b57cec5SDimitry Andric       !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
43180b57cec5SDimitry Andric     return TDK_MiscellaneousDeductionFailure;
43190b57cec5SDimitry Andric 
43200b57cec5SDimitry Andric   // Adjust the exception specification of the argument to match the
43210b57cec5SDimitry Andric   // substituted and resolved type we just formed. (Calling convention and
43220b57cec5SDimitry Andric   // noreturn can't be dependent, so we don't actually need this for them
43230b57cec5SDimitry Andric   // right now.)
43240b57cec5SDimitry Andric   QualType SpecializationType = Specialization->getType();
43250b57cec5SDimitry Andric   if (!IsAddressOfFunction)
43260b57cec5SDimitry Andric     ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
43270b57cec5SDimitry Andric                                           /*AdjustExceptionSpec*/true);
43280b57cec5SDimitry Andric 
43290b57cec5SDimitry Andric   // If the requested function type does not match the actual type of the
43300b57cec5SDimitry Andric   // specialization with respect to arguments of compatible pointer to function
43310b57cec5SDimitry Andric   // types, template argument deduction fails.
43320b57cec5SDimitry Andric   if (!ArgFunctionType.isNull()) {
43330b57cec5SDimitry Andric     if (IsAddressOfFunction &&
43340b57cec5SDimitry Andric         !isSameOrCompatibleFunctionType(
43350b57cec5SDimitry Andric             Context.getCanonicalType(SpecializationType),
43360b57cec5SDimitry Andric             Context.getCanonicalType(ArgFunctionType)))
43370b57cec5SDimitry Andric       return TDK_MiscellaneousDeductionFailure;
43380b57cec5SDimitry Andric 
43390b57cec5SDimitry Andric     if (!IsAddressOfFunction &&
43400b57cec5SDimitry Andric         !Context.hasSameType(SpecializationType, ArgFunctionType))
43410b57cec5SDimitry Andric       return TDK_MiscellaneousDeductionFailure;
43420b57cec5SDimitry Andric   }
43430b57cec5SDimitry Andric 
43440b57cec5SDimitry Andric   return TDK_Success;
43450b57cec5SDimitry Andric }
43460b57cec5SDimitry Andric 
43470b57cec5SDimitry Andric /// Deduce template arguments for a templated conversion
43480b57cec5SDimitry Andric /// function (C++ [temp.deduct.conv]) and, if successful, produce a
43490b57cec5SDimitry Andric /// conversion function template specialization.
43500b57cec5SDimitry Andric Sema::TemplateDeductionResult
43510b57cec5SDimitry Andric Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
43520b57cec5SDimitry Andric                               QualType ToType,
43530b57cec5SDimitry Andric                               CXXConversionDecl *&Specialization,
43540b57cec5SDimitry Andric                               TemplateDeductionInfo &Info) {
43550b57cec5SDimitry Andric   if (ConversionTemplate->isInvalidDecl())
43560b57cec5SDimitry Andric     return TDK_Invalid;
43570b57cec5SDimitry Andric 
43580b57cec5SDimitry Andric   CXXConversionDecl *ConversionGeneric
43590b57cec5SDimitry Andric     = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
43600b57cec5SDimitry Andric 
43610b57cec5SDimitry Andric   QualType FromType = ConversionGeneric->getConversionType();
43620b57cec5SDimitry Andric 
43630b57cec5SDimitry Andric   // Canonicalize the types for deduction.
43640b57cec5SDimitry Andric   QualType P = Context.getCanonicalType(FromType);
43650b57cec5SDimitry Andric   QualType A = Context.getCanonicalType(ToType);
43660b57cec5SDimitry Andric 
43670b57cec5SDimitry Andric   // C++0x [temp.deduct.conv]p2:
43680b57cec5SDimitry Andric   //   If P is a reference type, the type referred to by P is used for
43690b57cec5SDimitry Andric   //   type deduction.
43700b57cec5SDimitry Andric   if (const ReferenceType *PRef = P->getAs<ReferenceType>())
43710b57cec5SDimitry Andric     P = PRef->getPointeeType();
43720b57cec5SDimitry Andric 
43730b57cec5SDimitry Andric   // C++0x [temp.deduct.conv]p4:
43740b57cec5SDimitry Andric   //   [...] If A is a reference type, the type referred to by A is used
43750b57cec5SDimitry Andric   //   for type deduction.
43760b57cec5SDimitry Andric   if (const ReferenceType *ARef = A->getAs<ReferenceType>()) {
43770b57cec5SDimitry Andric     A = ARef->getPointeeType();
43780b57cec5SDimitry Andric     // We work around a defect in the standard here: cv-qualifiers are also
43790b57cec5SDimitry Andric     // removed from P and A in this case, unless P was a reference type. This
43800b57cec5SDimitry Andric     // seems to mostly match what other compilers are doing.
43810b57cec5SDimitry Andric     if (!FromType->getAs<ReferenceType>()) {
43820b57cec5SDimitry Andric       A = A.getUnqualifiedType();
43830b57cec5SDimitry Andric       P = P.getUnqualifiedType();
43840b57cec5SDimitry Andric     }
43850b57cec5SDimitry Andric 
43860b57cec5SDimitry Andric   // C++ [temp.deduct.conv]p3:
43870b57cec5SDimitry Andric   //
43880b57cec5SDimitry Andric   //   If A is not a reference type:
43890b57cec5SDimitry Andric   } else {
43900b57cec5SDimitry Andric     assert(!A->isReferenceType() && "Reference types were handled above");
43910b57cec5SDimitry Andric 
43920b57cec5SDimitry Andric     //   - If P is an array type, the pointer type produced by the
43930b57cec5SDimitry Andric     //     array-to-pointer standard conversion (4.2) is used in place
43940b57cec5SDimitry Andric     //     of P for type deduction; otherwise,
43950b57cec5SDimitry Andric     if (P->isArrayType())
43960b57cec5SDimitry Andric       P = Context.getArrayDecayedType(P);
43970b57cec5SDimitry Andric     //   - If P is a function type, the pointer type produced by the
43980b57cec5SDimitry Andric     //     function-to-pointer standard conversion (4.3) is used in
43990b57cec5SDimitry Andric     //     place of P for type deduction; otherwise,
44000b57cec5SDimitry Andric     else if (P->isFunctionType())
44010b57cec5SDimitry Andric       P = Context.getPointerType(P);
44020b57cec5SDimitry Andric     //   - If P is a cv-qualified type, the top level cv-qualifiers of
44030b57cec5SDimitry Andric     //     P's type are ignored for type deduction.
44040b57cec5SDimitry Andric     else
44050b57cec5SDimitry Andric       P = P.getUnqualifiedType();
44060b57cec5SDimitry Andric 
44070b57cec5SDimitry Andric     // C++0x [temp.deduct.conv]p4:
44080b57cec5SDimitry Andric     //   If A is a cv-qualified type, the top level cv-qualifiers of A's
44090b57cec5SDimitry Andric     //   type are ignored for type deduction. If A is a reference type, the type
44100b57cec5SDimitry Andric     //   referred to by A is used for type deduction.
44110b57cec5SDimitry Andric     A = A.getUnqualifiedType();
44120b57cec5SDimitry Andric   }
44130b57cec5SDimitry Andric 
44140b57cec5SDimitry Andric   // Unevaluated SFINAE context.
44150b57cec5SDimitry Andric   EnterExpressionEvaluationContext Unevaluated(
44160b57cec5SDimitry Andric       *this, Sema::ExpressionEvaluationContext::Unevaluated);
44170b57cec5SDimitry Andric   SFINAETrap Trap(*this);
44180b57cec5SDimitry Andric 
44190b57cec5SDimitry Andric   // C++ [temp.deduct.conv]p1:
44200b57cec5SDimitry Andric   //   Template argument deduction is done by comparing the return
44210b57cec5SDimitry Andric   //   type of the template conversion function (call it P) with the
44220b57cec5SDimitry Andric   //   type that is required as the result of the conversion (call it
44230b57cec5SDimitry Andric   //   A) as described in 14.8.2.4.
44240b57cec5SDimitry Andric   TemplateParameterList *TemplateParams
44250b57cec5SDimitry Andric     = ConversionTemplate->getTemplateParameters();
44260b57cec5SDimitry Andric   SmallVector<DeducedTemplateArgument, 4> Deduced;
44270b57cec5SDimitry Andric   Deduced.resize(TemplateParams->size());
44280b57cec5SDimitry Andric 
44290b57cec5SDimitry Andric   // C++0x [temp.deduct.conv]p4:
44300b57cec5SDimitry Andric   //   In general, the deduction process attempts to find template
44310b57cec5SDimitry Andric   //   argument values that will make the deduced A identical to
44320b57cec5SDimitry Andric   //   A. However, there are two cases that allow a difference:
44330b57cec5SDimitry Andric   unsigned TDF = 0;
44340b57cec5SDimitry Andric   //     - If the original A is a reference type, A can be more
44350b57cec5SDimitry Andric   //       cv-qualified than the deduced A (i.e., the type referred to
44360b57cec5SDimitry Andric   //       by the reference)
44370b57cec5SDimitry Andric   if (ToType->isReferenceType())
44380b57cec5SDimitry Andric     TDF |= TDF_ArgWithReferenceType;
44390b57cec5SDimitry Andric   //     - The deduced A can be another pointer or pointer to member
44400b57cec5SDimitry Andric   //       type that can be converted to A via a qualification
44410b57cec5SDimitry Andric   //       conversion.
44420b57cec5SDimitry Andric   //
44430b57cec5SDimitry Andric   // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
44440b57cec5SDimitry Andric   // both P and A are pointers or member pointers. In this case, we
44450b57cec5SDimitry Andric   // just ignore cv-qualifiers completely).
44460b57cec5SDimitry Andric   if ((P->isPointerType() && A->isPointerType()) ||
44470b57cec5SDimitry Andric       (P->isMemberPointerType() && A->isMemberPointerType()))
44480b57cec5SDimitry Andric     TDF |= TDF_IgnoreQualifiers;
44490b57cec5SDimitry Andric   if (TemplateDeductionResult Result
44500b57cec5SDimitry Andric         = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
44510b57cec5SDimitry Andric                                              P, A, Info, Deduced, TDF))
44520b57cec5SDimitry Andric     return Result;
44530b57cec5SDimitry Andric 
44540b57cec5SDimitry Andric   // Create an Instantiation Scope for finalizing the operator.
44550b57cec5SDimitry Andric   LocalInstantiationScope InstScope(*this);
44560b57cec5SDimitry Andric   // Finish template argument deduction.
44570b57cec5SDimitry Andric   FunctionDecl *ConversionSpecialized = nullptr;
44585ffd83dbSDimitry Andric   TemplateDeductionResult Result;
44595ffd83dbSDimitry Andric   runWithSufficientStackSpace(Info.getLocation(), [&] {
44605ffd83dbSDimitry Andric     Result = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
44610b57cec5SDimitry Andric                                              ConversionSpecialized, Info);
44625ffd83dbSDimitry Andric   });
44630b57cec5SDimitry Andric   Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
44640b57cec5SDimitry Andric   return Result;
44650b57cec5SDimitry Andric }
44660b57cec5SDimitry Andric 
44670b57cec5SDimitry Andric /// Deduce template arguments for a function template when there is
44680b57cec5SDimitry Andric /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
44690b57cec5SDimitry Andric ///
44700b57cec5SDimitry Andric /// \param FunctionTemplate the function template for which we are performing
44710b57cec5SDimitry Andric /// template argument deduction.
44720b57cec5SDimitry Andric ///
44730b57cec5SDimitry Andric /// \param ExplicitTemplateArgs the explicitly-specified template
44740b57cec5SDimitry Andric /// arguments.
44750b57cec5SDimitry Andric ///
44760b57cec5SDimitry Andric /// \param Specialization if template argument deduction was successful,
44770b57cec5SDimitry Andric /// this will be set to the function template specialization produced by
44780b57cec5SDimitry Andric /// template argument deduction.
44790b57cec5SDimitry Andric ///
44800b57cec5SDimitry Andric /// \param Info the argument will be updated to provide additional information
44810b57cec5SDimitry Andric /// about template argument deduction.
44820b57cec5SDimitry Andric ///
44830b57cec5SDimitry Andric /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
44840b57cec5SDimitry Andric /// the address of a function template in a context where we do not have a
44850b57cec5SDimitry Andric /// target type, per [over.over]. If \c false, we are looking up a function
44860b57cec5SDimitry Andric /// template specialization based on its signature, which only happens when
44870b57cec5SDimitry Andric /// deducing a function parameter type from an argument that is a template-id
44880b57cec5SDimitry Andric /// naming a function template specialization.
44890b57cec5SDimitry Andric ///
44900b57cec5SDimitry Andric /// \returns the result of template argument deduction.
44910b57cec5SDimitry Andric Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
44920b57cec5SDimitry Andric     FunctionTemplateDecl *FunctionTemplate,
44930b57cec5SDimitry Andric     TemplateArgumentListInfo *ExplicitTemplateArgs,
44940b57cec5SDimitry Andric     FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
44950b57cec5SDimitry Andric     bool IsAddressOfFunction) {
44960b57cec5SDimitry Andric   return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
44970b57cec5SDimitry Andric                                  QualType(), Specialization, Info,
44980b57cec5SDimitry Andric                                  IsAddressOfFunction);
44990b57cec5SDimitry Andric }
45000b57cec5SDimitry Andric 
45010b57cec5SDimitry Andric namespace {
45020b57cec5SDimitry Andric   struct DependentAuto { bool IsPack; };
45030b57cec5SDimitry Andric 
45040b57cec5SDimitry Andric   /// Substitute the 'auto' specifier or deduced template specialization type
45050b57cec5SDimitry Andric   /// specifier within a type for a given replacement type.
45060b57cec5SDimitry Andric   class SubstituteDeducedTypeTransform :
45070b57cec5SDimitry Andric       public TreeTransform<SubstituteDeducedTypeTransform> {
45080b57cec5SDimitry Andric     QualType Replacement;
45090b57cec5SDimitry Andric     bool ReplacementIsPack;
45100b57cec5SDimitry Andric     bool UseTypeSugar;
45110b57cec5SDimitry Andric 
45120b57cec5SDimitry Andric   public:
45130b57cec5SDimitry Andric     SubstituteDeducedTypeTransform(Sema &SemaRef, DependentAuto DA)
45140b57cec5SDimitry Andric         : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef), Replacement(),
45150b57cec5SDimitry Andric           ReplacementIsPack(DA.IsPack), UseTypeSugar(true) {}
45160b57cec5SDimitry Andric 
45170b57cec5SDimitry Andric     SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
45180b57cec5SDimitry Andric                                    bool UseTypeSugar = true)
45190b57cec5SDimitry Andric         : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
45200b57cec5SDimitry Andric           Replacement(Replacement), ReplacementIsPack(false),
45210b57cec5SDimitry Andric           UseTypeSugar(UseTypeSugar) {}
45220b57cec5SDimitry Andric 
45230b57cec5SDimitry Andric     QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
45240b57cec5SDimitry Andric       assert(isa<TemplateTypeParmType>(Replacement) &&
45250b57cec5SDimitry Andric              "unexpected unsugared replacement kind");
45260b57cec5SDimitry Andric       QualType Result = Replacement;
45270b57cec5SDimitry Andric       TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
45280b57cec5SDimitry Andric       NewTL.setNameLoc(TL.getNameLoc());
45290b57cec5SDimitry Andric       return Result;
45300b57cec5SDimitry Andric     }
45310b57cec5SDimitry Andric 
45320b57cec5SDimitry Andric     QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
45330b57cec5SDimitry Andric       // If we're building the type pattern to deduce against, don't wrap the
45340b57cec5SDimitry Andric       // substituted type in an AutoType. Certain template deduction rules
45350b57cec5SDimitry Andric       // apply only when a template type parameter appears directly (and not if
45360b57cec5SDimitry Andric       // the parameter is found through desugaring). For instance:
45370b57cec5SDimitry Andric       //   auto &&lref = lvalue;
45380b57cec5SDimitry Andric       // must transform into "rvalue reference to T" not "rvalue reference to
45390b57cec5SDimitry Andric       // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
45400b57cec5SDimitry Andric       //
45410b57cec5SDimitry Andric       // FIXME: Is this still necessary?
45420b57cec5SDimitry Andric       if (!UseTypeSugar)
45430b57cec5SDimitry Andric         return TransformDesugared(TLB, TL);
45440b57cec5SDimitry Andric 
45450b57cec5SDimitry Andric       QualType Result = SemaRef.Context.getAutoType(
45460b57cec5SDimitry Andric           Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull(),
454755e4f9d5SDimitry Andric           ReplacementIsPack, TL.getTypePtr()->getTypeConstraintConcept(),
454855e4f9d5SDimitry Andric           TL.getTypePtr()->getTypeConstraintArguments());
45490b57cec5SDimitry Andric       auto NewTL = TLB.push<AutoTypeLoc>(Result);
455055e4f9d5SDimitry Andric       NewTL.copy(TL);
45510b57cec5SDimitry Andric       return Result;
45520b57cec5SDimitry Andric     }
45530b57cec5SDimitry Andric 
45540b57cec5SDimitry Andric     QualType TransformDeducedTemplateSpecializationType(
45550b57cec5SDimitry Andric         TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
45560b57cec5SDimitry Andric       if (!UseTypeSugar)
45570b57cec5SDimitry Andric         return TransformDesugared(TLB, TL);
45580b57cec5SDimitry Andric 
45590b57cec5SDimitry Andric       QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
45600b57cec5SDimitry Andric           TL.getTypePtr()->getTemplateName(),
45610b57cec5SDimitry Andric           Replacement, Replacement.isNull());
45620b57cec5SDimitry Andric       auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
45630b57cec5SDimitry Andric       NewTL.setNameLoc(TL.getNameLoc());
45640b57cec5SDimitry Andric       return Result;
45650b57cec5SDimitry Andric     }
45660b57cec5SDimitry Andric 
45670b57cec5SDimitry Andric     ExprResult TransformLambdaExpr(LambdaExpr *E) {
45680b57cec5SDimitry Andric       // Lambdas never need to be transformed.
45690b57cec5SDimitry Andric       return E;
45700b57cec5SDimitry Andric     }
45710b57cec5SDimitry Andric 
45720b57cec5SDimitry Andric     QualType Apply(TypeLoc TL) {
45730b57cec5SDimitry Andric       // Create some scratch storage for the transformed type locations.
45740b57cec5SDimitry Andric       // FIXME: We're just going to throw this information away. Don't build it.
45750b57cec5SDimitry Andric       TypeLocBuilder TLB;
45760b57cec5SDimitry Andric       TLB.reserve(TL.getFullDataSize());
45770b57cec5SDimitry Andric       return TransformType(TLB, TL);
45780b57cec5SDimitry Andric     }
45790b57cec5SDimitry Andric   };
45800b57cec5SDimitry Andric 
45810b57cec5SDimitry Andric } // namespace
45820b57cec5SDimitry Andric 
45830b57cec5SDimitry Andric Sema::DeduceAutoResult
45840b57cec5SDimitry Andric Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result,
458555e4f9d5SDimitry Andric                      Optional<unsigned> DependentDeductionDepth,
458655e4f9d5SDimitry Andric                      bool IgnoreConstraints) {
45870b57cec5SDimitry Andric   return DeduceAutoType(Type->getTypeLoc(), Init, Result,
458855e4f9d5SDimitry Andric                         DependentDeductionDepth, IgnoreConstraints);
45890b57cec5SDimitry Andric }
45900b57cec5SDimitry Andric 
45910b57cec5SDimitry Andric /// Attempt to produce an informative diagostic explaining why auto deduction
45920b57cec5SDimitry Andric /// failed.
45930b57cec5SDimitry Andric /// \return \c true if diagnosed, \c false if not.
45940b57cec5SDimitry Andric static bool diagnoseAutoDeductionFailure(Sema &S,
45950b57cec5SDimitry Andric                                          Sema::TemplateDeductionResult TDK,
45960b57cec5SDimitry Andric                                          TemplateDeductionInfo &Info,
45970b57cec5SDimitry Andric                                          ArrayRef<SourceRange> Ranges) {
45980b57cec5SDimitry Andric   switch (TDK) {
45990b57cec5SDimitry Andric   case Sema::TDK_Inconsistent: {
46000b57cec5SDimitry Andric     // Inconsistent deduction means we were deducing from an initializer list.
46010b57cec5SDimitry Andric     auto D = S.Diag(Info.getLocation(), diag::err_auto_inconsistent_deduction);
46020b57cec5SDimitry Andric     D << Info.FirstArg << Info.SecondArg;
46030b57cec5SDimitry Andric     for (auto R : Ranges)
46040b57cec5SDimitry Andric       D << R;
46050b57cec5SDimitry Andric     return true;
46060b57cec5SDimitry Andric   }
46070b57cec5SDimitry Andric 
46080b57cec5SDimitry Andric   // FIXME: Are there other cases for which a custom diagnostic is more useful
46090b57cec5SDimitry Andric   // than the basic "types don't match" diagnostic?
46100b57cec5SDimitry Andric 
46110b57cec5SDimitry Andric   default:
46120b57cec5SDimitry Andric     return false;
46130b57cec5SDimitry Andric   }
46140b57cec5SDimitry Andric }
46150b57cec5SDimitry Andric 
461655e4f9d5SDimitry Andric static Sema::DeduceAutoResult
461755e4f9d5SDimitry Andric CheckDeducedPlaceholderConstraints(Sema &S, const AutoType &Type,
461855e4f9d5SDimitry Andric                                    AutoTypeLoc TypeLoc, QualType Deduced) {
461955e4f9d5SDimitry Andric   ConstraintSatisfaction Satisfaction;
462055e4f9d5SDimitry Andric   ConceptDecl *Concept = Type.getTypeConstraintConcept();
462155e4f9d5SDimitry Andric   TemplateArgumentListInfo TemplateArgs(TypeLoc.getLAngleLoc(),
462255e4f9d5SDimitry Andric                                         TypeLoc.getRAngleLoc());
462355e4f9d5SDimitry Andric   TemplateArgs.addArgument(
462455e4f9d5SDimitry Andric       TemplateArgumentLoc(TemplateArgument(Deduced),
462555e4f9d5SDimitry Andric                           S.Context.getTrivialTypeSourceInfo(
462655e4f9d5SDimitry Andric                               Deduced, TypeLoc.getNameLoc())));
462755e4f9d5SDimitry Andric   for (unsigned I = 0, C = TypeLoc.getNumArgs(); I != C; ++I)
462855e4f9d5SDimitry Andric     TemplateArgs.addArgument(TypeLoc.getArgLoc(I));
462955e4f9d5SDimitry Andric 
463055e4f9d5SDimitry Andric   llvm::SmallVector<TemplateArgument, 4> Converted;
463155e4f9d5SDimitry Andric   if (S.CheckTemplateArgumentList(Concept, SourceLocation(), TemplateArgs,
463255e4f9d5SDimitry Andric                                   /*PartialTemplateArgs=*/false, Converted))
463355e4f9d5SDimitry Andric     return Sema::DAR_FailedAlreadyDiagnosed;
463455e4f9d5SDimitry Andric   if (S.CheckConstraintSatisfaction(Concept, {Concept->getConstraintExpr()},
463555e4f9d5SDimitry Andric                                     Converted, TypeLoc.getLocalSourceRange(),
463655e4f9d5SDimitry Andric                                     Satisfaction))
463755e4f9d5SDimitry Andric     return Sema::DAR_FailedAlreadyDiagnosed;
463855e4f9d5SDimitry Andric   if (!Satisfaction.IsSatisfied) {
463955e4f9d5SDimitry Andric     std::string Buf;
464055e4f9d5SDimitry Andric     llvm::raw_string_ostream OS(Buf);
464155e4f9d5SDimitry Andric     OS << "'" << Concept->getName();
464255e4f9d5SDimitry Andric     if (TypeLoc.hasExplicitTemplateArgs()) {
464355e4f9d5SDimitry Andric       OS << "<";
464455e4f9d5SDimitry Andric       for (const auto &Arg : Type.getTypeConstraintArguments())
464555e4f9d5SDimitry Andric         Arg.print(S.getPrintingPolicy(), OS);
464655e4f9d5SDimitry Andric       OS << ">";
464755e4f9d5SDimitry Andric     }
464855e4f9d5SDimitry Andric     OS << "'";
464955e4f9d5SDimitry Andric     OS.flush();
465055e4f9d5SDimitry Andric     S.Diag(TypeLoc.getConceptNameLoc(),
465155e4f9d5SDimitry Andric            diag::err_placeholder_constraints_not_satisfied)
465255e4f9d5SDimitry Andric          << Deduced << Buf << TypeLoc.getLocalSourceRange();
465355e4f9d5SDimitry Andric     S.DiagnoseUnsatisfiedConstraint(Satisfaction);
465455e4f9d5SDimitry Andric     return Sema::DAR_FailedAlreadyDiagnosed;
465555e4f9d5SDimitry Andric   }
465655e4f9d5SDimitry Andric   return Sema::DAR_Succeeded;
465755e4f9d5SDimitry Andric }
465855e4f9d5SDimitry Andric 
46590b57cec5SDimitry Andric /// Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
46600b57cec5SDimitry Andric ///
46610b57cec5SDimitry Andric /// Note that this is done even if the initializer is dependent. (This is
46620b57cec5SDimitry Andric /// necessary to support partial ordering of templates using 'auto'.)
46630b57cec5SDimitry Andric /// A dependent type will be produced when deducing from a dependent type.
46640b57cec5SDimitry Andric ///
46650b57cec5SDimitry Andric /// \param Type the type pattern using the auto type-specifier.
46660b57cec5SDimitry Andric /// \param Init the initializer for the variable whose type is to be deduced.
46670b57cec5SDimitry Andric /// \param Result if type deduction was successful, this will be set to the
46680b57cec5SDimitry Andric ///        deduced type.
46690b57cec5SDimitry Andric /// \param DependentDeductionDepth Set if we should permit deduction in
46700b57cec5SDimitry Andric ///        dependent cases. This is necessary for template partial ordering with
46710b57cec5SDimitry Andric ///        'auto' template parameters. The value specified is the template
46720b57cec5SDimitry Andric ///        parameter depth at which we should perform 'auto' deduction.
467355e4f9d5SDimitry Andric /// \param IgnoreConstraints Set if we should not fail if the deduced type does
467455e4f9d5SDimitry Andric ///                          not satisfy the type-constraint in the auto type.
46750b57cec5SDimitry Andric Sema::DeduceAutoResult
46760b57cec5SDimitry Andric Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result,
467755e4f9d5SDimitry Andric                      Optional<unsigned> DependentDeductionDepth,
467855e4f9d5SDimitry Andric                      bool IgnoreConstraints) {
46795ffd83dbSDimitry Andric   if (Init->containsErrors())
46805ffd83dbSDimitry Andric     return DAR_FailedAlreadyDiagnosed;
46810b57cec5SDimitry Andric   if (Init->getType()->isNonOverloadPlaceholderType()) {
46820b57cec5SDimitry Andric     ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
46830b57cec5SDimitry Andric     if (NonPlaceholder.isInvalid())
46840b57cec5SDimitry Andric       return DAR_FailedAlreadyDiagnosed;
46850b57cec5SDimitry Andric     Init = NonPlaceholder.get();
46860b57cec5SDimitry Andric   }
46870b57cec5SDimitry Andric 
46880b57cec5SDimitry Andric   DependentAuto DependentResult = {
46890b57cec5SDimitry Andric       /*.IsPack = */ (bool)Type.getAs<PackExpansionTypeLoc>()};
46900b57cec5SDimitry Andric 
46910b57cec5SDimitry Andric   if (!DependentDeductionDepth &&
4692480093f4SDimitry Andric       (Type.getType()->isDependentType() || Init->isTypeDependent() ||
4693480093f4SDimitry Andric        Init->containsUnexpandedParameterPack())) {
46940b57cec5SDimitry Andric     Result = SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
46950b57cec5SDimitry Andric     assert(!Result.isNull() && "substituting DependentTy can't fail");
46960b57cec5SDimitry Andric     return DAR_Succeeded;
46970b57cec5SDimitry Andric   }
46980b57cec5SDimitry Andric 
46990b57cec5SDimitry Andric   // Find the depth of template parameter to synthesize.
47000b57cec5SDimitry Andric   unsigned Depth = DependentDeductionDepth.getValueOr(0);
47010b57cec5SDimitry Andric 
47020b57cec5SDimitry Andric   // If this is a 'decltype(auto)' specifier, do the decltype dance.
47030b57cec5SDimitry Andric   // Since 'decltype(auto)' can only occur at the top of the type, we
47040b57cec5SDimitry Andric   // don't need to go digging for it.
47050b57cec5SDimitry Andric   if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
47060b57cec5SDimitry Andric     if (AT->isDecltypeAuto()) {
47070b57cec5SDimitry Andric       if (isa<InitListExpr>(Init)) {
47080b57cec5SDimitry Andric         Diag(Init->getBeginLoc(), diag::err_decltype_auto_initializer_list);
47090b57cec5SDimitry Andric         return DAR_FailedAlreadyDiagnosed;
47100b57cec5SDimitry Andric       }
47110b57cec5SDimitry Andric 
47120b57cec5SDimitry Andric       ExprResult ER = CheckPlaceholderExpr(Init);
47130b57cec5SDimitry Andric       if (ER.isInvalid())
47140b57cec5SDimitry Andric         return DAR_FailedAlreadyDiagnosed;
47150b57cec5SDimitry Andric       Init = ER.get();
47160b57cec5SDimitry Andric       QualType Deduced = BuildDecltypeType(Init, Init->getBeginLoc(), false);
47170b57cec5SDimitry Andric       if (Deduced.isNull())
47180b57cec5SDimitry Andric         return DAR_FailedAlreadyDiagnosed;
47190b57cec5SDimitry Andric       // FIXME: Support a non-canonical deduced type for 'auto'.
47200b57cec5SDimitry Andric       Deduced = Context.getCanonicalType(Deduced);
472155e4f9d5SDimitry Andric       if (AT->isConstrained() && !IgnoreConstraints) {
472255e4f9d5SDimitry Andric         auto ConstraintsResult =
472355e4f9d5SDimitry Andric             CheckDeducedPlaceholderConstraints(*this, *AT,
472455e4f9d5SDimitry Andric                                                Type.getContainedAutoTypeLoc(),
472555e4f9d5SDimitry Andric                                                Deduced);
472655e4f9d5SDimitry Andric         if (ConstraintsResult != DAR_Succeeded)
472755e4f9d5SDimitry Andric           return ConstraintsResult;
472855e4f9d5SDimitry Andric       }
47290b57cec5SDimitry Andric       Result = SubstituteDeducedTypeTransform(*this, Deduced).Apply(Type);
47300b57cec5SDimitry Andric       if (Result.isNull())
47310b57cec5SDimitry Andric         return DAR_FailedAlreadyDiagnosed;
47320b57cec5SDimitry Andric       return DAR_Succeeded;
47330b57cec5SDimitry Andric     } else if (!getLangOpts().CPlusPlus) {
47340b57cec5SDimitry Andric       if (isa<InitListExpr>(Init)) {
47350b57cec5SDimitry Andric         Diag(Init->getBeginLoc(), diag::err_auto_init_list_from_c);
47360b57cec5SDimitry Andric         return DAR_FailedAlreadyDiagnosed;
47370b57cec5SDimitry Andric       }
47380b57cec5SDimitry Andric     }
47390b57cec5SDimitry Andric   }
47400b57cec5SDimitry Andric 
47410b57cec5SDimitry Andric   SourceLocation Loc = Init->getExprLoc();
47420b57cec5SDimitry Andric 
47430b57cec5SDimitry Andric   LocalInstantiationScope InstScope(*this);
47440b57cec5SDimitry Andric 
47450b57cec5SDimitry Andric   // Build template<class TemplParam> void Func(FuncParam);
47460b57cec5SDimitry Andric   TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
4747480093f4SDimitry Andric       Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false,
4748480093f4SDimitry Andric       false);
47490b57cec5SDimitry Andric   QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
47500b57cec5SDimitry Andric   NamedDecl *TemplParamPtr = TemplParam;
47510b57cec5SDimitry Andric   FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4752480093f4SDimitry Andric       Context, Loc, Loc, TemplParamPtr, Loc, nullptr);
47530b57cec5SDimitry Andric 
47540b57cec5SDimitry Andric   QualType FuncParam =
47550b57cec5SDimitry Andric       SubstituteDeducedTypeTransform(*this, TemplArg, /*UseTypeSugar*/false)
47560b57cec5SDimitry Andric           .Apply(Type);
47570b57cec5SDimitry Andric   assert(!FuncParam.isNull() &&
47580b57cec5SDimitry Andric          "substituting template parameter for 'auto' failed");
47590b57cec5SDimitry Andric 
47600b57cec5SDimitry Andric   // Deduce type of TemplParam in Func(Init)
47610b57cec5SDimitry Andric   SmallVector<DeducedTemplateArgument, 1> Deduced;
47620b57cec5SDimitry Andric   Deduced.resize(1);
47630b57cec5SDimitry Andric 
47640b57cec5SDimitry Andric   TemplateDeductionInfo Info(Loc, Depth);
47650b57cec5SDimitry Andric 
47660b57cec5SDimitry Andric   // If deduction failed, don't diagnose if the initializer is dependent; it
47670b57cec5SDimitry Andric   // might acquire a matching type in the instantiation.
47680b57cec5SDimitry Andric   auto DeductionFailed = [&](TemplateDeductionResult TDK,
47690b57cec5SDimitry Andric                              ArrayRef<SourceRange> Ranges) -> DeduceAutoResult {
47700b57cec5SDimitry Andric     if (Init->isTypeDependent()) {
47710b57cec5SDimitry Andric       Result =
47720b57cec5SDimitry Andric           SubstituteDeducedTypeTransform(*this, DependentResult).Apply(Type);
47730b57cec5SDimitry Andric       assert(!Result.isNull() && "substituting DependentTy can't fail");
47740b57cec5SDimitry Andric       return DAR_Succeeded;
47750b57cec5SDimitry Andric     }
47760b57cec5SDimitry Andric     if (diagnoseAutoDeductionFailure(*this, TDK, Info, Ranges))
47770b57cec5SDimitry Andric       return DAR_FailedAlreadyDiagnosed;
47780b57cec5SDimitry Andric     return DAR_Failed;
47790b57cec5SDimitry Andric   };
47800b57cec5SDimitry Andric 
47810b57cec5SDimitry Andric   SmallVector<OriginalCallArg, 4> OriginalCallArgs;
47820b57cec5SDimitry Andric 
47830b57cec5SDimitry Andric   InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
47840b57cec5SDimitry Andric   if (InitList) {
47850b57cec5SDimitry Andric     // Notionally, we substitute std::initializer_list<T> for 'auto' and deduce
47860b57cec5SDimitry Andric     // against that. Such deduction only succeeds if removing cv-qualifiers and
47870b57cec5SDimitry Andric     // references results in std::initializer_list<T>.
47880b57cec5SDimitry Andric     if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
47890b57cec5SDimitry Andric       return DAR_Failed;
47900b57cec5SDimitry Andric 
4791a7dea167SDimitry Andric     // Resolving a core issue: a braced-init-list containing any designators is
4792a7dea167SDimitry Andric     // a non-deduced context.
4793a7dea167SDimitry Andric     for (Expr *E : InitList->inits())
4794a7dea167SDimitry Andric       if (isa<DesignatedInitExpr>(E))
4795a7dea167SDimitry Andric         return DAR_Failed;
4796a7dea167SDimitry Andric 
47970b57cec5SDimitry Andric     SourceRange DeducedFromInitRange;
47980b57cec5SDimitry Andric     for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
47990b57cec5SDimitry Andric       Expr *Init = InitList->getInit(i);
48000b57cec5SDimitry Andric 
48010b57cec5SDimitry Andric       if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
48020b57cec5SDimitry Andric               *this, TemplateParamsSt.get(), 0, TemplArg, Init,
48030b57cec5SDimitry Andric               Info, Deduced, OriginalCallArgs, /*Decomposed*/ true,
48040b57cec5SDimitry Andric               /*ArgIdx*/ 0, /*TDF*/ 0))
48050b57cec5SDimitry Andric         return DeductionFailed(TDK, {DeducedFromInitRange,
48060b57cec5SDimitry Andric                                      Init->getSourceRange()});
48070b57cec5SDimitry Andric 
48080b57cec5SDimitry Andric       if (DeducedFromInitRange.isInvalid() &&
48090b57cec5SDimitry Andric           Deduced[0].getKind() != TemplateArgument::Null)
48100b57cec5SDimitry Andric         DeducedFromInitRange = Init->getSourceRange();
48110b57cec5SDimitry Andric     }
48120b57cec5SDimitry Andric   } else {
48130b57cec5SDimitry Andric     if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
48140b57cec5SDimitry Andric       Diag(Loc, diag::err_auto_bitfield);
48150b57cec5SDimitry Andric       return DAR_FailedAlreadyDiagnosed;
48160b57cec5SDimitry Andric     }
48170b57cec5SDimitry Andric 
48180b57cec5SDimitry Andric     if (auto TDK = DeduceTemplateArgumentsFromCallArgument(
48190b57cec5SDimitry Andric             *this, TemplateParamsSt.get(), 0, FuncParam, Init, Info, Deduced,
48200b57cec5SDimitry Andric             OriginalCallArgs, /*Decomposed*/ false, /*ArgIdx*/ 0, /*TDF*/ 0))
48210b57cec5SDimitry Andric       return DeductionFailed(TDK, {});
48220b57cec5SDimitry Andric   }
48230b57cec5SDimitry Andric 
48240b57cec5SDimitry Andric   // Could be null if somehow 'auto' appears in a non-deduced context.
48250b57cec5SDimitry Andric   if (Deduced[0].getKind() != TemplateArgument::Type)
48260b57cec5SDimitry Andric     return DeductionFailed(TDK_Incomplete, {});
48270b57cec5SDimitry Andric 
48280b57cec5SDimitry Andric   QualType DeducedType = Deduced[0].getAsType();
48290b57cec5SDimitry Andric 
48300b57cec5SDimitry Andric   if (InitList) {
48310b57cec5SDimitry Andric     DeducedType = BuildStdInitializerList(DeducedType, Loc);
48320b57cec5SDimitry Andric     if (DeducedType.isNull())
48330b57cec5SDimitry Andric       return DAR_FailedAlreadyDiagnosed;
48340b57cec5SDimitry Andric   }
48350b57cec5SDimitry Andric 
483655e4f9d5SDimitry Andric   if (const auto *AT = Type.getType()->getAs<AutoType>()) {
483755e4f9d5SDimitry Andric     if (AT->isConstrained() && !IgnoreConstraints) {
483855e4f9d5SDimitry Andric       auto ConstraintsResult =
483955e4f9d5SDimitry Andric           CheckDeducedPlaceholderConstraints(*this, *AT,
484055e4f9d5SDimitry Andric                                              Type.getContainedAutoTypeLoc(),
484155e4f9d5SDimitry Andric                                              DeducedType);
484255e4f9d5SDimitry Andric       if (ConstraintsResult != DAR_Succeeded)
484355e4f9d5SDimitry Andric         return ConstraintsResult;
484455e4f9d5SDimitry Andric     }
484555e4f9d5SDimitry Andric   }
484655e4f9d5SDimitry Andric 
48470b57cec5SDimitry Andric   Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
48480b57cec5SDimitry Andric   if (Result.isNull())
48490b57cec5SDimitry Andric     return DAR_FailedAlreadyDiagnosed;
48500b57cec5SDimitry Andric 
48510b57cec5SDimitry Andric   // Check that the deduced argument type is compatible with the original
48520b57cec5SDimitry Andric   // argument type per C++ [temp.deduct.call]p4.
48530b57cec5SDimitry Andric   QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
48540b57cec5SDimitry Andric   for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
48550b57cec5SDimitry Andric     assert((bool)InitList == OriginalArg.DecomposedParam &&
48560b57cec5SDimitry Andric            "decomposed non-init-list in auto deduction?");
48570b57cec5SDimitry Andric     if (auto TDK =
48580b57cec5SDimitry Andric             CheckOriginalCallArgDeduction(*this, Info, OriginalArg, DeducedA)) {
48590b57cec5SDimitry Andric       Result = QualType();
48600b57cec5SDimitry Andric       return DeductionFailed(TDK, {});
48610b57cec5SDimitry Andric     }
48620b57cec5SDimitry Andric   }
48630b57cec5SDimitry Andric 
48640b57cec5SDimitry Andric   return DAR_Succeeded;
48650b57cec5SDimitry Andric }
48660b57cec5SDimitry Andric 
48670b57cec5SDimitry Andric QualType Sema::SubstAutoType(QualType TypeWithAuto,
48680b57cec5SDimitry Andric                              QualType TypeToReplaceAuto) {
48690b57cec5SDimitry Andric   if (TypeToReplaceAuto->isDependentType())
48700b57cec5SDimitry Andric     return SubstituteDeducedTypeTransform(
48710b57cec5SDimitry Andric                *this, DependentAuto{
48720b57cec5SDimitry Andric                           TypeToReplaceAuto->containsUnexpandedParameterPack()})
48730b57cec5SDimitry Andric         .TransformType(TypeWithAuto);
48740b57cec5SDimitry Andric   return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
48750b57cec5SDimitry Andric       .TransformType(TypeWithAuto);
48760b57cec5SDimitry Andric }
48770b57cec5SDimitry Andric 
48780b57cec5SDimitry Andric TypeSourceInfo *Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
48790b57cec5SDimitry Andric                                               QualType TypeToReplaceAuto) {
48800b57cec5SDimitry Andric   if (TypeToReplaceAuto->isDependentType())
48810b57cec5SDimitry Andric     return SubstituteDeducedTypeTransform(
48820b57cec5SDimitry Andric                *this,
48830b57cec5SDimitry Andric                DependentAuto{
48840b57cec5SDimitry Andric                    TypeToReplaceAuto->containsUnexpandedParameterPack()})
48850b57cec5SDimitry Andric         .TransformType(TypeWithAuto);
48860b57cec5SDimitry Andric   return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
48870b57cec5SDimitry Andric       .TransformType(TypeWithAuto);
48880b57cec5SDimitry Andric }
48890b57cec5SDimitry Andric 
48900b57cec5SDimitry Andric QualType Sema::ReplaceAutoType(QualType TypeWithAuto,
48910b57cec5SDimitry Andric                                QualType TypeToReplaceAuto) {
48920b57cec5SDimitry Andric   return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
48930b57cec5SDimitry Andric                                         /*UseTypeSugar*/ false)
48940b57cec5SDimitry Andric       .TransformType(TypeWithAuto);
48950b57cec5SDimitry Andric }
48960b57cec5SDimitry Andric 
4897*e63539f3SDimitry Andric TypeSourceInfo *Sema::ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4898*e63539f3SDimitry Andric                                                 QualType TypeToReplaceAuto) {
4899*e63539f3SDimitry Andric   return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
4900*e63539f3SDimitry Andric                                         /*UseTypeSugar*/ false)
4901*e63539f3SDimitry Andric       .TransformType(TypeWithAuto);
4902*e63539f3SDimitry Andric }
4903*e63539f3SDimitry Andric 
49040b57cec5SDimitry Andric void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
49050b57cec5SDimitry Andric   if (isa<InitListExpr>(Init))
49060b57cec5SDimitry Andric     Diag(VDecl->getLocation(),
49070b57cec5SDimitry Andric          VDecl->isInitCapture()
49080b57cec5SDimitry Andric              ? diag::err_init_capture_deduction_failure_from_init_list
49090b57cec5SDimitry Andric              : diag::err_auto_var_deduction_failure_from_init_list)
49100b57cec5SDimitry Andric       << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
49110b57cec5SDimitry Andric   else
49120b57cec5SDimitry Andric     Diag(VDecl->getLocation(),
49130b57cec5SDimitry Andric          VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
49140b57cec5SDimitry Andric                                 : diag::err_auto_var_deduction_failure)
49150b57cec5SDimitry Andric       << VDecl->getDeclName() << VDecl->getType() << Init->getType()
49160b57cec5SDimitry Andric       << Init->getSourceRange();
49170b57cec5SDimitry Andric }
49180b57cec5SDimitry Andric 
49190b57cec5SDimitry Andric bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
49200b57cec5SDimitry Andric                             bool Diagnose) {
49210b57cec5SDimitry Andric   assert(FD->getReturnType()->isUndeducedType());
49220b57cec5SDimitry Andric 
49230b57cec5SDimitry Andric   // For a lambda's conversion operator, deduce any 'auto' or 'decltype(auto)'
49240b57cec5SDimitry Andric   // within the return type from the call operator's type.
49250b57cec5SDimitry Andric   if (isLambdaConversionOperator(FD)) {
49260b57cec5SDimitry Andric     CXXRecordDecl *Lambda = cast<CXXMethodDecl>(FD)->getParent();
49270b57cec5SDimitry Andric     FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
49280b57cec5SDimitry Andric 
49290b57cec5SDimitry Andric     // For a generic lambda, instantiate the call operator if needed.
49300b57cec5SDimitry Andric     if (auto *Args = FD->getTemplateSpecializationArgs()) {
49310b57cec5SDimitry Andric       CallOp = InstantiateFunctionDeclaration(
49320b57cec5SDimitry Andric           CallOp->getDescribedFunctionTemplate(), Args, Loc);
49330b57cec5SDimitry Andric       if (!CallOp || CallOp->isInvalidDecl())
49340b57cec5SDimitry Andric         return true;
49350b57cec5SDimitry Andric 
49360b57cec5SDimitry Andric       // We might need to deduce the return type by instantiating the definition
49370b57cec5SDimitry Andric       // of the operator() function.
4938a7dea167SDimitry Andric       if (CallOp->getReturnType()->isUndeducedType()) {
4939a7dea167SDimitry Andric         runWithSufficientStackSpace(Loc, [&] {
49400b57cec5SDimitry Andric           InstantiateFunctionDefinition(Loc, CallOp);
4941a7dea167SDimitry Andric         });
4942a7dea167SDimitry Andric       }
49430b57cec5SDimitry Andric     }
49440b57cec5SDimitry Andric 
49450b57cec5SDimitry Andric     if (CallOp->isInvalidDecl())
49460b57cec5SDimitry Andric       return true;
49470b57cec5SDimitry Andric     assert(!CallOp->getReturnType()->isUndeducedType() &&
49480b57cec5SDimitry Andric            "failed to deduce lambda return type");
49490b57cec5SDimitry Andric 
49500b57cec5SDimitry Andric     // Build the new return type from scratch.
49510b57cec5SDimitry Andric     QualType RetType = getLambdaConversionFunctionResultType(
49520b57cec5SDimitry Andric         CallOp->getType()->castAs<FunctionProtoType>());
49530b57cec5SDimitry Andric     if (FD->getReturnType()->getAs<PointerType>())
49540b57cec5SDimitry Andric       RetType = Context.getPointerType(RetType);
49550b57cec5SDimitry Andric     else {
49560b57cec5SDimitry Andric       assert(FD->getReturnType()->getAs<BlockPointerType>());
49570b57cec5SDimitry Andric       RetType = Context.getBlockPointerType(RetType);
49580b57cec5SDimitry Andric     }
49590b57cec5SDimitry Andric     Context.adjustDeducedFunctionResultType(FD, RetType);
49600b57cec5SDimitry Andric     return false;
49610b57cec5SDimitry Andric   }
49620b57cec5SDimitry Andric 
4963a7dea167SDimitry Andric   if (FD->getTemplateInstantiationPattern()) {
4964a7dea167SDimitry Andric     runWithSufficientStackSpace(Loc, [&] {
49650b57cec5SDimitry Andric       InstantiateFunctionDefinition(Loc, FD);
4966a7dea167SDimitry Andric     });
4967a7dea167SDimitry Andric   }
49680b57cec5SDimitry Andric 
49690b57cec5SDimitry Andric   bool StillUndeduced = FD->getReturnType()->isUndeducedType();
49700b57cec5SDimitry Andric   if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
49710b57cec5SDimitry Andric     Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
49720b57cec5SDimitry Andric     Diag(FD->getLocation(), diag::note_callee_decl) << FD;
49730b57cec5SDimitry Andric   }
49740b57cec5SDimitry Andric 
49750b57cec5SDimitry Andric   return StillUndeduced;
49760b57cec5SDimitry Andric }
49770b57cec5SDimitry Andric 
49780b57cec5SDimitry Andric /// If this is a non-static member function,
49790b57cec5SDimitry Andric static void
49800b57cec5SDimitry Andric AddImplicitObjectParameterType(ASTContext &Context,
49810b57cec5SDimitry Andric                                CXXMethodDecl *Method,
49820b57cec5SDimitry Andric                                SmallVectorImpl<QualType> &ArgTypes) {
49830b57cec5SDimitry Andric   // C++11 [temp.func.order]p3:
49840b57cec5SDimitry Andric   //   [...] The new parameter is of type "reference to cv A," where cv are
49850b57cec5SDimitry Andric   //   the cv-qualifiers of the function template (if any) and A is
49860b57cec5SDimitry Andric   //   the class of which the function template is a member.
49870b57cec5SDimitry Andric   //
49880b57cec5SDimitry Andric   // The standard doesn't say explicitly, but we pick the appropriate kind of
49890b57cec5SDimitry Andric   // reference type based on [over.match.funcs]p4.
49900b57cec5SDimitry Andric   QualType ArgTy = Context.getTypeDeclType(Method->getParent());
49910b57cec5SDimitry Andric   ArgTy = Context.getQualifiedType(ArgTy, Method->getMethodQualifiers());
49920b57cec5SDimitry Andric   if (Method->getRefQualifier() == RQ_RValue)
49930b57cec5SDimitry Andric     ArgTy = Context.getRValueReferenceType(ArgTy);
49940b57cec5SDimitry Andric   else
49950b57cec5SDimitry Andric     ArgTy = Context.getLValueReferenceType(ArgTy);
49960b57cec5SDimitry Andric   ArgTypes.push_back(ArgTy);
49970b57cec5SDimitry Andric }
49980b57cec5SDimitry Andric 
49990b57cec5SDimitry Andric /// Determine whether the function template \p FT1 is at least as
50000b57cec5SDimitry Andric /// specialized as \p FT2.
50010b57cec5SDimitry Andric static bool isAtLeastAsSpecializedAs(Sema &S,
50020b57cec5SDimitry Andric                                      SourceLocation Loc,
50030b57cec5SDimitry Andric                                      FunctionTemplateDecl *FT1,
50040b57cec5SDimitry Andric                                      FunctionTemplateDecl *FT2,
50050b57cec5SDimitry Andric                                      TemplatePartialOrderingContext TPOC,
50065ffd83dbSDimitry Andric                                      unsigned NumCallArguments1,
50075ffd83dbSDimitry Andric                                      bool Reversed) {
50085ffd83dbSDimitry Andric   assert(!Reversed || TPOC == TPOC_Call);
50095ffd83dbSDimitry Andric 
50100b57cec5SDimitry Andric   FunctionDecl *FD1 = FT1->getTemplatedDecl();
50110b57cec5SDimitry Andric   FunctionDecl *FD2 = FT2->getTemplatedDecl();
50120b57cec5SDimitry Andric   const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
50130b57cec5SDimitry Andric   const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
50140b57cec5SDimitry Andric 
50150b57cec5SDimitry Andric   assert(Proto1 && Proto2 && "Function templates must have prototypes");
50160b57cec5SDimitry Andric   TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
50170b57cec5SDimitry Andric   SmallVector<DeducedTemplateArgument, 4> Deduced;
50180b57cec5SDimitry Andric   Deduced.resize(TemplateParams->size());
50190b57cec5SDimitry Andric 
50200b57cec5SDimitry Andric   // C++0x [temp.deduct.partial]p3:
50210b57cec5SDimitry Andric   //   The types used to determine the ordering depend on the context in which
50220b57cec5SDimitry Andric   //   the partial ordering is done:
50230b57cec5SDimitry Andric   TemplateDeductionInfo Info(Loc);
50240b57cec5SDimitry Andric   SmallVector<QualType, 4> Args2;
50250b57cec5SDimitry Andric   switch (TPOC) {
50260b57cec5SDimitry Andric   case TPOC_Call: {
50270b57cec5SDimitry Andric     //   - In the context of a function call, the function parameter types are
50280b57cec5SDimitry Andric     //     used.
50290b57cec5SDimitry Andric     CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
50300b57cec5SDimitry Andric     CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
50310b57cec5SDimitry Andric 
50320b57cec5SDimitry Andric     // C++11 [temp.func.order]p3:
50330b57cec5SDimitry Andric     //   [...] If only one of the function templates is a non-static
50340b57cec5SDimitry Andric     //   member, that function template is considered to have a new
50350b57cec5SDimitry Andric     //   first parameter inserted in its function parameter list. The
50360b57cec5SDimitry Andric     //   new parameter is of type "reference to cv A," where cv are
50370b57cec5SDimitry Andric     //   the cv-qualifiers of the function template (if any) and A is
50380b57cec5SDimitry Andric     //   the class of which the function template is a member.
50390b57cec5SDimitry Andric     //
50400b57cec5SDimitry Andric     // Note that we interpret this to mean "if one of the function
50410b57cec5SDimitry Andric     // templates is a non-static member and the other is a non-member";
50420b57cec5SDimitry Andric     // otherwise, the ordering rules for static functions against non-static
50430b57cec5SDimitry Andric     // functions don't make any sense.
50440b57cec5SDimitry Andric     //
50450b57cec5SDimitry Andric     // C++98/03 doesn't have this provision but we've extended DR532 to cover
50460b57cec5SDimitry Andric     // it as wording was broken prior to it.
50470b57cec5SDimitry Andric     SmallVector<QualType, 4> Args1;
50480b57cec5SDimitry Andric 
50490b57cec5SDimitry Andric     unsigned NumComparedArguments = NumCallArguments1;
50500b57cec5SDimitry Andric 
50510b57cec5SDimitry Andric     if (!Method2 && Method1 && !Method1->isStatic()) {
50520b57cec5SDimitry Andric       // Compare 'this' from Method1 against first parameter from Method2.
50530b57cec5SDimitry Andric       AddImplicitObjectParameterType(S.Context, Method1, Args1);
50540b57cec5SDimitry Andric       ++NumComparedArguments;
50550b57cec5SDimitry Andric     } else if (!Method1 && Method2 && !Method2->isStatic()) {
50560b57cec5SDimitry Andric       // Compare 'this' from Method2 against first parameter from Method1.
50570b57cec5SDimitry Andric       AddImplicitObjectParameterType(S.Context, Method2, Args2);
50585ffd83dbSDimitry Andric     } else if (Method1 && Method2 && Reversed) {
50595ffd83dbSDimitry Andric       // Compare 'this' from Method1 against second parameter from Method2
50605ffd83dbSDimitry Andric       // and 'this' from Method2 against second parameter from Method1.
50615ffd83dbSDimitry Andric       AddImplicitObjectParameterType(S.Context, Method1, Args1);
50625ffd83dbSDimitry Andric       AddImplicitObjectParameterType(S.Context, Method2, Args2);
50635ffd83dbSDimitry Andric       ++NumComparedArguments;
50640b57cec5SDimitry Andric     }
50650b57cec5SDimitry Andric 
50660b57cec5SDimitry Andric     Args1.insert(Args1.end(), Proto1->param_type_begin(),
50670b57cec5SDimitry Andric                  Proto1->param_type_end());
50680b57cec5SDimitry Andric     Args2.insert(Args2.end(), Proto2->param_type_begin(),
50690b57cec5SDimitry Andric                  Proto2->param_type_end());
50700b57cec5SDimitry Andric 
50710b57cec5SDimitry Andric     // C++ [temp.func.order]p5:
50720b57cec5SDimitry Andric     //   The presence of unused ellipsis and default arguments has no effect on
50730b57cec5SDimitry Andric     //   the partial ordering of function templates.
50740b57cec5SDimitry Andric     if (Args1.size() > NumComparedArguments)
50750b57cec5SDimitry Andric       Args1.resize(NumComparedArguments);
50760b57cec5SDimitry Andric     if (Args2.size() > NumComparedArguments)
50770b57cec5SDimitry Andric       Args2.resize(NumComparedArguments);
50785ffd83dbSDimitry Andric     if (Reversed)
50795ffd83dbSDimitry Andric       std::reverse(Args2.begin(), Args2.end());
50800b57cec5SDimitry Andric     if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
50810b57cec5SDimitry Andric                                 Args1.data(), Args1.size(), Info, Deduced,
50820b57cec5SDimitry Andric                                 TDF_None, /*PartialOrdering=*/true))
50830b57cec5SDimitry Andric       return false;
50840b57cec5SDimitry Andric 
50850b57cec5SDimitry Andric     break;
50860b57cec5SDimitry Andric   }
50870b57cec5SDimitry Andric 
50880b57cec5SDimitry Andric   case TPOC_Conversion:
50890b57cec5SDimitry Andric     //   - In the context of a call to a conversion operator, the return types
50900b57cec5SDimitry Andric     //     of the conversion function templates are used.
50910b57cec5SDimitry Andric     if (DeduceTemplateArgumentsByTypeMatch(
50920b57cec5SDimitry Andric             S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
50930b57cec5SDimitry Andric             Info, Deduced, TDF_None,
50940b57cec5SDimitry Andric             /*PartialOrdering=*/true))
50950b57cec5SDimitry Andric       return false;
50960b57cec5SDimitry Andric     break;
50970b57cec5SDimitry Andric 
50980b57cec5SDimitry Andric   case TPOC_Other:
50990b57cec5SDimitry Andric     //   - In other contexts (14.6.6.2) the function template's function type
51000b57cec5SDimitry Andric     //     is used.
51010b57cec5SDimitry Andric     if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
51020b57cec5SDimitry Andric                                            FD2->getType(), FD1->getType(),
51030b57cec5SDimitry Andric                                            Info, Deduced, TDF_None,
51040b57cec5SDimitry Andric                                            /*PartialOrdering=*/true))
51050b57cec5SDimitry Andric       return false;
51060b57cec5SDimitry Andric     break;
51070b57cec5SDimitry Andric   }
51080b57cec5SDimitry Andric 
51090b57cec5SDimitry Andric   // C++0x [temp.deduct.partial]p11:
51100b57cec5SDimitry Andric   //   In most cases, all template parameters must have values in order for
51110b57cec5SDimitry Andric   //   deduction to succeed, but for partial ordering purposes a template
51120b57cec5SDimitry Andric   //   parameter may remain without a value provided it is not used in the
51130b57cec5SDimitry Andric   //   types being used for partial ordering. [ Note: a template parameter used
51140b57cec5SDimitry Andric   //   in a non-deduced context is considered used. -end note]
51150b57cec5SDimitry Andric   unsigned ArgIdx = 0, NumArgs = Deduced.size();
51160b57cec5SDimitry Andric   for (; ArgIdx != NumArgs; ++ArgIdx)
51170b57cec5SDimitry Andric     if (Deduced[ArgIdx].isNull())
51180b57cec5SDimitry Andric       break;
51190b57cec5SDimitry Andric 
51200b57cec5SDimitry Andric   // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
51210b57cec5SDimitry Andric   // to substitute the deduced arguments back into the template and check that
51220b57cec5SDimitry Andric   // we get the right type.
51230b57cec5SDimitry Andric 
51240b57cec5SDimitry Andric   if (ArgIdx == NumArgs) {
51250b57cec5SDimitry Andric     // All template arguments were deduced. FT1 is at least as specialized
51260b57cec5SDimitry Andric     // as FT2.
51270b57cec5SDimitry Andric     return true;
51280b57cec5SDimitry Andric   }
51290b57cec5SDimitry Andric 
51300b57cec5SDimitry Andric   // Figure out which template parameters were used.
51310b57cec5SDimitry Andric   llvm::SmallBitVector UsedParameters(TemplateParams->size());
51320b57cec5SDimitry Andric   switch (TPOC) {
51330b57cec5SDimitry Andric   case TPOC_Call:
51340b57cec5SDimitry Andric     for (unsigned I = 0, N = Args2.size(); I != N; ++I)
51350b57cec5SDimitry Andric       ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
51360b57cec5SDimitry Andric                                    TemplateParams->getDepth(),
51370b57cec5SDimitry Andric                                    UsedParameters);
51380b57cec5SDimitry Andric     break;
51390b57cec5SDimitry Andric 
51400b57cec5SDimitry Andric   case TPOC_Conversion:
51410b57cec5SDimitry Andric     ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
51420b57cec5SDimitry Andric                                  TemplateParams->getDepth(), UsedParameters);
51430b57cec5SDimitry Andric     break;
51440b57cec5SDimitry Andric 
51450b57cec5SDimitry Andric   case TPOC_Other:
51460b57cec5SDimitry Andric     ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
51470b57cec5SDimitry Andric                                  TemplateParams->getDepth(),
51480b57cec5SDimitry Andric                                  UsedParameters);
51490b57cec5SDimitry Andric     break;
51500b57cec5SDimitry Andric   }
51510b57cec5SDimitry Andric 
51520b57cec5SDimitry Andric   for (; ArgIdx != NumArgs; ++ArgIdx)
51530b57cec5SDimitry Andric     // If this argument had no value deduced but was used in one of the types
51540b57cec5SDimitry Andric     // used for partial ordering, then deduction fails.
51550b57cec5SDimitry Andric     if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
51560b57cec5SDimitry Andric       return false;
51570b57cec5SDimitry Andric 
51580b57cec5SDimitry Andric   return true;
51590b57cec5SDimitry Andric }
51600b57cec5SDimitry Andric 
51610b57cec5SDimitry Andric /// Determine whether this a function template whose parameter-type-list
51620b57cec5SDimitry Andric /// ends with a function parameter pack.
51630b57cec5SDimitry Andric static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
51640b57cec5SDimitry Andric   FunctionDecl *Function = FunTmpl->getTemplatedDecl();
51650b57cec5SDimitry Andric   unsigned NumParams = Function->getNumParams();
51660b57cec5SDimitry Andric   if (NumParams == 0)
51670b57cec5SDimitry Andric     return false;
51680b57cec5SDimitry Andric 
51690b57cec5SDimitry Andric   ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
51700b57cec5SDimitry Andric   if (!Last->isParameterPack())
51710b57cec5SDimitry Andric     return false;
51720b57cec5SDimitry Andric 
51730b57cec5SDimitry Andric   // Make sure that no previous parameter is a parameter pack.
51740b57cec5SDimitry Andric   while (--NumParams > 0) {
51750b57cec5SDimitry Andric     if (Function->getParamDecl(NumParams - 1)->isParameterPack())
51760b57cec5SDimitry Andric       return false;
51770b57cec5SDimitry Andric   }
51780b57cec5SDimitry Andric 
51790b57cec5SDimitry Andric   return true;
51800b57cec5SDimitry Andric }
51810b57cec5SDimitry Andric 
51820b57cec5SDimitry Andric /// Returns the more specialized function template according
51830b57cec5SDimitry Andric /// to the rules of function template partial ordering (C++ [temp.func.order]).
51840b57cec5SDimitry Andric ///
51850b57cec5SDimitry Andric /// \param FT1 the first function template
51860b57cec5SDimitry Andric ///
51870b57cec5SDimitry Andric /// \param FT2 the second function template
51880b57cec5SDimitry Andric ///
51890b57cec5SDimitry Andric /// \param TPOC the context in which we are performing partial ordering of
51900b57cec5SDimitry Andric /// function templates.
51910b57cec5SDimitry Andric ///
51920b57cec5SDimitry Andric /// \param NumCallArguments1 The number of arguments in the call to FT1, used
51930b57cec5SDimitry Andric /// only when \c TPOC is \c TPOC_Call.
51940b57cec5SDimitry Andric ///
51950b57cec5SDimitry Andric /// \param NumCallArguments2 The number of arguments in the call to FT2, used
51960b57cec5SDimitry Andric /// only when \c TPOC is \c TPOC_Call.
51970b57cec5SDimitry Andric ///
51985ffd83dbSDimitry Andric /// \param Reversed If \c true, exactly one of FT1 and FT2 is an overload
51995ffd83dbSDimitry Andric /// candidate with a reversed parameter order. In this case, the corresponding
52005ffd83dbSDimitry Andric /// P/A pairs between FT1 and FT2 are reversed.
52015ffd83dbSDimitry Andric ///
52020b57cec5SDimitry Andric /// \returns the more specialized function template. If neither
52030b57cec5SDimitry Andric /// template is more specialized, returns NULL.
52040b57cec5SDimitry Andric FunctionTemplateDecl *
52050b57cec5SDimitry Andric Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
52060b57cec5SDimitry Andric                                  FunctionTemplateDecl *FT2,
52070b57cec5SDimitry Andric                                  SourceLocation Loc,
52080b57cec5SDimitry Andric                                  TemplatePartialOrderingContext TPOC,
52090b57cec5SDimitry Andric                                  unsigned NumCallArguments1,
52105ffd83dbSDimitry Andric                                  unsigned NumCallArguments2,
52115ffd83dbSDimitry Andric                                  bool Reversed) {
5212480093f4SDimitry Andric 
5213480093f4SDimitry Andric   auto JudgeByConstraints = [&] () -> FunctionTemplateDecl * {
5214480093f4SDimitry Andric     llvm::SmallVector<const Expr *, 3> AC1, AC2;
5215480093f4SDimitry Andric     FT1->getAssociatedConstraints(AC1);
5216480093f4SDimitry Andric     FT2->getAssociatedConstraints(AC2);
5217480093f4SDimitry Andric     bool AtLeastAsConstrained1, AtLeastAsConstrained2;
5218480093f4SDimitry Andric     if (IsAtLeastAsConstrained(FT1, AC1, FT2, AC2, AtLeastAsConstrained1))
5219480093f4SDimitry Andric       return nullptr;
5220480093f4SDimitry Andric     if (IsAtLeastAsConstrained(FT2, AC2, FT1, AC1, AtLeastAsConstrained2))
5221480093f4SDimitry Andric       return nullptr;
5222480093f4SDimitry Andric     if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
5223480093f4SDimitry Andric       return nullptr;
5224480093f4SDimitry Andric     return AtLeastAsConstrained1 ? FT1 : FT2;
5225480093f4SDimitry Andric   };
5226480093f4SDimitry Andric 
52270b57cec5SDimitry Andric   bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
52285ffd83dbSDimitry Andric                                           NumCallArguments1, Reversed);
52290b57cec5SDimitry Andric   bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
52305ffd83dbSDimitry Andric                                           NumCallArguments2, Reversed);
52310b57cec5SDimitry Andric 
52320b57cec5SDimitry Andric   if (Better1 != Better2) // We have a clear winner
52330b57cec5SDimitry Andric     return Better1 ? FT1 : FT2;
52340b57cec5SDimitry Andric 
52350b57cec5SDimitry Andric   if (!Better1 && !Better2) // Neither is better than the other
5236480093f4SDimitry Andric     return JudgeByConstraints();
52370b57cec5SDimitry Andric 
52380b57cec5SDimitry Andric   // FIXME: This mimics what GCC implements, but doesn't match up with the
52390b57cec5SDimitry Andric   // proposed resolution for core issue 692. This area needs to be sorted out,
52400b57cec5SDimitry Andric   // but for now we attempt to maintain compatibility.
52410b57cec5SDimitry Andric   bool Variadic1 = isVariadicFunctionTemplate(FT1);
52420b57cec5SDimitry Andric   bool Variadic2 = isVariadicFunctionTemplate(FT2);
52430b57cec5SDimitry Andric   if (Variadic1 != Variadic2)
52440b57cec5SDimitry Andric     return Variadic1? FT2 : FT1;
52450b57cec5SDimitry Andric 
5246480093f4SDimitry Andric   return JudgeByConstraints();
52470b57cec5SDimitry Andric }
52480b57cec5SDimitry Andric 
52490b57cec5SDimitry Andric /// Determine if the two templates are equivalent.
52500b57cec5SDimitry Andric static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
52510b57cec5SDimitry Andric   if (T1 == T2)
52520b57cec5SDimitry Andric     return true;
52530b57cec5SDimitry Andric 
52540b57cec5SDimitry Andric   if (!T1 || !T2)
52550b57cec5SDimitry Andric     return false;
52560b57cec5SDimitry Andric 
52570b57cec5SDimitry Andric   return T1->getCanonicalDecl() == T2->getCanonicalDecl();
52580b57cec5SDimitry Andric }
52590b57cec5SDimitry Andric 
52600b57cec5SDimitry Andric /// Retrieve the most specialized of the given function template
52610b57cec5SDimitry Andric /// specializations.
52620b57cec5SDimitry Andric ///
52630b57cec5SDimitry Andric /// \param SpecBegin the start iterator of the function template
52640b57cec5SDimitry Andric /// specializations that we will be comparing.
52650b57cec5SDimitry Andric ///
52660b57cec5SDimitry Andric /// \param SpecEnd the end iterator of the function template
52670b57cec5SDimitry Andric /// specializations, paired with \p SpecBegin.
52680b57cec5SDimitry Andric ///
52690b57cec5SDimitry Andric /// \param Loc the location where the ambiguity or no-specializations
52700b57cec5SDimitry Andric /// diagnostic should occur.
52710b57cec5SDimitry Andric ///
52720b57cec5SDimitry Andric /// \param NoneDiag partial diagnostic used to diagnose cases where there are
52730b57cec5SDimitry Andric /// no matching candidates.
52740b57cec5SDimitry Andric ///
52750b57cec5SDimitry Andric /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
52760b57cec5SDimitry Andric /// occurs.
52770b57cec5SDimitry Andric ///
52780b57cec5SDimitry Andric /// \param CandidateDiag partial diagnostic used for each function template
52790b57cec5SDimitry Andric /// specialization that is a candidate in the ambiguous ordering. One parameter
52800b57cec5SDimitry Andric /// in this diagnostic should be unbound, which will correspond to the string
52810b57cec5SDimitry Andric /// describing the template arguments for the function template specialization.
52820b57cec5SDimitry Andric ///
52830b57cec5SDimitry Andric /// \returns the most specialized function template specialization, if
52840b57cec5SDimitry Andric /// found. Otherwise, returns SpecEnd.
52850b57cec5SDimitry Andric UnresolvedSetIterator Sema::getMostSpecialized(
52860b57cec5SDimitry Andric     UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
52870b57cec5SDimitry Andric     TemplateSpecCandidateSet &FailedCandidates,
52880b57cec5SDimitry Andric     SourceLocation Loc, const PartialDiagnostic &NoneDiag,
52890b57cec5SDimitry Andric     const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
52900b57cec5SDimitry Andric     bool Complain, QualType TargetType) {
52910b57cec5SDimitry Andric   if (SpecBegin == SpecEnd) {
52920b57cec5SDimitry Andric     if (Complain) {
52930b57cec5SDimitry Andric       Diag(Loc, NoneDiag);
52940b57cec5SDimitry Andric       FailedCandidates.NoteCandidates(*this, Loc);
52950b57cec5SDimitry Andric     }
52960b57cec5SDimitry Andric     return SpecEnd;
52970b57cec5SDimitry Andric   }
52980b57cec5SDimitry Andric 
52990b57cec5SDimitry Andric   if (SpecBegin + 1 == SpecEnd)
53000b57cec5SDimitry Andric     return SpecBegin;
53010b57cec5SDimitry Andric 
53020b57cec5SDimitry Andric   // Find the function template that is better than all of the templates it
53030b57cec5SDimitry Andric   // has been compared to.
53040b57cec5SDimitry Andric   UnresolvedSetIterator Best = SpecBegin;
53050b57cec5SDimitry Andric   FunctionTemplateDecl *BestTemplate
53060b57cec5SDimitry Andric     = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
53070b57cec5SDimitry Andric   assert(BestTemplate && "Not a function template specialization?");
53080b57cec5SDimitry Andric   for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
53090b57cec5SDimitry Andric     FunctionTemplateDecl *Challenger
53100b57cec5SDimitry Andric       = cast<FunctionDecl>(*I)->getPrimaryTemplate();
53110b57cec5SDimitry Andric     assert(Challenger && "Not a function template specialization?");
53120b57cec5SDimitry Andric     if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
53130b57cec5SDimitry Andric                                                   Loc, TPOC_Other, 0, 0),
53140b57cec5SDimitry Andric                        Challenger)) {
53150b57cec5SDimitry Andric       Best = I;
53160b57cec5SDimitry Andric       BestTemplate = Challenger;
53170b57cec5SDimitry Andric     }
53180b57cec5SDimitry Andric   }
53190b57cec5SDimitry Andric 
53200b57cec5SDimitry Andric   // Make sure that the "best" function template is more specialized than all
53210b57cec5SDimitry Andric   // of the others.
53220b57cec5SDimitry Andric   bool Ambiguous = false;
53230b57cec5SDimitry Andric   for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
53240b57cec5SDimitry Andric     FunctionTemplateDecl *Challenger
53250b57cec5SDimitry Andric       = cast<FunctionDecl>(*I)->getPrimaryTemplate();
53260b57cec5SDimitry Andric     if (I != Best &&
53270b57cec5SDimitry Andric         !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
53280b57cec5SDimitry Andric                                                    Loc, TPOC_Other, 0, 0),
53290b57cec5SDimitry Andric                         BestTemplate)) {
53300b57cec5SDimitry Andric       Ambiguous = true;
53310b57cec5SDimitry Andric       break;
53320b57cec5SDimitry Andric     }
53330b57cec5SDimitry Andric   }
53340b57cec5SDimitry Andric 
53350b57cec5SDimitry Andric   if (!Ambiguous) {
53360b57cec5SDimitry Andric     // We found an answer. Return it.
53370b57cec5SDimitry Andric     return Best;
53380b57cec5SDimitry Andric   }
53390b57cec5SDimitry Andric 
53400b57cec5SDimitry Andric   // Diagnose the ambiguity.
53410b57cec5SDimitry Andric   if (Complain) {
53420b57cec5SDimitry Andric     Diag(Loc, AmbigDiag);
53430b57cec5SDimitry Andric 
53440b57cec5SDimitry Andric     // FIXME: Can we order the candidates in some sane way?
53450b57cec5SDimitry Andric     for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
53460b57cec5SDimitry Andric       PartialDiagnostic PD = CandidateDiag;
53470b57cec5SDimitry Andric       const auto *FD = cast<FunctionDecl>(*I);
53480b57cec5SDimitry Andric       PD << FD << getTemplateArgumentBindingsText(
53490b57cec5SDimitry Andric                       FD->getPrimaryTemplate()->getTemplateParameters(),
53500b57cec5SDimitry Andric                       *FD->getTemplateSpecializationArgs());
53510b57cec5SDimitry Andric       if (!TargetType.isNull())
53520b57cec5SDimitry Andric         HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
53530b57cec5SDimitry Andric       Diag((*I)->getLocation(), PD);
53540b57cec5SDimitry Andric     }
53550b57cec5SDimitry Andric   }
53560b57cec5SDimitry Andric 
53570b57cec5SDimitry Andric   return SpecEnd;
53580b57cec5SDimitry Andric }
53590b57cec5SDimitry Andric 
53600b57cec5SDimitry Andric /// Determine whether one partial specialization, P1, is at least as
53610b57cec5SDimitry Andric /// specialized than another, P2.
53620b57cec5SDimitry Andric ///
53630b57cec5SDimitry Andric /// \tparam TemplateLikeDecl The kind of P2, which must be a
53640b57cec5SDimitry Andric /// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
53650b57cec5SDimitry Andric /// \param T1 The injected-class-name of P1 (faked for a variable template).
53660b57cec5SDimitry Andric /// \param T2 The injected-class-name of P2 (faked for a variable template).
53670b57cec5SDimitry Andric template<typename TemplateLikeDecl>
53680b57cec5SDimitry Andric static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
53690b57cec5SDimitry Andric                                      TemplateLikeDecl *P2,
53700b57cec5SDimitry Andric                                      TemplateDeductionInfo &Info) {
53710b57cec5SDimitry Andric   // C++ [temp.class.order]p1:
53720b57cec5SDimitry Andric   //   For two class template partial specializations, the first is at least as
53730b57cec5SDimitry Andric   //   specialized as the second if, given the following rewrite to two
53740b57cec5SDimitry Andric   //   function templates, the first function template is at least as
53750b57cec5SDimitry Andric   //   specialized as the second according to the ordering rules for function
53760b57cec5SDimitry Andric   //   templates (14.6.6.2):
53770b57cec5SDimitry Andric   //     - the first function template has the same template parameters as the
53780b57cec5SDimitry Andric   //       first partial specialization and has a single function parameter
53790b57cec5SDimitry Andric   //       whose type is a class template specialization with the template
53800b57cec5SDimitry Andric   //       arguments of the first partial specialization, and
53810b57cec5SDimitry Andric   //     - the second function template has the same template parameters as the
53820b57cec5SDimitry Andric   //       second partial specialization and has a single function parameter
53830b57cec5SDimitry Andric   //       whose type is a class template specialization with the template
53840b57cec5SDimitry Andric   //       arguments of the second partial specialization.
53850b57cec5SDimitry Andric   //
53860b57cec5SDimitry Andric   // Rather than synthesize function templates, we merely perform the
53870b57cec5SDimitry Andric   // equivalent partial ordering by performing deduction directly on
53880b57cec5SDimitry Andric   // the template arguments of the class template partial
53890b57cec5SDimitry Andric   // specializations. This computation is slightly simpler than the
53900b57cec5SDimitry Andric   // general problem of function template partial ordering, because
53910b57cec5SDimitry Andric   // class template partial specializations are more constrained. We
53920b57cec5SDimitry Andric   // know that every template parameter is deducible from the class
53930b57cec5SDimitry Andric   // template partial specialization's template arguments, for
53940b57cec5SDimitry Andric   // example.
53950b57cec5SDimitry Andric   SmallVector<DeducedTemplateArgument, 4> Deduced;
53960b57cec5SDimitry Andric 
53970b57cec5SDimitry Andric   // Determine whether P1 is at least as specialized as P2.
53980b57cec5SDimitry Andric   Deduced.resize(P2->getTemplateParameters()->size());
53990b57cec5SDimitry Andric   if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
54000b57cec5SDimitry Andric                                          T2, T1, Info, Deduced, TDF_None,
54010b57cec5SDimitry Andric                                          /*PartialOrdering=*/true))
54020b57cec5SDimitry Andric     return false;
54030b57cec5SDimitry Andric 
54040b57cec5SDimitry Andric   SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
54050b57cec5SDimitry Andric                                                Deduced.end());
54060b57cec5SDimitry Andric   Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
54070b57cec5SDimitry Andric                                    Info);
54080b57cec5SDimitry Andric   auto *TST1 = T1->castAs<TemplateSpecializationType>();
54095ffd83dbSDimitry Andric   bool AtLeastAsSpecialized;
54105ffd83dbSDimitry Andric   S.runWithSufficientStackSpace(Info.getLocation(), [&] {
54115ffd83dbSDimitry Andric     AtLeastAsSpecialized = !FinishTemplateArgumentDeduction(
54120b57cec5SDimitry Andric         S, P2, /*IsPartialOrdering=*/true,
54130b57cec5SDimitry Andric         TemplateArgumentList(TemplateArgumentList::OnStack,
54140b57cec5SDimitry Andric                              TST1->template_arguments()),
54155ffd83dbSDimitry Andric         Deduced, Info);
54165ffd83dbSDimitry Andric   });
54175ffd83dbSDimitry Andric   return AtLeastAsSpecialized;
54180b57cec5SDimitry Andric }
54190b57cec5SDimitry Andric 
54200b57cec5SDimitry Andric /// Returns the more specialized class template partial specialization
54210b57cec5SDimitry Andric /// according to the rules of partial ordering of class template partial
54220b57cec5SDimitry Andric /// specializations (C++ [temp.class.order]).
54230b57cec5SDimitry Andric ///
54240b57cec5SDimitry Andric /// \param PS1 the first class template partial specialization
54250b57cec5SDimitry Andric ///
54260b57cec5SDimitry Andric /// \param PS2 the second class template partial specialization
54270b57cec5SDimitry Andric ///
54280b57cec5SDimitry Andric /// \returns the more specialized class template partial specialization. If
54290b57cec5SDimitry Andric /// neither partial specialization is more specialized, returns NULL.
54300b57cec5SDimitry Andric ClassTemplatePartialSpecializationDecl *
54310b57cec5SDimitry Andric Sema::getMoreSpecializedPartialSpecialization(
54320b57cec5SDimitry Andric                                   ClassTemplatePartialSpecializationDecl *PS1,
54330b57cec5SDimitry Andric                                   ClassTemplatePartialSpecializationDecl *PS2,
54340b57cec5SDimitry Andric                                               SourceLocation Loc) {
54350b57cec5SDimitry Andric   QualType PT1 = PS1->getInjectedSpecializationType();
54360b57cec5SDimitry Andric   QualType PT2 = PS2->getInjectedSpecializationType();
54370b57cec5SDimitry Andric 
54380b57cec5SDimitry Andric   TemplateDeductionInfo Info(Loc);
54390b57cec5SDimitry Andric   bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
54400b57cec5SDimitry Andric   bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
54410b57cec5SDimitry Andric 
5442480093f4SDimitry Andric   if (!Better1 && !Better2)
54430b57cec5SDimitry Andric       return nullptr;
5444480093f4SDimitry Andric   if (Better1 && Better2) {
5445480093f4SDimitry Andric     llvm::SmallVector<const Expr *, 3> AC1, AC2;
5446480093f4SDimitry Andric     PS1->getAssociatedConstraints(AC1);
5447480093f4SDimitry Andric     PS2->getAssociatedConstraints(AC2);
5448480093f4SDimitry Andric     bool AtLeastAsConstrained1, AtLeastAsConstrained2;
5449480093f4SDimitry Andric     if (IsAtLeastAsConstrained(PS1, AC1, PS2, AC2, AtLeastAsConstrained1))
5450480093f4SDimitry Andric       return nullptr;
5451480093f4SDimitry Andric     if (IsAtLeastAsConstrained(PS2, AC2, PS1, AC1, AtLeastAsConstrained2))
5452480093f4SDimitry Andric       return nullptr;
5453480093f4SDimitry Andric     if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
5454480093f4SDimitry Andric       return nullptr;
5455480093f4SDimitry Andric     return AtLeastAsConstrained1 ? PS1 : PS2;
5456480093f4SDimitry Andric   }
54570b57cec5SDimitry Andric 
54580b57cec5SDimitry Andric   return Better1 ? PS1 : PS2;
54590b57cec5SDimitry Andric }
54600b57cec5SDimitry Andric 
54610b57cec5SDimitry Andric bool Sema::isMoreSpecializedThanPrimary(
54620b57cec5SDimitry Andric     ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
54630b57cec5SDimitry Andric   ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
54640b57cec5SDimitry Andric   QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
54650b57cec5SDimitry Andric   QualType PartialT = Spec->getInjectedSpecializationType();
54660b57cec5SDimitry Andric   if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
54670b57cec5SDimitry Andric     return false;
5468480093f4SDimitry Andric   if (!isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info))
54690b57cec5SDimitry Andric     return true;
5470480093f4SDimitry Andric   Info.clearSFINAEDiagnostic();
5471480093f4SDimitry Andric   llvm::SmallVector<const Expr *, 3> PrimaryAC, SpecAC;
5472480093f4SDimitry Andric   Primary->getAssociatedConstraints(PrimaryAC);
5473480093f4SDimitry Andric   Spec->getAssociatedConstraints(SpecAC);
5474480093f4SDimitry Andric   bool AtLeastAsConstrainedPrimary, AtLeastAsConstrainedSpec;
5475480093f4SDimitry Andric   if (IsAtLeastAsConstrained(Spec, SpecAC, Primary, PrimaryAC,
5476480093f4SDimitry Andric                              AtLeastAsConstrainedSpec))
5477480093f4SDimitry Andric     return false;
5478480093f4SDimitry Andric   if (!AtLeastAsConstrainedSpec)
5479480093f4SDimitry Andric     return false;
5480480093f4SDimitry Andric   if (IsAtLeastAsConstrained(Primary, PrimaryAC, Spec, SpecAC,
5481480093f4SDimitry Andric                              AtLeastAsConstrainedPrimary))
5482480093f4SDimitry Andric     return false;
5483480093f4SDimitry Andric   return !AtLeastAsConstrainedPrimary;
54840b57cec5SDimitry Andric }
54850b57cec5SDimitry Andric 
54860b57cec5SDimitry Andric VarTemplatePartialSpecializationDecl *
54870b57cec5SDimitry Andric Sema::getMoreSpecializedPartialSpecialization(
54880b57cec5SDimitry Andric     VarTemplatePartialSpecializationDecl *PS1,
54890b57cec5SDimitry Andric     VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
54900b57cec5SDimitry Andric   // Pretend the variable template specializations are class template
54910b57cec5SDimitry Andric   // specializations and form a fake injected class name type for comparison.
54920b57cec5SDimitry Andric   assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
54930b57cec5SDimitry Andric          "the partial specializations being compared should specialize"
54940b57cec5SDimitry Andric          " the same template.");
54950b57cec5SDimitry Andric   TemplateName Name(PS1->getSpecializedTemplate());
54960b57cec5SDimitry Andric   TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
54970b57cec5SDimitry Andric   QualType PT1 = Context.getTemplateSpecializationType(
54980b57cec5SDimitry Andric       CanonTemplate, PS1->getTemplateArgs().asArray());
54990b57cec5SDimitry Andric   QualType PT2 = Context.getTemplateSpecializationType(
55000b57cec5SDimitry Andric       CanonTemplate, PS2->getTemplateArgs().asArray());
55010b57cec5SDimitry Andric 
55020b57cec5SDimitry Andric   TemplateDeductionInfo Info(Loc);
55030b57cec5SDimitry Andric   bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
55040b57cec5SDimitry Andric   bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
55050b57cec5SDimitry Andric 
5506480093f4SDimitry Andric   if (!Better1 && !Better2)
55070b57cec5SDimitry Andric     return nullptr;
5508480093f4SDimitry Andric   if (Better1 && Better2) {
5509480093f4SDimitry Andric     llvm::SmallVector<const Expr *, 3> AC1, AC2;
5510480093f4SDimitry Andric     PS1->getAssociatedConstraints(AC1);
5511480093f4SDimitry Andric     PS2->getAssociatedConstraints(AC2);
5512480093f4SDimitry Andric     bool AtLeastAsConstrained1, AtLeastAsConstrained2;
5513480093f4SDimitry Andric     if (IsAtLeastAsConstrained(PS1, AC1, PS2, AC2, AtLeastAsConstrained1))
5514480093f4SDimitry Andric       return nullptr;
5515480093f4SDimitry Andric     if (IsAtLeastAsConstrained(PS2, AC2, PS1, AC1, AtLeastAsConstrained2))
5516480093f4SDimitry Andric       return nullptr;
5517480093f4SDimitry Andric     if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
5518480093f4SDimitry Andric       return nullptr;
5519480093f4SDimitry Andric     return AtLeastAsConstrained1 ? PS1 : PS2;
5520480093f4SDimitry Andric   }
55210b57cec5SDimitry Andric 
55220b57cec5SDimitry Andric   return Better1 ? PS1 : PS2;
55230b57cec5SDimitry Andric }
55240b57cec5SDimitry Andric 
55250b57cec5SDimitry Andric bool Sema::isMoreSpecializedThanPrimary(
55260b57cec5SDimitry Andric     VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
55270b57cec5SDimitry Andric   TemplateDecl *Primary = Spec->getSpecializedTemplate();
55280b57cec5SDimitry Andric   // FIXME: Cache the injected template arguments rather than recomputing
55290b57cec5SDimitry Andric   // them for each partial specialization.
55300b57cec5SDimitry Andric   SmallVector<TemplateArgument, 8> PrimaryArgs;
55310b57cec5SDimitry Andric   Context.getInjectedTemplateArgs(Primary->getTemplateParameters(),
55320b57cec5SDimitry Andric                                   PrimaryArgs);
55330b57cec5SDimitry Andric 
55340b57cec5SDimitry Andric   TemplateName CanonTemplate =
55350b57cec5SDimitry Andric       Context.getCanonicalTemplateName(TemplateName(Primary));
55360b57cec5SDimitry Andric   QualType PrimaryT = Context.getTemplateSpecializationType(
55370b57cec5SDimitry Andric       CanonTemplate, PrimaryArgs);
55380b57cec5SDimitry Andric   QualType PartialT = Context.getTemplateSpecializationType(
55390b57cec5SDimitry Andric       CanonTemplate, Spec->getTemplateArgs().asArray());
5540480093f4SDimitry Andric 
55410b57cec5SDimitry Andric   if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
55420b57cec5SDimitry Andric     return false;
5543480093f4SDimitry Andric   if (!isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info))
55440b57cec5SDimitry Andric     return true;
5545480093f4SDimitry Andric   Info.clearSFINAEDiagnostic();
5546480093f4SDimitry Andric   llvm::SmallVector<const Expr *, 3> PrimaryAC, SpecAC;
5547480093f4SDimitry Andric   Primary->getAssociatedConstraints(PrimaryAC);
5548480093f4SDimitry Andric   Spec->getAssociatedConstraints(SpecAC);
5549480093f4SDimitry Andric   bool AtLeastAsConstrainedPrimary, AtLeastAsConstrainedSpec;
5550480093f4SDimitry Andric   if (IsAtLeastAsConstrained(Spec, SpecAC, Primary, PrimaryAC,
5551480093f4SDimitry Andric                              AtLeastAsConstrainedSpec))
5552480093f4SDimitry Andric     return false;
5553480093f4SDimitry Andric   if (!AtLeastAsConstrainedSpec)
5554480093f4SDimitry Andric     return false;
5555480093f4SDimitry Andric   if (IsAtLeastAsConstrained(Primary, PrimaryAC, Spec, SpecAC,
5556480093f4SDimitry Andric                              AtLeastAsConstrainedPrimary))
5557480093f4SDimitry Andric     return false;
5558480093f4SDimitry Andric   return !AtLeastAsConstrainedPrimary;
55590b57cec5SDimitry Andric }
55600b57cec5SDimitry Andric 
55610b57cec5SDimitry Andric bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
55620b57cec5SDimitry Andric      TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) {
55630b57cec5SDimitry Andric   // C++1z [temp.arg.template]p4: (DR 150)
55640b57cec5SDimitry Andric   //   A template template-parameter P is at least as specialized as a
55650b57cec5SDimitry Andric   //   template template-argument A if, given the following rewrite to two
55660b57cec5SDimitry Andric   //   function templates...
55670b57cec5SDimitry Andric 
55680b57cec5SDimitry Andric   // Rather than synthesize function templates, we merely perform the
55690b57cec5SDimitry Andric   // equivalent partial ordering by performing deduction directly on
55700b57cec5SDimitry Andric   // the template parameter lists of the template template parameters.
55710b57cec5SDimitry Andric   //
55720b57cec5SDimitry Andric   //   Given an invented class template X with the template parameter list of
55730b57cec5SDimitry Andric   //   A (including default arguments):
55740b57cec5SDimitry Andric   TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg));
55750b57cec5SDimitry Andric   TemplateParameterList *A = AArg->getTemplateParameters();
55760b57cec5SDimitry Andric 
55770b57cec5SDimitry Andric   //    - Each function template has a single function parameter whose type is
55780b57cec5SDimitry Andric   //      a specialization of X with template arguments corresponding to the
55790b57cec5SDimitry Andric   //      template parameters from the respective function template
55800b57cec5SDimitry Andric   SmallVector<TemplateArgument, 8> AArgs;
55810b57cec5SDimitry Andric   Context.getInjectedTemplateArgs(A, AArgs);
55820b57cec5SDimitry Andric 
55830b57cec5SDimitry Andric   // Check P's arguments against A's parameter list. This will fill in default
55840b57cec5SDimitry Andric   // template arguments as needed. AArgs are already correct by construction.
55850b57cec5SDimitry Andric   // We can't just use CheckTemplateIdType because that will expand alias
55860b57cec5SDimitry Andric   // templates.
55870b57cec5SDimitry Andric   SmallVector<TemplateArgument, 4> PArgs;
55880b57cec5SDimitry Andric   {
55890b57cec5SDimitry Andric     SFINAETrap Trap(*this);
55900b57cec5SDimitry Andric 
55910b57cec5SDimitry Andric     Context.getInjectedTemplateArgs(P, PArgs);
5592480093f4SDimitry Andric     TemplateArgumentListInfo PArgList(P->getLAngleLoc(),
5593480093f4SDimitry Andric                                       P->getRAngleLoc());
55940b57cec5SDimitry Andric     for (unsigned I = 0, N = P->size(); I != N; ++I) {
55950b57cec5SDimitry Andric       // Unwrap packs that getInjectedTemplateArgs wrapped around pack
55960b57cec5SDimitry Andric       // expansions, to form an "as written" argument list.
55970b57cec5SDimitry Andric       TemplateArgument Arg = PArgs[I];
55980b57cec5SDimitry Andric       if (Arg.getKind() == TemplateArgument::Pack) {
55990b57cec5SDimitry Andric         assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
56000b57cec5SDimitry Andric         Arg = *Arg.pack_begin();
56010b57cec5SDimitry Andric       }
56020b57cec5SDimitry Andric       PArgList.addArgument(getTrivialTemplateArgumentLoc(
56030b57cec5SDimitry Andric           Arg, QualType(), P->getParam(I)->getLocation()));
56040b57cec5SDimitry Andric     }
56050b57cec5SDimitry Andric     PArgs.clear();
56060b57cec5SDimitry Andric 
56070b57cec5SDimitry Andric     // C++1z [temp.arg.template]p3:
56080b57cec5SDimitry Andric     //   If the rewrite produces an invalid type, then P is not at least as
56090b57cec5SDimitry Andric     //   specialized as A.
56100b57cec5SDimitry Andric     if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, PArgs) ||
56110b57cec5SDimitry Andric         Trap.hasErrorOccurred())
56120b57cec5SDimitry Andric       return false;
56130b57cec5SDimitry Andric   }
56140b57cec5SDimitry Andric 
56150b57cec5SDimitry Andric   QualType AType = Context.getTemplateSpecializationType(X, AArgs);
56160b57cec5SDimitry Andric   QualType PType = Context.getTemplateSpecializationType(X, PArgs);
56170b57cec5SDimitry Andric 
56180b57cec5SDimitry Andric   //   ... the function template corresponding to P is at least as specialized
56190b57cec5SDimitry Andric   //   as the function template corresponding to A according to the partial
56200b57cec5SDimitry Andric   //   ordering rules for function templates.
56210b57cec5SDimitry Andric   TemplateDeductionInfo Info(Loc, A->getDepth());
56220b57cec5SDimitry Andric   return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info);
56230b57cec5SDimitry Andric }
56240b57cec5SDimitry Andric 
5625480093f4SDimitry Andric namespace {
5626480093f4SDimitry Andric struct MarkUsedTemplateParameterVisitor :
5627480093f4SDimitry Andric     RecursiveASTVisitor<MarkUsedTemplateParameterVisitor> {
5628480093f4SDimitry Andric   llvm::SmallBitVector &Used;
5629480093f4SDimitry Andric   unsigned Depth;
5630480093f4SDimitry Andric 
5631480093f4SDimitry Andric   MarkUsedTemplateParameterVisitor(llvm::SmallBitVector &Used,
5632480093f4SDimitry Andric                                    unsigned Depth)
5633480093f4SDimitry Andric       : Used(Used), Depth(Depth) { }
5634480093f4SDimitry Andric 
5635480093f4SDimitry Andric   bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
5636480093f4SDimitry Andric     if (T->getDepth() == Depth)
5637480093f4SDimitry Andric       Used[T->getIndex()] = true;
5638480093f4SDimitry Andric     return true;
5639480093f4SDimitry Andric   }
5640480093f4SDimitry Andric 
5641480093f4SDimitry Andric   bool TraverseTemplateName(TemplateName Template) {
5642480093f4SDimitry Andric     if (auto *TTP =
5643480093f4SDimitry Andric             dyn_cast<TemplateTemplateParmDecl>(Template.getAsTemplateDecl()))
5644480093f4SDimitry Andric       if (TTP->getDepth() == Depth)
5645480093f4SDimitry Andric         Used[TTP->getIndex()] = true;
5646480093f4SDimitry Andric     RecursiveASTVisitor<MarkUsedTemplateParameterVisitor>::
5647480093f4SDimitry Andric         TraverseTemplateName(Template);
5648480093f4SDimitry Andric     return true;
5649480093f4SDimitry Andric   }
5650480093f4SDimitry Andric 
5651480093f4SDimitry Andric   bool VisitDeclRefExpr(DeclRefExpr *E) {
5652480093f4SDimitry Andric     if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
5653480093f4SDimitry Andric       if (NTTP->getDepth() == Depth)
5654480093f4SDimitry Andric         Used[NTTP->getIndex()] = true;
5655480093f4SDimitry Andric     return true;
5656480093f4SDimitry Andric   }
5657480093f4SDimitry Andric };
5658480093f4SDimitry Andric }
5659480093f4SDimitry Andric 
56600b57cec5SDimitry Andric /// Mark the template parameters that are used by the given
56610b57cec5SDimitry Andric /// expression.
56620b57cec5SDimitry Andric static void
56630b57cec5SDimitry Andric MarkUsedTemplateParameters(ASTContext &Ctx,
56640b57cec5SDimitry Andric                            const Expr *E,
56650b57cec5SDimitry Andric                            bool OnlyDeduced,
56660b57cec5SDimitry Andric                            unsigned Depth,
56670b57cec5SDimitry Andric                            llvm::SmallBitVector &Used) {
5668480093f4SDimitry Andric   if (!OnlyDeduced) {
5669480093f4SDimitry Andric     MarkUsedTemplateParameterVisitor(Used, Depth)
5670480093f4SDimitry Andric         .TraverseStmt(const_cast<Expr *>(E));
5671480093f4SDimitry Andric     return;
5672480093f4SDimitry Andric   }
5673480093f4SDimitry Andric 
56740b57cec5SDimitry Andric   // We can deduce from a pack expansion.
56750b57cec5SDimitry Andric   if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
56760b57cec5SDimitry Andric     E = Expansion->getPattern();
56770b57cec5SDimitry Andric 
56780b57cec5SDimitry Andric   // Skip through any implicit casts we added while type-checking, and any
56790b57cec5SDimitry Andric   // substitutions performed by template alias expansion.
56800b57cec5SDimitry Andric   while (true) {
56810b57cec5SDimitry Andric     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
56820b57cec5SDimitry Andric       E = ICE->getSubExpr();
56830b57cec5SDimitry Andric     else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(E))
56840b57cec5SDimitry Andric       E = CE->getSubExpr();
56850b57cec5SDimitry Andric     else if (const SubstNonTypeTemplateParmExpr *Subst =
56860b57cec5SDimitry Andric                dyn_cast<SubstNonTypeTemplateParmExpr>(E))
56870b57cec5SDimitry Andric       E = Subst->getReplacement();
56880b57cec5SDimitry Andric     else
56890b57cec5SDimitry Andric       break;
56900b57cec5SDimitry Andric   }
56910b57cec5SDimitry Andric 
56920b57cec5SDimitry Andric   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
56930b57cec5SDimitry Andric   if (!DRE)
56940b57cec5SDimitry Andric     return;
56950b57cec5SDimitry Andric 
56960b57cec5SDimitry Andric   const NonTypeTemplateParmDecl *NTTP
56970b57cec5SDimitry Andric     = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
56980b57cec5SDimitry Andric   if (!NTTP)
56990b57cec5SDimitry Andric     return;
57000b57cec5SDimitry Andric 
57010b57cec5SDimitry Andric   if (NTTP->getDepth() == Depth)
57020b57cec5SDimitry Andric     Used[NTTP->getIndex()] = true;
57030b57cec5SDimitry Andric 
57040b57cec5SDimitry Andric   // In C++17 mode, additional arguments may be deduced from the type of a
57050b57cec5SDimitry Andric   // non-type argument.
57060b57cec5SDimitry Andric   if (Ctx.getLangOpts().CPlusPlus17)
57070b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
57080b57cec5SDimitry Andric }
57090b57cec5SDimitry Andric 
57100b57cec5SDimitry Andric /// Mark the template parameters that are used by the given
57110b57cec5SDimitry Andric /// nested name specifier.
57120b57cec5SDimitry Andric static void
57130b57cec5SDimitry Andric MarkUsedTemplateParameters(ASTContext &Ctx,
57140b57cec5SDimitry Andric                            NestedNameSpecifier *NNS,
57150b57cec5SDimitry Andric                            bool OnlyDeduced,
57160b57cec5SDimitry Andric                            unsigned Depth,
57170b57cec5SDimitry Andric                            llvm::SmallBitVector &Used) {
57180b57cec5SDimitry Andric   if (!NNS)
57190b57cec5SDimitry Andric     return;
57200b57cec5SDimitry Andric 
57210b57cec5SDimitry Andric   MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
57220b57cec5SDimitry Andric                              Used);
57230b57cec5SDimitry Andric   MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
57240b57cec5SDimitry Andric                              OnlyDeduced, Depth, Used);
57250b57cec5SDimitry Andric }
57260b57cec5SDimitry Andric 
57270b57cec5SDimitry Andric /// Mark the template parameters that are used by the given
57280b57cec5SDimitry Andric /// template name.
57290b57cec5SDimitry Andric static void
57300b57cec5SDimitry Andric MarkUsedTemplateParameters(ASTContext &Ctx,
57310b57cec5SDimitry Andric                            TemplateName Name,
57320b57cec5SDimitry Andric                            bool OnlyDeduced,
57330b57cec5SDimitry Andric                            unsigned Depth,
57340b57cec5SDimitry Andric                            llvm::SmallBitVector &Used) {
57350b57cec5SDimitry Andric   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
57360b57cec5SDimitry Andric     if (TemplateTemplateParmDecl *TTP
57370b57cec5SDimitry Andric           = dyn_cast<TemplateTemplateParmDecl>(Template)) {
57380b57cec5SDimitry Andric       if (TTP->getDepth() == Depth)
57390b57cec5SDimitry Andric         Used[TTP->getIndex()] = true;
57400b57cec5SDimitry Andric     }
57410b57cec5SDimitry Andric     return;
57420b57cec5SDimitry Andric   }
57430b57cec5SDimitry Andric 
57440b57cec5SDimitry Andric   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
57450b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
57460b57cec5SDimitry Andric                                Depth, Used);
57470b57cec5SDimitry Andric   if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
57480b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
57490b57cec5SDimitry Andric                                Depth, Used);
57500b57cec5SDimitry Andric }
57510b57cec5SDimitry Andric 
57520b57cec5SDimitry Andric /// Mark the template parameters that are used by the given
57530b57cec5SDimitry Andric /// type.
57540b57cec5SDimitry Andric static void
57550b57cec5SDimitry Andric MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
57560b57cec5SDimitry Andric                            bool OnlyDeduced,
57570b57cec5SDimitry Andric                            unsigned Depth,
57580b57cec5SDimitry Andric                            llvm::SmallBitVector &Used) {
57590b57cec5SDimitry Andric   if (T.isNull())
57600b57cec5SDimitry Andric     return;
57610b57cec5SDimitry Andric 
57620b57cec5SDimitry Andric   // Non-dependent types have nothing deducible
57630b57cec5SDimitry Andric   if (!T->isDependentType())
57640b57cec5SDimitry Andric     return;
57650b57cec5SDimitry Andric 
57660b57cec5SDimitry Andric   T = Ctx.getCanonicalType(T);
57670b57cec5SDimitry Andric   switch (T->getTypeClass()) {
57680b57cec5SDimitry Andric   case Type::Pointer:
57690b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx,
57700b57cec5SDimitry Andric                                cast<PointerType>(T)->getPointeeType(),
57710b57cec5SDimitry Andric                                OnlyDeduced,
57720b57cec5SDimitry Andric                                Depth,
57730b57cec5SDimitry Andric                                Used);
57740b57cec5SDimitry Andric     break;
57750b57cec5SDimitry Andric 
57760b57cec5SDimitry Andric   case Type::BlockPointer:
57770b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx,
57780b57cec5SDimitry Andric                                cast<BlockPointerType>(T)->getPointeeType(),
57790b57cec5SDimitry Andric                                OnlyDeduced,
57800b57cec5SDimitry Andric                                Depth,
57810b57cec5SDimitry Andric                                Used);
57820b57cec5SDimitry Andric     break;
57830b57cec5SDimitry Andric 
57840b57cec5SDimitry Andric   case Type::LValueReference:
57850b57cec5SDimitry Andric   case Type::RValueReference:
57860b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx,
57870b57cec5SDimitry Andric                                cast<ReferenceType>(T)->getPointeeType(),
57880b57cec5SDimitry Andric                                OnlyDeduced,
57890b57cec5SDimitry Andric                                Depth,
57900b57cec5SDimitry Andric                                Used);
57910b57cec5SDimitry Andric     break;
57920b57cec5SDimitry Andric 
57930b57cec5SDimitry Andric   case Type::MemberPointer: {
57940b57cec5SDimitry Andric     const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
57950b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
57960b57cec5SDimitry Andric                                Depth, Used);
57970b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
57980b57cec5SDimitry Andric                                OnlyDeduced, Depth, Used);
57990b57cec5SDimitry Andric     break;
58000b57cec5SDimitry Andric   }
58010b57cec5SDimitry Andric 
58020b57cec5SDimitry Andric   case Type::DependentSizedArray:
58030b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx,
58040b57cec5SDimitry Andric                                cast<DependentSizedArrayType>(T)->getSizeExpr(),
58050b57cec5SDimitry Andric                                OnlyDeduced, Depth, Used);
58060b57cec5SDimitry Andric     // Fall through to check the element type
58070b57cec5SDimitry Andric     LLVM_FALLTHROUGH;
58080b57cec5SDimitry Andric 
58090b57cec5SDimitry Andric   case Type::ConstantArray:
58100b57cec5SDimitry Andric   case Type::IncompleteArray:
58110b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx,
58120b57cec5SDimitry Andric                                cast<ArrayType>(T)->getElementType(),
58130b57cec5SDimitry Andric                                OnlyDeduced, Depth, Used);
58140b57cec5SDimitry Andric     break;
58150b57cec5SDimitry Andric 
58160b57cec5SDimitry Andric   case Type::Vector:
58170b57cec5SDimitry Andric   case Type::ExtVector:
58180b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx,
58190b57cec5SDimitry Andric                                cast<VectorType>(T)->getElementType(),
58200b57cec5SDimitry Andric                                OnlyDeduced, Depth, Used);
58210b57cec5SDimitry Andric     break;
58220b57cec5SDimitry Andric 
58230b57cec5SDimitry Andric   case Type::DependentVector: {
58240b57cec5SDimitry Andric     const auto *VecType = cast<DependentVectorType>(T);
58250b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
58260b57cec5SDimitry Andric                                Depth, Used);
58270b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced, Depth,
58280b57cec5SDimitry Andric                                Used);
58290b57cec5SDimitry Andric     break;
58300b57cec5SDimitry Andric   }
58310b57cec5SDimitry Andric   case Type::DependentSizedExtVector: {
58320b57cec5SDimitry Andric     const DependentSizedExtVectorType *VecType
58330b57cec5SDimitry Andric       = cast<DependentSizedExtVectorType>(T);
58340b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
58350b57cec5SDimitry Andric                                Depth, Used);
58360b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
58370b57cec5SDimitry Andric                                Depth, Used);
58380b57cec5SDimitry Andric     break;
58390b57cec5SDimitry Andric   }
58400b57cec5SDimitry Andric 
58410b57cec5SDimitry Andric   case Type::DependentAddressSpace: {
58420b57cec5SDimitry Andric     const DependentAddressSpaceType *DependentASType =
58430b57cec5SDimitry Andric         cast<DependentAddressSpaceType>(T);
58440b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, DependentASType->getPointeeType(),
58450b57cec5SDimitry Andric                                OnlyDeduced, Depth, Used);
58460b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx,
58470b57cec5SDimitry Andric                                DependentASType->getAddrSpaceExpr(),
58480b57cec5SDimitry Andric                                OnlyDeduced, Depth, Used);
58490b57cec5SDimitry Andric     break;
58500b57cec5SDimitry Andric   }
58510b57cec5SDimitry Andric 
58525ffd83dbSDimitry Andric   case Type::ConstantMatrix: {
58535ffd83dbSDimitry Andric     const ConstantMatrixType *MatType = cast<ConstantMatrixType>(T);
58545ffd83dbSDimitry Andric     MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
58555ffd83dbSDimitry Andric                                Depth, Used);
58565ffd83dbSDimitry Andric     break;
58575ffd83dbSDimitry Andric   }
58585ffd83dbSDimitry Andric 
58595ffd83dbSDimitry Andric   case Type::DependentSizedMatrix: {
58605ffd83dbSDimitry Andric     const DependentSizedMatrixType *MatType = cast<DependentSizedMatrixType>(T);
58615ffd83dbSDimitry Andric     MarkUsedTemplateParameters(Ctx, MatType->getElementType(), OnlyDeduced,
58625ffd83dbSDimitry Andric                                Depth, Used);
58635ffd83dbSDimitry Andric     MarkUsedTemplateParameters(Ctx, MatType->getRowExpr(), OnlyDeduced, Depth,
58645ffd83dbSDimitry Andric                                Used);
58655ffd83dbSDimitry Andric     MarkUsedTemplateParameters(Ctx, MatType->getColumnExpr(), OnlyDeduced,
58665ffd83dbSDimitry Andric                                Depth, Used);
58675ffd83dbSDimitry Andric     break;
58685ffd83dbSDimitry Andric   }
58695ffd83dbSDimitry Andric 
58700b57cec5SDimitry Andric   case Type::FunctionProto: {
58710b57cec5SDimitry Andric     const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
58720b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
58730b57cec5SDimitry Andric                                Used);
58740b57cec5SDimitry Andric     for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I) {
58750b57cec5SDimitry Andric       // C++17 [temp.deduct.type]p5:
58760b57cec5SDimitry Andric       //   The non-deduced contexts are: [...]
58770b57cec5SDimitry Andric       //   -- A function parameter pack that does not occur at the end of the
58780b57cec5SDimitry Andric       //      parameter-declaration-list.
58790b57cec5SDimitry Andric       if (!OnlyDeduced || I + 1 == N ||
58800b57cec5SDimitry Andric           !Proto->getParamType(I)->getAs<PackExpansionType>()) {
58810b57cec5SDimitry Andric         MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
58820b57cec5SDimitry Andric                                    Depth, Used);
58830b57cec5SDimitry Andric       } else {
58840b57cec5SDimitry Andric         // FIXME: C++17 [temp.deduct.call]p1:
58850b57cec5SDimitry Andric         //   When a function parameter pack appears in a non-deduced context,
58860b57cec5SDimitry Andric         //   the type of that pack is never deduced.
58870b57cec5SDimitry Andric         //
58880b57cec5SDimitry Andric         // We should also track a set of "never deduced" parameters, and
58890b57cec5SDimitry Andric         // subtract that from the list of deduced parameters after marking.
58900b57cec5SDimitry Andric       }
58910b57cec5SDimitry Andric     }
58920b57cec5SDimitry Andric     if (auto *E = Proto->getNoexceptExpr())
58930b57cec5SDimitry Andric       MarkUsedTemplateParameters(Ctx, E, OnlyDeduced, Depth, Used);
58940b57cec5SDimitry Andric     break;
58950b57cec5SDimitry Andric   }
58960b57cec5SDimitry Andric 
58970b57cec5SDimitry Andric   case Type::TemplateTypeParm: {
58980b57cec5SDimitry Andric     const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
58990b57cec5SDimitry Andric     if (TTP->getDepth() == Depth)
59000b57cec5SDimitry Andric       Used[TTP->getIndex()] = true;
59010b57cec5SDimitry Andric     break;
59020b57cec5SDimitry Andric   }
59030b57cec5SDimitry Andric 
59040b57cec5SDimitry Andric   case Type::SubstTemplateTypeParmPack: {
59050b57cec5SDimitry Andric     const SubstTemplateTypeParmPackType *Subst
59060b57cec5SDimitry Andric       = cast<SubstTemplateTypeParmPackType>(T);
59070b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx,
59080b57cec5SDimitry Andric                                QualType(Subst->getReplacedParameter(), 0),
59090b57cec5SDimitry Andric                                OnlyDeduced, Depth, Used);
59100b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
59110b57cec5SDimitry Andric                                OnlyDeduced, Depth, Used);
59120b57cec5SDimitry Andric     break;
59130b57cec5SDimitry Andric   }
59140b57cec5SDimitry Andric 
59150b57cec5SDimitry Andric   case Type::InjectedClassName:
59160b57cec5SDimitry Andric     T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
59170b57cec5SDimitry Andric     LLVM_FALLTHROUGH;
59180b57cec5SDimitry Andric 
59190b57cec5SDimitry Andric   case Type::TemplateSpecialization: {
59200b57cec5SDimitry Andric     const TemplateSpecializationType *Spec
59210b57cec5SDimitry Andric       = cast<TemplateSpecializationType>(T);
59220b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
59230b57cec5SDimitry Andric                                Depth, Used);
59240b57cec5SDimitry Andric 
59250b57cec5SDimitry Andric     // C++0x [temp.deduct.type]p9:
59260b57cec5SDimitry Andric     //   If the template argument list of P contains a pack expansion that is
59270b57cec5SDimitry Andric     //   not the last template argument, the entire template argument list is a
59280b57cec5SDimitry Andric     //   non-deduced context.
59290b57cec5SDimitry Andric     if (OnlyDeduced &&
59300b57cec5SDimitry Andric         hasPackExpansionBeforeEnd(Spec->template_arguments()))
59310b57cec5SDimitry Andric       break;
59320b57cec5SDimitry Andric 
59330b57cec5SDimitry Andric     for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
59340b57cec5SDimitry Andric       MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
59350b57cec5SDimitry Andric                                  Used);
59360b57cec5SDimitry Andric     break;
59370b57cec5SDimitry Andric   }
59380b57cec5SDimitry Andric 
59390b57cec5SDimitry Andric   case Type::Complex:
59400b57cec5SDimitry Andric     if (!OnlyDeduced)
59410b57cec5SDimitry Andric       MarkUsedTemplateParameters(Ctx,
59420b57cec5SDimitry Andric                                  cast<ComplexType>(T)->getElementType(),
59430b57cec5SDimitry Andric                                  OnlyDeduced, Depth, Used);
59440b57cec5SDimitry Andric     break;
59450b57cec5SDimitry Andric 
59460b57cec5SDimitry Andric   case Type::Atomic:
59470b57cec5SDimitry Andric     if (!OnlyDeduced)
59480b57cec5SDimitry Andric       MarkUsedTemplateParameters(Ctx,
59490b57cec5SDimitry Andric                                  cast<AtomicType>(T)->getValueType(),
59500b57cec5SDimitry Andric                                  OnlyDeduced, Depth, Used);
59510b57cec5SDimitry Andric     break;
59520b57cec5SDimitry Andric 
59530b57cec5SDimitry Andric   case Type::DependentName:
59540b57cec5SDimitry Andric     if (!OnlyDeduced)
59550b57cec5SDimitry Andric       MarkUsedTemplateParameters(Ctx,
59560b57cec5SDimitry Andric                                  cast<DependentNameType>(T)->getQualifier(),
59570b57cec5SDimitry Andric                                  OnlyDeduced, Depth, Used);
59580b57cec5SDimitry Andric     break;
59590b57cec5SDimitry Andric 
59600b57cec5SDimitry Andric   case Type::DependentTemplateSpecialization: {
59610b57cec5SDimitry Andric     // C++14 [temp.deduct.type]p5:
59620b57cec5SDimitry Andric     //   The non-deduced contexts are:
59630b57cec5SDimitry Andric     //     -- The nested-name-specifier of a type that was specified using a
59640b57cec5SDimitry Andric     //        qualified-id
59650b57cec5SDimitry Andric     //
59660b57cec5SDimitry Andric     // C++14 [temp.deduct.type]p6:
59670b57cec5SDimitry Andric     //   When a type name is specified in a way that includes a non-deduced
59680b57cec5SDimitry Andric     //   context, all of the types that comprise that type name are also
59690b57cec5SDimitry Andric     //   non-deduced.
59700b57cec5SDimitry Andric     if (OnlyDeduced)
59710b57cec5SDimitry Andric       break;
59720b57cec5SDimitry Andric 
59730b57cec5SDimitry Andric     const DependentTemplateSpecializationType *Spec
59740b57cec5SDimitry Andric       = cast<DependentTemplateSpecializationType>(T);
59750b57cec5SDimitry Andric 
59760b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
59770b57cec5SDimitry Andric                                OnlyDeduced, Depth, Used);
59780b57cec5SDimitry Andric 
59790b57cec5SDimitry Andric     for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
59800b57cec5SDimitry Andric       MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
59810b57cec5SDimitry Andric                                  Used);
59820b57cec5SDimitry Andric     break;
59830b57cec5SDimitry Andric   }
59840b57cec5SDimitry Andric 
59850b57cec5SDimitry Andric   case Type::TypeOf:
59860b57cec5SDimitry Andric     if (!OnlyDeduced)
59870b57cec5SDimitry Andric       MarkUsedTemplateParameters(Ctx,
59880b57cec5SDimitry Andric                                  cast<TypeOfType>(T)->getUnderlyingType(),
59890b57cec5SDimitry Andric                                  OnlyDeduced, Depth, Used);
59900b57cec5SDimitry Andric     break;
59910b57cec5SDimitry Andric 
59920b57cec5SDimitry Andric   case Type::TypeOfExpr:
59930b57cec5SDimitry Andric     if (!OnlyDeduced)
59940b57cec5SDimitry Andric       MarkUsedTemplateParameters(Ctx,
59950b57cec5SDimitry Andric                                  cast<TypeOfExprType>(T)->getUnderlyingExpr(),
59960b57cec5SDimitry Andric                                  OnlyDeduced, Depth, Used);
59970b57cec5SDimitry Andric     break;
59980b57cec5SDimitry Andric 
59990b57cec5SDimitry Andric   case Type::Decltype:
60000b57cec5SDimitry Andric     if (!OnlyDeduced)
60010b57cec5SDimitry Andric       MarkUsedTemplateParameters(Ctx,
60020b57cec5SDimitry Andric                                  cast<DecltypeType>(T)->getUnderlyingExpr(),
60030b57cec5SDimitry Andric                                  OnlyDeduced, Depth, Used);
60040b57cec5SDimitry Andric     break;
60050b57cec5SDimitry Andric 
60060b57cec5SDimitry Andric   case Type::UnaryTransform:
60070b57cec5SDimitry Andric     if (!OnlyDeduced)
60080b57cec5SDimitry Andric       MarkUsedTemplateParameters(Ctx,
60090b57cec5SDimitry Andric                                  cast<UnaryTransformType>(T)->getUnderlyingType(),
60100b57cec5SDimitry Andric                                  OnlyDeduced, Depth, Used);
60110b57cec5SDimitry Andric     break;
60120b57cec5SDimitry Andric 
60130b57cec5SDimitry Andric   case Type::PackExpansion:
60140b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx,
60150b57cec5SDimitry Andric                                cast<PackExpansionType>(T)->getPattern(),
60160b57cec5SDimitry Andric                                OnlyDeduced, Depth, Used);
60170b57cec5SDimitry Andric     break;
60180b57cec5SDimitry Andric 
60190b57cec5SDimitry Andric   case Type::Auto:
60200b57cec5SDimitry Andric   case Type::DeducedTemplateSpecialization:
60210b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx,
60220b57cec5SDimitry Andric                                cast<DeducedType>(T)->getDeducedType(),
60230b57cec5SDimitry Andric                                OnlyDeduced, Depth, Used);
60240b57cec5SDimitry Andric     break;
60255ffd83dbSDimitry Andric   case Type::DependentExtInt:
60265ffd83dbSDimitry Andric     MarkUsedTemplateParameters(Ctx,
60275ffd83dbSDimitry Andric                                cast<DependentExtIntType>(T)->getNumBitsExpr(),
60285ffd83dbSDimitry Andric                                OnlyDeduced, Depth, Used);
60295ffd83dbSDimitry Andric     break;
60300b57cec5SDimitry Andric 
60310b57cec5SDimitry Andric   // None of these types have any template parameters in them.
60320b57cec5SDimitry Andric   case Type::Builtin:
60330b57cec5SDimitry Andric   case Type::VariableArray:
60340b57cec5SDimitry Andric   case Type::FunctionNoProto:
60350b57cec5SDimitry Andric   case Type::Record:
60360b57cec5SDimitry Andric   case Type::Enum:
60370b57cec5SDimitry Andric   case Type::ObjCInterface:
60380b57cec5SDimitry Andric   case Type::ObjCObject:
60390b57cec5SDimitry Andric   case Type::ObjCObjectPointer:
60400b57cec5SDimitry Andric   case Type::UnresolvedUsing:
60410b57cec5SDimitry Andric   case Type::Pipe:
60425ffd83dbSDimitry Andric   case Type::ExtInt:
60430b57cec5SDimitry Andric #define TYPE(Class, Base)
60440b57cec5SDimitry Andric #define ABSTRACT_TYPE(Class, Base)
60450b57cec5SDimitry Andric #define DEPENDENT_TYPE(Class, Base)
60460b57cec5SDimitry Andric #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6047a7dea167SDimitry Andric #include "clang/AST/TypeNodes.inc"
60480b57cec5SDimitry Andric     break;
60490b57cec5SDimitry Andric   }
60500b57cec5SDimitry Andric }
60510b57cec5SDimitry Andric 
60520b57cec5SDimitry Andric /// Mark the template parameters that are used by this
60530b57cec5SDimitry Andric /// template argument.
60540b57cec5SDimitry Andric static void
60550b57cec5SDimitry Andric MarkUsedTemplateParameters(ASTContext &Ctx,
60560b57cec5SDimitry Andric                            const TemplateArgument &TemplateArg,
60570b57cec5SDimitry Andric                            bool OnlyDeduced,
60580b57cec5SDimitry Andric                            unsigned Depth,
60590b57cec5SDimitry Andric                            llvm::SmallBitVector &Used) {
60600b57cec5SDimitry Andric   switch (TemplateArg.getKind()) {
60610b57cec5SDimitry Andric   case TemplateArgument::Null:
60620b57cec5SDimitry Andric   case TemplateArgument::Integral:
60630b57cec5SDimitry Andric   case TemplateArgument::Declaration:
60640b57cec5SDimitry Andric     break;
60650b57cec5SDimitry Andric 
60660b57cec5SDimitry Andric   case TemplateArgument::NullPtr:
60670b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
60680b57cec5SDimitry Andric                                Depth, Used);
60690b57cec5SDimitry Andric     break;
60700b57cec5SDimitry Andric 
60710b57cec5SDimitry Andric   case TemplateArgument::Type:
60720b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
60730b57cec5SDimitry Andric                                Depth, Used);
60740b57cec5SDimitry Andric     break;
60750b57cec5SDimitry Andric 
60760b57cec5SDimitry Andric   case TemplateArgument::Template:
60770b57cec5SDimitry Andric   case TemplateArgument::TemplateExpansion:
60780b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx,
60790b57cec5SDimitry Andric                                TemplateArg.getAsTemplateOrTemplatePattern(),
60800b57cec5SDimitry Andric                                OnlyDeduced, Depth, Used);
60810b57cec5SDimitry Andric     break;
60820b57cec5SDimitry Andric 
60830b57cec5SDimitry Andric   case TemplateArgument::Expression:
60840b57cec5SDimitry Andric     MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
60850b57cec5SDimitry Andric                                Depth, Used);
60860b57cec5SDimitry Andric     break;
60870b57cec5SDimitry Andric 
60880b57cec5SDimitry Andric   case TemplateArgument::Pack:
60890b57cec5SDimitry Andric     for (const auto &P : TemplateArg.pack_elements())
60900b57cec5SDimitry Andric       MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
60910b57cec5SDimitry Andric     break;
60920b57cec5SDimitry Andric   }
60930b57cec5SDimitry Andric }
60940b57cec5SDimitry Andric 
6095480093f4SDimitry Andric /// Mark which template parameters are used in a given expression.
6096480093f4SDimitry Andric ///
6097480093f4SDimitry Andric /// \param E the expression from which template parameters will be deduced.
6098480093f4SDimitry Andric ///
6099480093f4SDimitry Andric /// \param Used a bit vector whose elements will be set to \c true
6100480093f4SDimitry Andric /// to indicate when the corresponding template parameter will be
6101480093f4SDimitry Andric /// deduced.
6102480093f4SDimitry Andric void
6103480093f4SDimitry Andric Sema::MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
6104480093f4SDimitry Andric                                  unsigned Depth,
6105480093f4SDimitry Andric                                  llvm::SmallBitVector &Used) {
6106480093f4SDimitry Andric   ::MarkUsedTemplateParameters(Context, E, OnlyDeduced, Depth, Used);
6107480093f4SDimitry Andric }
6108480093f4SDimitry Andric 
61090b57cec5SDimitry Andric /// Mark which template parameters can be deduced from a given
61100b57cec5SDimitry Andric /// template argument list.
61110b57cec5SDimitry Andric ///
61120b57cec5SDimitry Andric /// \param TemplateArgs the template argument list from which template
61130b57cec5SDimitry Andric /// parameters will be deduced.
61140b57cec5SDimitry Andric ///
61150b57cec5SDimitry Andric /// \param Used a bit vector whose elements will be set to \c true
61160b57cec5SDimitry Andric /// to indicate when the corresponding template parameter will be
61170b57cec5SDimitry Andric /// deduced.
61180b57cec5SDimitry Andric void
61190b57cec5SDimitry Andric Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
61200b57cec5SDimitry Andric                                  bool OnlyDeduced, unsigned Depth,
61210b57cec5SDimitry Andric                                  llvm::SmallBitVector &Used) {
61220b57cec5SDimitry Andric   // C++0x [temp.deduct.type]p9:
61230b57cec5SDimitry Andric   //   If the template argument list of P contains a pack expansion that is not
61240b57cec5SDimitry Andric   //   the last template argument, the entire template argument list is a
61250b57cec5SDimitry Andric   //   non-deduced context.
61260b57cec5SDimitry Andric   if (OnlyDeduced &&
61270b57cec5SDimitry Andric       hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
61280b57cec5SDimitry Andric     return;
61290b57cec5SDimitry Andric 
61300b57cec5SDimitry Andric   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
61310b57cec5SDimitry Andric     ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
61320b57cec5SDimitry Andric                                  Depth, Used);
61330b57cec5SDimitry Andric }
61340b57cec5SDimitry Andric 
61350b57cec5SDimitry Andric /// Marks all of the template parameters that will be deduced by a
61360b57cec5SDimitry Andric /// call to the given function template.
61370b57cec5SDimitry Andric void Sema::MarkDeducedTemplateParameters(
61380b57cec5SDimitry Andric     ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
61390b57cec5SDimitry Andric     llvm::SmallBitVector &Deduced) {
61400b57cec5SDimitry Andric   TemplateParameterList *TemplateParams
61410b57cec5SDimitry Andric     = FunctionTemplate->getTemplateParameters();
61420b57cec5SDimitry Andric   Deduced.clear();
61430b57cec5SDimitry Andric   Deduced.resize(TemplateParams->size());
61440b57cec5SDimitry Andric 
61450b57cec5SDimitry Andric   FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
61460b57cec5SDimitry Andric   for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
61470b57cec5SDimitry Andric     ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
61480b57cec5SDimitry Andric                                  true, TemplateParams->getDepth(), Deduced);
61490b57cec5SDimitry Andric }
61500b57cec5SDimitry Andric 
61510b57cec5SDimitry Andric bool hasDeducibleTemplateParameters(Sema &S,
61520b57cec5SDimitry Andric                                     FunctionTemplateDecl *FunctionTemplate,
61530b57cec5SDimitry Andric                                     QualType T) {
61540b57cec5SDimitry Andric   if (!T->isDependentType())
61550b57cec5SDimitry Andric     return false;
61560b57cec5SDimitry Andric 
61570b57cec5SDimitry Andric   TemplateParameterList *TemplateParams
61580b57cec5SDimitry Andric     = FunctionTemplate->getTemplateParameters();
61590b57cec5SDimitry Andric   llvm::SmallBitVector Deduced(TemplateParams->size());
61600b57cec5SDimitry Andric   ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
61610b57cec5SDimitry Andric                                Deduced);
61620b57cec5SDimitry Andric 
61630b57cec5SDimitry Andric   return Deduced.any();
61640b57cec5SDimitry Andric }
6165