Coverage Report

Created: 2024-01-17 10:31

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