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