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