1 //===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===/
9 // This file implements C++ template argument deduction.
11 //===----------------------------------------------------------------------===/
13 #include "clang/Sema/TemplateDeduction.h"
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/StmtVisitor.h"
22 #include "clang/AST/TypeOrdering.h"
23 #include "clang/Sema/DeclSpec.h"
24 #include "clang/Sema/Sema.h"
25 #include "clang/Sema/Template.h"
26 #include "llvm/ADT/SmallBitVector.h"
31 /// \brief Various flags that control template argument deduction.
33 /// These flags can be bitwise-OR'd together.
34 enum TemplateDeductionFlags {
35 /// \brief No template argument deduction flags, which indicates the
36 /// strictest results for template argument deduction (as used for, e.g.,
37 /// matching class template partial specializations).
39 /// \brief Within template argument deduction from a function call, we are
40 /// matching with a parameter type for which the original parameter was
42 TDF_ParamWithReferenceType = 0x1,
43 /// \brief Within template argument deduction from a function call, we
44 /// are matching in a case where we ignore cv-qualifiers.
45 TDF_IgnoreQualifiers = 0x02,
46 /// \brief Within template argument deduction from a function call,
47 /// we are matching in a case where we can perform template argument
48 /// deduction from a template-id of a derived class of the argument type.
49 TDF_DerivedClass = 0x04,
50 /// \brief Allow non-dependent types to differ, e.g., when performing
51 /// template argument deduction from a function call where conversions
53 TDF_SkipNonDependent = 0x08,
54 /// \brief Whether we are performing template argument deduction for
55 /// parameters and arguments in a top-level template argument
56 TDF_TopLevelParameterTypeList = 0x10,
57 /// \brief Within template argument deduction from overload resolution per
58 /// C++ [over.over] allow matching function types that are compatible in
59 /// terms of noreturn and default calling convention adjustments.
60 TDF_InOverloadResolution = 0x20
64 using namespace clang;
66 /// \brief Compare two APSInts, extending and switching the sign as
67 /// necessary to compare their values regardless of underlying type.
68 static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
69 if (Y.getBitWidth() > X.getBitWidth())
70 X = X.extend(Y.getBitWidth());
71 else if (Y.getBitWidth() < X.getBitWidth())
72 Y = Y.extend(X.getBitWidth());
74 // If there is a signedness mismatch, correct it.
75 if (X.isSigned() != Y.isSigned()) {
76 // If the signed value is negative, then the values cannot be the same.
77 if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
87 static Sema::TemplateDeductionResult
88 DeduceTemplateArguments(Sema &S,
89 TemplateParameterList *TemplateParams,
90 const TemplateArgument &Param,
92 TemplateDeductionInfo &Info,
93 SmallVectorImpl<DeducedTemplateArgument> &Deduced);
95 static Sema::TemplateDeductionResult
96 DeduceTemplateArgumentsByTypeMatch(Sema &S,
97 TemplateParameterList *TemplateParams,
100 TemplateDeductionInfo &Info,
101 SmallVectorImpl<DeducedTemplateArgument> &
104 bool PartialOrdering = false,
105 bool DeducedFromArrayBound = false);
107 static Sema::TemplateDeductionResult
108 DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
109 ArrayRef<TemplateArgument> Params,
110 ArrayRef<TemplateArgument> Args,
111 TemplateDeductionInfo &Info,
112 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
113 bool NumberOfArgumentsMustMatch);
115 static void MarkUsedTemplateParameters(ASTContext &Ctx,
116 const TemplateArgument &TemplateArg,
117 bool OnlyDeduced, unsigned Depth,
118 llvm::SmallBitVector &Used);
120 static void MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
121 bool OnlyDeduced, unsigned Level,
122 llvm::SmallBitVector &Deduced);
124 /// \brief If the given expression is of a form that permits the deduction
125 /// of a non-type template parameter, return the declaration of that
126 /// non-type template parameter.
127 static NonTypeTemplateParmDecl *
128 getDeducedParameterFromExpr(TemplateDeductionInfo &Info, Expr *E) {
129 // If we are within an alias template, the expression may have undergone
130 // any number of parameter substitutions already.
132 if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
133 E = IC->getSubExpr();
134 else if (SubstNonTypeTemplateParmExpr *Subst =
135 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
136 E = Subst->getReplacement();
141 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
142 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
143 if (NTTP->getDepth() == Info.getDeducedDepth())
149 /// \brief Determine whether two declaration pointers refer to the same
151 static bool isSameDeclaration(Decl *X, Decl *Y) {
152 if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
153 X = NX->getUnderlyingDecl();
154 if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
155 Y = NY->getUnderlyingDecl();
157 return X->getCanonicalDecl() == Y->getCanonicalDecl();
160 /// \brief Verify that the given, deduced template arguments are compatible.
162 /// \returns The deduced template argument, or a NULL template argument if
163 /// the deduced template arguments were incompatible.
164 static DeducedTemplateArgument
165 checkDeducedTemplateArguments(ASTContext &Context,
166 const DeducedTemplateArgument &X,
167 const DeducedTemplateArgument &Y) {
168 // We have no deduction for one or both of the arguments; they're compatible.
174 // If we have two non-type template argument values deduced for the same
175 // parameter, they must both match the type of the parameter, and thus must
176 // match each other's type. As we're only keeping one of them, we must check
177 // for that now. The exception is that if either was deduced from an array
178 // bound, the type is permitted to differ.
179 if (!X.wasDeducedFromArrayBound() && !Y.wasDeducedFromArrayBound()) {
180 QualType XType = X.getNonTypeTemplateArgumentType();
181 if (!XType.isNull()) {
182 QualType YType = Y.getNonTypeTemplateArgumentType();
183 if (YType.isNull() || !Context.hasSameType(XType, YType))
184 return DeducedTemplateArgument();
188 switch (X.getKind()) {
189 case TemplateArgument::Null:
190 llvm_unreachable("Non-deduced template arguments handled above");
192 case TemplateArgument::Type:
193 // If two template type arguments have the same type, they're compatible.
194 if (Y.getKind() == TemplateArgument::Type &&
195 Context.hasSameType(X.getAsType(), Y.getAsType()))
198 // If one of the two arguments was deduced from an array bound, the other
200 if (X.wasDeducedFromArrayBound() != Y.wasDeducedFromArrayBound())
201 return X.wasDeducedFromArrayBound() ? Y : X;
203 // The arguments are not compatible.
204 return DeducedTemplateArgument();
206 case TemplateArgument::Integral:
207 // If we deduced a constant in one case and either a dependent expression or
208 // declaration in another case, keep the integral constant.
209 // If both are integral constants with the same value, keep that value.
210 if (Y.getKind() == TemplateArgument::Expression ||
211 Y.getKind() == TemplateArgument::Declaration ||
212 (Y.getKind() == TemplateArgument::Integral &&
213 hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral())))
214 return X.wasDeducedFromArrayBound() ? Y : X;
216 // All other combinations are incompatible.
217 return DeducedTemplateArgument();
219 case TemplateArgument::Template:
220 if (Y.getKind() == TemplateArgument::Template &&
221 Context.hasSameTemplateName(X.getAsTemplate(), Y.getAsTemplate()))
224 // All other combinations are incompatible.
225 return DeducedTemplateArgument();
227 case TemplateArgument::TemplateExpansion:
228 if (Y.getKind() == TemplateArgument::TemplateExpansion &&
229 Context.hasSameTemplateName(X.getAsTemplateOrTemplatePattern(),
230 Y.getAsTemplateOrTemplatePattern()))
233 // All other combinations are incompatible.
234 return DeducedTemplateArgument();
236 case TemplateArgument::Expression: {
237 if (Y.getKind() != TemplateArgument::Expression)
238 return checkDeducedTemplateArguments(Context, Y, X);
240 // Compare the expressions for equality
241 llvm::FoldingSetNodeID ID1, ID2;
242 X.getAsExpr()->Profile(ID1, Context, true);
243 Y.getAsExpr()->Profile(ID2, Context, true);
245 return X.wasDeducedFromArrayBound() ? Y : X;
247 // Differing dependent expressions are incompatible.
248 return DeducedTemplateArgument();
251 case TemplateArgument::Declaration:
252 assert(!X.wasDeducedFromArrayBound());
254 // If we deduced a declaration and a dependent expression, keep the
256 if (Y.getKind() == TemplateArgument::Expression)
259 // If we deduced a declaration and an integral constant, keep the
260 // integral constant and whichever type did not come from an array
262 if (Y.getKind() == TemplateArgument::Integral) {
263 if (Y.wasDeducedFromArrayBound())
264 return TemplateArgument(Context, Y.getAsIntegral(),
265 X.getParamTypeForDecl());
269 // If we deduced two declarations, make sure they they refer to the
271 if (Y.getKind() == TemplateArgument::Declaration &&
272 isSameDeclaration(X.getAsDecl(), Y.getAsDecl()))
275 // All other combinations are incompatible.
276 return DeducedTemplateArgument();
278 case TemplateArgument::NullPtr:
279 // If we deduced a null pointer and a dependent expression, keep the
281 if (Y.getKind() == TemplateArgument::Expression)
284 // If we deduced a null pointer and an integral constant, keep the
285 // integral constant.
286 if (Y.getKind() == TemplateArgument::Integral)
289 // If we deduced two null pointers, they are the same.
290 if (Y.getKind() == TemplateArgument::NullPtr)
293 // All other combinations are incompatible.
294 return DeducedTemplateArgument();
296 case TemplateArgument::Pack:
297 if (Y.getKind() != TemplateArgument::Pack ||
298 X.pack_size() != Y.pack_size())
299 return DeducedTemplateArgument();
301 llvm::SmallVector<TemplateArgument, 8> NewPack;
302 for (TemplateArgument::pack_iterator XA = X.pack_begin(),
303 XAEnd = X.pack_end(),
305 XA != XAEnd; ++XA, ++YA) {
306 TemplateArgument Merged = checkDeducedTemplateArguments(
307 Context, DeducedTemplateArgument(*XA, X.wasDeducedFromArrayBound()),
308 DeducedTemplateArgument(*YA, Y.wasDeducedFromArrayBound()));
310 return DeducedTemplateArgument();
311 NewPack.push_back(Merged);
314 return DeducedTemplateArgument(
315 TemplateArgument::CreatePackCopy(Context, NewPack),
316 X.wasDeducedFromArrayBound() && Y.wasDeducedFromArrayBound());
319 llvm_unreachable("Invalid TemplateArgument Kind!");
322 /// \brief Deduce the value of the given non-type template parameter
323 /// as the given deduced template argument. All non-type template parameter
324 /// deduction is funneled through here.
325 static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
326 Sema &S, TemplateParameterList *TemplateParams,
327 NonTypeTemplateParmDecl *NTTP, const DeducedTemplateArgument &NewDeduced,
328 QualType ValueType, TemplateDeductionInfo &Info,
329 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
330 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
331 "deducing non-type template argument with wrong depth");
333 DeducedTemplateArgument Result = checkDeducedTemplateArguments(
334 S.Context, Deduced[NTTP->getIndex()], NewDeduced);
335 if (Result.isNull()) {
337 Info.FirstArg = Deduced[NTTP->getIndex()];
338 Info.SecondArg = NewDeduced;
339 return Sema::TDK_Inconsistent;
342 Deduced[NTTP->getIndex()] = Result;
343 if (!S.getLangOpts().CPlusPlus1z)
344 return Sema::TDK_Success;
346 if (NTTP->isExpandedParameterPack())
347 // FIXME: We may still need to deduce parts of the type here! But we
348 // don't have any way to find which slice of the type to use, and the
349 // type stored on the NTTP itself is nonsense. Perhaps the type of an
350 // expanded NTTP should be a pack expansion type?
351 return Sema::TDK_Success;
353 // Get the type of the parameter for deduction.
354 QualType ParamType = NTTP->getType();
355 if (auto *Expansion = dyn_cast<PackExpansionType>(ParamType))
356 ParamType = Expansion->getPattern();
358 // FIXME: It's not clear how deduction of a parameter of reference
359 // type from an argument (of non-reference type) should be performed.
360 // For now, we just remove reference types from both sides and let
361 // the final check for matching types sort out the mess.
362 return DeduceTemplateArgumentsByTypeMatch(
363 S, TemplateParams, ParamType.getNonReferenceType(),
364 ValueType.getNonReferenceType(), Info, Deduced, TDF_SkipNonDependent,
365 /*PartialOrdering=*/false,
366 /*ArrayBound=*/NewDeduced.wasDeducedFromArrayBound());
369 /// \brief Deduce the value of the given non-type template parameter
370 /// from the given integral constant.
371 static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
372 Sema &S, TemplateParameterList *TemplateParams,
373 NonTypeTemplateParmDecl *NTTP, const llvm::APSInt &Value,
374 QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info,
375 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
376 return DeduceNonTypeTemplateArgument(
377 S, TemplateParams, NTTP,
378 DeducedTemplateArgument(S.Context, Value, ValueType,
379 DeducedFromArrayBound),
380 ValueType, Info, Deduced);
383 /// \brief Deduce the value of the given non-type template parameter
384 /// from the given null pointer template argument type.
385 static Sema::TemplateDeductionResult DeduceNullPtrTemplateArgument(
386 Sema &S, TemplateParameterList *TemplateParams,
387 NonTypeTemplateParmDecl *NTTP, QualType NullPtrType,
388 TemplateDeductionInfo &Info,
389 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
391 S.ImpCastExprToType(new (S.Context) CXXNullPtrLiteralExpr(
392 S.Context.NullPtrTy, NTTP->getLocation()),
393 NullPtrType, CK_NullToPointer)
395 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
396 DeducedTemplateArgument(Value),
397 Value->getType(), Info, Deduced);
400 /// \brief Deduce the value of the given non-type template parameter
401 /// from the given type- or value-dependent expression.
403 /// \returns true if deduction succeeded, false otherwise.
404 static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
405 Sema &S, TemplateParameterList *TemplateParams,
406 NonTypeTemplateParmDecl *NTTP, Expr *Value, TemplateDeductionInfo &Info,
407 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
408 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
409 DeducedTemplateArgument(Value),
410 Value->getType(), Info, Deduced);
413 /// \brief Deduce the value of the given non-type template parameter
414 /// from the given declaration.
416 /// \returns true if deduction succeeded, false otherwise.
417 static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(
418 Sema &S, TemplateParameterList *TemplateParams,
419 NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
420 TemplateDeductionInfo &Info,
421 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
422 D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
423 TemplateArgument New(D, T);
424 return DeduceNonTypeTemplateArgument(
425 S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
428 static Sema::TemplateDeductionResult
429 DeduceTemplateArguments(Sema &S,
430 TemplateParameterList *TemplateParams,
433 TemplateDeductionInfo &Info,
434 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
435 TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
437 // The parameter type is dependent and is not a template template parameter,
438 // so there is nothing that we can deduce.
439 return Sema::TDK_Success;
442 if (TemplateTemplateParmDecl *TempParam
443 = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
444 // If we're not deducing at this depth, there's nothing to deduce.
445 if (TempParam->getDepth() != Info.getDeducedDepth())
446 return Sema::TDK_Success;
448 DeducedTemplateArgument NewDeduced(S.Context.getCanonicalTemplateName(Arg));
449 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
450 Deduced[TempParam->getIndex()],
452 if (Result.isNull()) {
453 Info.Param = TempParam;
454 Info.FirstArg = Deduced[TempParam->getIndex()];
455 Info.SecondArg = NewDeduced;
456 return Sema::TDK_Inconsistent;
459 Deduced[TempParam->getIndex()] = Result;
460 return Sema::TDK_Success;
463 // Verify that the two template names are equivalent.
464 if (S.Context.hasSameTemplateName(Param, Arg))
465 return Sema::TDK_Success;
467 // Mismatch of non-dependent template parameter to argument.
468 Info.FirstArg = TemplateArgument(Param);
469 Info.SecondArg = TemplateArgument(Arg);
470 return Sema::TDK_NonDeducedMismatch;
473 /// \brief Deduce the template arguments by comparing the template parameter
474 /// type (which is a template-id) with the template argument type.
476 /// \param S the Sema
478 /// \param TemplateParams the template parameters that we are deducing
480 /// \param Param the parameter type
482 /// \param Arg the argument type
484 /// \param Info information about the template argument deduction itself
486 /// \param Deduced the deduced template arguments
488 /// \returns the result of template argument deduction so far. Note that a
489 /// "success" result means that template argument deduction has not yet failed,
490 /// but it may still fail, later, for other reasons.
491 static Sema::TemplateDeductionResult
492 DeduceTemplateArguments(Sema &S,
493 TemplateParameterList *TemplateParams,
494 const TemplateSpecializationType *Param,
496 TemplateDeductionInfo &Info,
497 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
498 assert(Arg.isCanonical() && "Argument type must be canonical");
500 // Check whether the template argument is a dependent template-id.
501 if (const TemplateSpecializationType *SpecArg
502 = dyn_cast<TemplateSpecializationType>(Arg)) {
503 // Perform template argument deduction for the template name.
504 if (Sema::TemplateDeductionResult Result
505 = DeduceTemplateArguments(S, TemplateParams,
506 Param->getTemplateName(),
507 SpecArg->getTemplateName(),
512 // Perform template argument deduction on each template
513 // argument. Ignore any missing/extra arguments, since they could be
514 // filled in by default arguments.
515 return DeduceTemplateArguments(S, TemplateParams,
516 Param->template_arguments(),
517 SpecArg->template_arguments(), Info, Deduced,
518 /*NumberOfArgumentsMustMatch=*/false);
521 // If the argument type is a class template specialization, we
522 // perform template argument deduction using its template
524 const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
526 Info.FirstArg = TemplateArgument(QualType(Param, 0));
527 Info.SecondArg = TemplateArgument(Arg);
528 return Sema::TDK_NonDeducedMismatch;
531 ClassTemplateSpecializationDecl *SpecArg
532 = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
534 Info.FirstArg = TemplateArgument(QualType(Param, 0));
535 Info.SecondArg = TemplateArgument(Arg);
536 return Sema::TDK_NonDeducedMismatch;
539 // Perform template argument deduction for the template name.
540 if (Sema::TemplateDeductionResult Result
541 = DeduceTemplateArguments(S,
543 Param->getTemplateName(),
544 TemplateName(SpecArg->getSpecializedTemplate()),
548 // Perform template argument deduction for the template arguments.
549 return DeduceTemplateArguments(S, TemplateParams, Param->template_arguments(),
550 SpecArg->getTemplateArgs().asArray(), Info,
551 Deduced, /*NumberOfArgumentsMustMatch=*/true);
554 /// \brief Determines whether the given type is an opaque type that
555 /// might be more qualified when instantiated.
556 static bool IsPossiblyOpaquelyQualifiedType(QualType T) {
557 switch (T->getTypeClass()) {
558 case Type::TypeOfExpr:
560 case Type::DependentName:
562 case Type::UnresolvedUsing:
563 case Type::TemplateTypeParm:
566 case Type::ConstantArray:
567 case Type::IncompleteArray:
568 case Type::VariableArray:
569 case Type::DependentSizedArray:
570 return IsPossiblyOpaquelyQualifiedType(
571 cast<ArrayType>(T)->getElementType());
578 /// \brief Retrieve the depth and index of a template parameter.
579 static std::pair<unsigned, unsigned>
580 getDepthAndIndex(NamedDecl *ND) {
581 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
582 return std::make_pair(TTP->getDepth(), TTP->getIndex());
584 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
585 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
587 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
588 return std::make_pair(TTP->getDepth(), TTP->getIndex());
591 /// \brief Retrieve the depth and index of an unexpanded parameter pack.
592 static std::pair<unsigned, unsigned>
593 getDepthAndIndex(UnexpandedParameterPack UPP) {
594 if (const TemplateTypeParmType *TTP
595 = UPP.first.dyn_cast<const TemplateTypeParmType *>())
596 return std::make_pair(TTP->getDepth(), TTP->getIndex());
598 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
601 /// \brief Helper function to build a TemplateParameter when we don't
602 /// know its type statically.
603 static TemplateParameter makeTemplateParameter(Decl *D) {
604 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
605 return TemplateParameter(TTP);
606 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
607 return TemplateParameter(NTTP);
609 return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
612 /// A pack that we're currently deducing.
613 struct clang::DeducedPack {
614 DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
616 // The index of the pack.
619 // The old value of the pack before we started deducing it.
620 DeducedTemplateArgument Saved;
622 // A deferred value of this pack from an inner deduction, that couldn't be
623 // deduced because this deduction hadn't happened yet.
624 DeducedTemplateArgument DeferredDeduction;
626 // The new value of the pack.
627 SmallVector<DeducedTemplateArgument, 4> New;
629 // The outer deduction for this pack, if any.
634 /// A scope in which we're performing pack deduction.
635 class PackDeductionScope {
637 PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
638 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
639 TemplateDeductionInfo &Info, TemplateArgument Pattern)
640 : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
641 // Dig out the partially-substituted pack, if there is one.
642 const TemplateArgument *PartialPackArgs = nullptr;
643 unsigned NumPartialPackArgs = 0;
644 std::pair<unsigned, unsigned> PartialPackDepthIndex(-1u, -1u);
645 if (auto *Scope = S.CurrentInstantiationScope)
646 if (auto *Partial = Scope->getPartiallySubstitutedPack(
647 &PartialPackArgs, &NumPartialPackArgs))
648 PartialPackDepthIndex = getDepthAndIndex(Partial);
650 // Compute the set of template parameter indices that correspond to
651 // parameter packs expanded by the pack expansion.
653 llvm::SmallBitVector SawIndices(TemplateParams->size());
655 auto AddPack = [&](unsigned Index) {
656 if (SawIndices[Index])
658 SawIndices[Index] = true;
660 // Save the deduced template argument for the parameter pack expanded
661 // by this pack expansion, then clear out the deduction.
662 DeducedPack Pack(Index);
663 Pack.Saved = Deduced[Index];
664 Deduced[Index] = TemplateArgument();
666 Packs.push_back(Pack);
669 // First look for unexpanded packs in the pattern.
670 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
671 S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
672 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
673 unsigned Depth, Index;
674 std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
675 if (Depth == Info.getDeducedDepth())
678 assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
680 // This pack expansion will have been partially expanded iff the only
681 // unexpanded parameter pack within it is the partially-substituted pack.
682 IsPartiallyExpanded =
684 PartialPackDepthIndex ==
685 std::make_pair(Info.getDeducedDepth(), Packs.front().Index);
687 // Skip over the pack elements that were expanded into separate arguments.
688 if (IsPartiallyExpanded)
689 PackElements += NumPartialPackArgs;
691 // We can also have deduced template parameters that do not actually
692 // appear in the pattern, but can be deduced by it (the type of a non-type
693 // template parameter pack, in particular). These won't have prevented us
694 // from partially expanding the pack.
695 llvm::SmallBitVector Used(TemplateParams->size());
696 MarkUsedTemplateParameters(S.Context, Pattern, /*OnlyDeduced*/true,
697 Info.getDeducedDepth(), Used);
698 for (int Index = Used.find_first(); Index != -1;
699 Index = Used.find_next(Index))
700 if (TemplateParams->getParam(Index)->isParameterPack())
704 for (auto &Pack : Packs) {
705 if (Info.PendingDeducedPacks.size() > Pack.Index)
706 Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
708 Info.PendingDeducedPacks.resize(Pack.Index + 1);
709 Info.PendingDeducedPacks[Pack.Index] = &Pack;
711 if (PartialPackDepthIndex ==
712 std::make_pair(Info.getDeducedDepth(), Pack.Index)) {
713 Pack.New.append(PartialPackArgs, PartialPackArgs + NumPartialPackArgs);
714 // We pre-populate the deduced value of the partially-substituted
715 // pack with the specified value. This is not entirely correct: the
716 // value is supposed to have been substituted, not deduced, but the
717 // cases where this is observable require an exact type match anyway.
719 // FIXME: If we could represent a "depth i, index j, pack elem k"
720 // parameter, we could substitute the partially-substituted pack
721 // everywhere and avoid this.
722 if (Pack.New.size() > PackElements)
723 Deduced[Pack.Index] = Pack.New[PackElements];
728 ~PackDeductionScope() {
729 for (auto &Pack : Packs)
730 Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
733 /// Determine whether this pack has already been partially expanded into a
734 /// sequence of (prior) function parameters / template arguments.
735 bool isPartiallyExpanded() { return IsPartiallyExpanded; }
737 /// Move to deducing the next element in each pack that is being deduced.
738 void nextPackElement() {
739 // Capture the deduced template arguments for each parameter pack expanded
740 // by this pack expansion, add them to the list of arguments we've deduced
741 // for that pack, then clear out the deduced argument.
742 for (auto &Pack : Packs) {
743 DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
744 if (!Pack.New.empty() || !DeducedArg.isNull()) {
745 while (Pack.New.size() < PackElements)
746 Pack.New.push_back(DeducedTemplateArgument());
747 if (Pack.New.size() == PackElements)
748 Pack.New.push_back(DeducedArg);
750 Pack.New[PackElements] = DeducedArg;
751 DeducedArg = Pack.New.size() > PackElements + 1
752 ? Pack.New[PackElements + 1]
753 : DeducedTemplateArgument();
759 /// \brief Finish template argument deduction for a set of argument packs,
760 /// producing the argument packs and checking for consistency with prior
762 Sema::TemplateDeductionResult finish() {
763 // Build argument packs for each of the parameter packs expanded by this
765 for (auto &Pack : Packs) {
766 // Put back the old value for this pack.
767 Deduced[Pack.Index] = Pack.Saved;
769 // Build or find a new value for this pack.
770 DeducedTemplateArgument NewPack;
771 if (PackElements && Pack.New.empty()) {
772 if (Pack.DeferredDeduction.isNull()) {
773 // We were not able to deduce anything for this parameter pack
774 // (because it only appeared in non-deduced contexts), so just
775 // restore the saved argument pack.
779 NewPack = Pack.DeferredDeduction;
780 Pack.DeferredDeduction = TemplateArgument();
781 } else if (Pack.New.empty()) {
782 // If we deduced an empty argument pack, create it now.
783 NewPack = DeducedTemplateArgument(TemplateArgument::getEmptyPack());
785 TemplateArgument *ArgumentPack =
786 new (S.Context) TemplateArgument[Pack.New.size()];
787 std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
788 NewPack = DeducedTemplateArgument(
789 TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
790 // FIXME: This is wrong, it's possible that some pack elements are
791 // deduced from an array bound and others are not:
792 // template<typename ...T, T ...V> void g(const T (&...p)[V]);
793 // g({1, 2, 3}, {{}, {}});
794 // ... should deduce T = {int, size_t (from array bound)}.
795 Pack.New[0].wasDeducedFromArrayBound());
798 // Pick where we're going to put the merged pack.
799 DeducedTemplateArgument *Loc;
801 if (Pack.Outer->DeferredDeduction.isNull()) {
802 // Defer checking this pack until we have a complete pack to compare
804 Pack.Outer->DeferredDeduction = NewPack;
807 Loc = &Pack.Outer->DeferredDeduction;
809 Loc = &Deduced[Pack.Index];
812 // Check the new pack matches any previous value.
813 DeducedTemplateArgument OldPack = *Loc;
814 DeducedTemplateArgument Result =
815 checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
817 // If we deferred a deduction of this pack, check that one now too.
818 if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
820 NewPack = Pack.DeferredDeduction;
821 Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
824 if (Result.isNull()) {
826 makeTemplateParameter(TemplateParams->getParam(Pack.Index));
827 Info.FirstArg = OldPack;
828 Info.SecondArg = NewPack;
829 return Sema::TDK_Inconsistent;
835 return Sema::TDK_Success;
840 TemplateParameterList *TemplateParams;
841 SmallVectorImpl<DeducedTemplateArgument> &Deduced;
842 TemplateDeductionInfo &Info;
843 unsigned PackElements = 0;
844 bool IsPartiallyExpanded = false;
846 SmallVector<DeducedPack, 2> Packs;
850 /// \brief Deduce the template arguments by comparing the list of parameter
851 /// types to the list of argument types, as in the parameter-type-lists of
852 /// function types (C++ [temp.deduct.type]p10).
854 /// \param S The semantic analysis object within which we are deducing
856 /// \param TemplateParams The template parameters that we are deducing
858 /// \param Params The list of parameter types
860 /// \param NumParams The number of types in \c Params
862 /// \param Args The list of argument types
864 /// \param NumArgs The number of types in \c Args
866 /// \param Info information about the template argument deduction itself
868 /// \param Deduced the deduced template arguments
870 /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
871 /// how template argument deduction is performed.
873 /// \param PartialOrdering If true, we are performing template argument
874 /// deduction for during partial ordering for a call
875 /// (C++0x [temp.deduct.partial]).
877 /// \returns the result of template argument deduction so far. Note that a
878 /// "success" result means that template argument deduction has not yet failed,
879 /// but it may still fail, later, for other reasons.
880 static Sema::TemplateDeductionResult
881 DeduceTemplateArguments(Sema &S,
882 TemplateParameterList *TemplateParams,
883 const QualType *Params, unsigned NumParams,
884 const QualType *Args, unsigned NumArgs,
885 TemplateDeductionInfo &Info,
886 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
888 bool PartialOrdering = false) {
889 // Fast-path check to see if we have too many/too few arguments.
890 if (NumParams != NumArgs &&
891 !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
892 !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
893 return Sema::TDK_MiscellaneousDeductionFailure;
895 // C++0x [temp.deduct.type]p10:
896 // Similarly, if P has a form that contains (T), then each parameter type
897 // Pi of the respective parameter-type- list of P is compared with the
898 // corresponding parameter type Ai of the corresponding parameter-type-list
900 unsigned ArgIdx = 0, ParamIdx = 0;
901 for (; ParamIdx != NumParams; ++ParamIdx) {
902 // Check argument types.
903 const PackExpansionType *Expansion
904 = dyn_cast<PackExpansionType>(Params[ParamIdx]);
906 // Simple case: compare the parameter and argument types at this point.
908 // Make sure we have an argument.
909 if (ArgIdx >= NumArgs)
910 return Sema::TDK_MiscellaneousDeductionFailure;
912 if (isa<PackExpansionType>(Args[ArgIdx])) {
913 // C++0x [temp.deduct.type]p22:
914 // If the original function parameter associated with A is a function
915 // parameter pack and the function parameter associated with P is not
916 // a function parameter pack, then template argument deduction fails.
917 return Sema::TDK_MiscellaneousDeductionFailure;
920 if (Sema::TemplateDeductionResult Result
921 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
922 Params[ParamIdx], Args[ArgIdx],
931 // C++0x [temp.deduct.type]p5:
932 // The non-deduced contexts are:
933 // - A function parameter pack that does not occur at the end of the
934 // parameter-declaration-clause.
935 if (ParamIdx + 1 < NumParams)
936 return Sema::TDK_Success;
938 // C++0x [temp.deduct.type]p10:
939 // If the parameter-declaration corresponding to Pi is a function
940 // parameter pack, then the type of its declarator- id is compared with
941 // each remaining parameter type in the parameter-type-list of A. Each
942 // comparison deduces template arguments for subsequent positions in the
943 // template parameter packs expanded by the function parameter pack.
945 QualType Pattern = Expansion->getPattern();
946 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
948 for (; ArgIdx < NumArgs; ++ArgIdx) {
949 // Deduce template arguments from the pattern.
950 if (Sema::TemplateDeductionResult Result
951 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
952 Args[ArgIdx], Info, Deduced,
953 TDF, PartialOrdering))
956 PackScope.nextPackElement();
959 // Build argument packs for each of the parameter packs expanded by this
961 if (auto Result = PackScope.finish())
965 // Make sure we don't have any extra arguments.
966 if (ArgIdx < NumArgs)
967 return Sema::TDK_MiscellaneousDeductionFailure;
969 return Sema::TDK_Success;
972 /// \brief Determine whether the parameter has qualifiers that are either
973 /// inconsistent with or a superset of the argument's qualifiers.
974 static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType,
976 Qualifiers ParamQs = ParamType.getQualifiers();
977 Qualifiers ArgQs = ArgType.getQualifiers();
979 if (ParamQs == ArgQs)
982 // Mismatched (but not missing) Objective-C GC attributes.
983 if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
984 ParamQs.hasObjCGCAttr())
987 // Mismatched (but not missing) address spaces.
988 if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
989 ParamQs.hasAddressSpace())
992 // Mismatched (but not missing) Objective-C lifetime qualifiers.
993 if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
994 ParamQs.hasObjCLifetime())
997 // CVR qualifier superset.
998 return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
999 ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
1000 == ParamQs.getCVRQualifiers());
1003 /// \brief Compare types for equality with respect to possibly compatible
1004 /// function types (noreturn adjustment, implicit calling conventions). If any
1005 /// of parameter and argument is not a function, just perform type comparison.
1007 /// \param Param the template parameter type.
1009 /// \param Arg the argument type.
1010 bool Sema::isSameOrCompatibleFunctionType(CanQualType Param,
1012 const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
1013 *ArgFunction = Arg->getAs<FunctionType>();
1015 // Just compare if not functions.
1016 if (!ParamFunction || !ArgFunction)
1017 return Param == Arg;
1019 // Noreturn and noexcept adjustment.
1020 QualType AdjustedParam;
1021 if (IsFunctionConversion(Param, Arg, AdjustedParam))
1022 return Arg == Context.getCanonicalType(AdjustedParam);
1024 // FIXME: Compatible calling conventions.
1026 return Param == Arg;
1029 /// Get the index of the first template parameter that was originally from the
1030 /// innermost template-parameter-list. This is 0 except when we concatenate
1031 /// the template parameter lists of a class template and a constructor template
1032 /// when forming an implicit deduction guide.
1033 static unsigned getFirstInnerIndex(FunctionTemplateDecl *FTD) {
1034 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FTD->getTemplatedDecl());
1035 if (!Guide || !Guide->isImplicit())
1037 return Guide->getDeducedTemplate()->getTemplateParameters()->size();
1040 /// Determine whether a type denotes a forwarding reference.
1041 static bool isForwardingReference(QualType Param, unsigned FirstInnerIndex) {
1042 // C++1z [temp.deduct.call]p3:
1043 // A forwarding reference is an rvalue reference to a cv-unqualified
1044 // template parameter that does not represent a template parameter of a
1046 if (auto *ParamRef = Param->getAs<RValueReferenceType>()) {
1047 if (ParamRef->getPointeeType().getQualifiers())
1049 auto *TypeParm = ParamRef->getPointeeType()->getAs<TemplateTypeParmType>();
1050 return TypeParm && TypeParm->getIndex() >= FirstInnerIndex;
1055 /// \brief Deduce the template arguments by comparing the parameter type and
1056 /// the argument type (C++ [temp.deduct.type]).
1058 /// \param S the semantic analysis object within which we are deducing
1060 /// \param TemplateParams the template parameters that we are deducing
1062 /// \param ParamIn the parameter type
1064 /// \param ArgIn the argument type
1066 /// \param Info information about the template argument deduction itself
1068 /// \param Deduced the deduced template arguments
1070 /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
1071 /// how template argument deduction is performed.
1073 /// \param PartialOrdering Whether we're performing template argument deduction
1074 /// in the context of partial ordering (C++0x [temp.deduct.partial]).
1076 /// \returns the result of template argument deduction so far. Note that a
1077 /// "success" result means that template argument deduction has not yet failed,
1078 /// but it may still fail, later, for other reasons.
1079 static Sema::TemplateDeductionResult
1080 DeduceTemplateArgumentsByTypeMatch(Sema &S,
1081 TemplateParameterList *TemplateParams,
1082 QualType ParamIn, QualType ArgIn,
1083 TemplateDeductionInfo &Info,
1084 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1086 bool PartialOrdering,
1087 bool DeducedFromArrayBound) {
1088 // We only want to look at the canonical types, since typedefs and
1089 // sugar are not part of template argument deduction.
1090 QualType Param = S.Context.getCanonicalType(ParamIn);
1091 QualType Arg = S.Context.getCanonicalType(ArgIn);
1093 // If the argument type is a pack expansion, look at its pattern.
1094 // This isn't explicitly called out
1095 if (const PackExpansionType *ArgExpansion
1096 = dyn_cast<PackExpansionType>(Arg))
1097 Arg = ArgExpansion->getPattern();
1099 if (PartialOrdering) {
1100 // C++11 [temp.deduct.partial]p5:
1101 // Before the partial ordering is done, certain transformations are
1102 // performed on the types used for partial ordering:
1103 // - If P is a reference type, P is replaced by the type referred to.
1104 const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
1106 Param = ParamRef->getPointeeType();
1108 // - If A is a reference type, A is replaced by the type referred to.
1109 const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
1111 Arg = ArgRef->getPointeeType();
1113 if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
1114 // C++11 [temp.deduct.partial]p9:
1115 // If, for a given type, deduction succeeds in both directions (i.e.,
1116 // the types are identical after the transformations above) and both
1117 // P and A were reference types [...]:
1118 // - if [one type] was an lvalue reference and [the other type] was
1119 // not, [the other type] is not considered to be at least as
1120 // specialized as [the first type]
1121 // - if [one type] is more cv-qualified than [the other type],
1122 // [the other type] is not considered to be at least as specialized
1123 // as [the first type]
1124 // Objective-C ARC adds:
1125 // - [one type] has non-trivial lifetime, [the other type] has
1126 // __unsafe_unretained lifetime, and the types are otherwise
1129 // A is "considered to be at least as specialized" as P iff deduction
1130 // succeeds, so we model this as a deduction failure. Note that
1131 // [the first type] is P and [the other type] is A here; the standard
1132 // gets this backwards.
1133 Qualifiers ParamQuals = Param.getQualifiers();
1134 Qualifiers ArgQuals = Arg.getQualifiers();
1135 if ((ParamRef->isLValueReferenceType() &&
1136 !ArgRef->isLValueReferenceType()) ||
1137 ParamQuals.isStrictSupersetOf(ArgQuals) ||
1138 (ParamQuals.hasNonTrivialObjCLifetime() &&
1139 ArgQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone &&
1140 ParamQuals.withoutObjCLifetime() ==
1141 ArgQuals.withoutObjCLifetime())) {
1142 Info.FirstArg = TemplateArgument(ParamIn);
1143 Info.SecondArg = TemplateArgument(ArgIn);
1144 return Sema::TDK_NonDeducedMismatch;
1148 // C++11 [temp.deduct.partial]p7:
1149 // Remove any top-level cv-qualifiers:
1150 // - If P is a cv-qualified type, P is replaced by the cv-unqualified
1152 Param = Param.getUnqualifiedType();
1153 // - If A is a cv-qualified type, A is replaced by the cv-unqualified
1155 Arg = Arg.getUnqualifiedType();
1157 // C++0x [temp.deduct.call]p4 bullet 1:
1158 // - If the original P is a reference type, the deduced A (i.e., the type
1159 // referred to by the reference) can be more cv-qualified than the
1161 if (TDF & TDF_ParamWithReferenceType) {
1163 QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1164 Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
1165 Arg.getCVRQualifiers());
1166 Param = S.Context.getQualifiedType(UnqualParam, Quals);
1169 if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1170 // C++0x [temp.deduct.type]p10:
1171 // If P and A are function types that originated from deduction when
1172 // taking the address of a function template (14.8.2.2) or when deducing
1173 // template arguments from a function declaration (14.8.2.6) and Pi and
1174 // Ai are parameters of the top-level parameter-type-list of P and A,
1175 // respectively, Pi is adjusted if it is a forwarding reference and Ai
1176 // is an lvalue reference, in
1177 // which case the type of Pi is changed to be the template parameter
1178 // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1179 // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
1180 // deduced as X&. - end note ]
1181 TDF &= ~TDF_TopLevelParameterTypeList;
1182 if (isForwardingReference(Param, 0) && Arg->isLValueReferenceType())
1183 Param = Param->getPointeeType();
1187 // C++ [temp.deduct.type]p9:
1188 // A template type argument T, a template template argument TT or a
1189 // template non-type argument i can be deduced if P and A have one of
1190 // the following forms:
1194 if (const TemplateTypeParmType *TemplateTypeParm
1195 = Param->getAs<TemplateTypeParmType>()) {
1196 // Just skip any attempts to deduce from a placeholder type or a parameter
1197 // at a different depth.
1198 if (Arg->isPlaceholderType() ||
1199 Info.getDeducedDepth() != TemplateTypeParm->getDepth())
1200 return Sema::TDK_Success;
1202 unsigned Index = TemplateTypeParm->getIndex();
1203 bool RecanonicalizeArg = false;
1205 // If the argument type is an array type, move the qualifiers up to the
1206 // top level, so they can be matched with the qualifiers on the parameter.
1207 if (isa<ArrayType>(Arg)) {
1209 Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
1211 Arg = S.Context.getQualifiedType(Arg, Quals);
1212 RecanonicalizeArg = true;
1216 // The argument type can not be less qualified than the parameter
1218 if (!(TDF & TDF_IgnoreQualifiers) &&
1219 hasInconsistentOrSupersetQualifiersOf(Param, Arg)) {
1220 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1221 Info.FirstArg = TemplateArgument(Param);
1222 Info.SecondArg = TemplateArgument(Arg);
1223 return Sema::TDK_Underqualified;
1226 assert(TemplateTypeParm->getDepth() == Info.getDeducedDepth() &&
1227 "saw template type parameter with wrong depth");
1228 assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
1229 QualType DeducedType = Arg;
1231 // Remove any qualifiers on the parameter from the deduced type.
1232 // We checked the qualifiers for consistency above.
1233 Qualifiers DeducedQs = DeducedType.getQualifiers();
1234 Qualifiers ParamQs = Param.getQualifiers();
1235 DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1236 if (ParamQs.hasObjCGCAttr())
1237 DeducedQs.removeObjCGCAttr();
1238 if (ParamQs.hasAddressSpace())
1239 DeducedQs.removeAddressSpace();
1240 if (ParamQs.hasObjCLifetime())
1241 DeducedQs.removeObjCLifetime();
1244 // If template deduction would produce a lifetime qualifier on a type
1245 // that is not a lifetime type, template argument deduction fails.
1246 if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1247 !DeducedType->isDependentType()) {
1248 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1249 Info.FirstArg = TemplateArgument(Param);
1250 Info.SecondArg = TemplateArgument(Arg);
1251 return Sema::TDK_Underqualified;
1255 // If template deduction would produce an argument type with lifetime type
1256 // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1257 if (S.getLangOpts().ObjCAutoRefCount &&
1258 DeducedType->isObjCLifetimeType() &&
1259 !DeducedQs.hasObjCLifetime())
1260 DeducedQs.setObjCLifetime(Qualifiers::OCL_Strong);
1262 DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1265 if (RecanonicalizeArg)
1266 DeducedType = S.Context.getCanonicalType(DeducedType);
1268 DeducedTemplateArgument NewDeduced(DeducedType, DeducedFromArrayBound);
1269 DeducedTemplateArgument Result = checkDeducedTemplateArguments(S.Context,
1272 if (Result.isNull()) {
1273 Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1274 Info.FirstArg = Deduced[Index];
1275 Info.SecondArg = NewDeduced;
1276 return Sema::TDK_Inconsistent;
1279 Deduced[Index] = Result;
1280 return Sema::TDK_Success;
1283 // Set up the template argument deduction information for a failure.
1284 Info.FirstArg = TemplateArgument(ParamIn);
1285 Info.SecondArg = TemplateArgument(ArgIn);
1287 // If the parameter is an already-substituted template parameter
1288 // pack, do nothing: we don't know which of its arguments to look
1289 // at, so we have to wait until all of the parameter packs in this
1290 // expansion have arguments.
1291 if (isa<SubstTemplateTypeParmPackType>(Param))
1292 return Sema::TDK_Success;
1294 // Check the cv-qualifiers on the parameter and argument types.
1295 CanQualType CanParam = S.Context.getCanonicalType(Param);
1296 CanQualType CanArg = S.Context.getCanonicalType(Arg);
1297 if (!(TDF & TDF_IgnoreQualifiers)) {
1298 if (TDF & TDF_ParamWithReferenceType) {
1299 if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
1300 return Sema::TDK_NonDeducedMismatch;
1301 } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
1302 if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
1303 return Sema::TDK_NonDeducedMismatch;
1306 // If the parameter type is not dependent, there is nothing to deduce.
1307 if (!Param->isDependentType()) {
1308 if (!(TDF & TDF_SkipNonDependent)) {
1309 bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1310 !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1313 return Sema::TDK_NonDeducedMismatch;
1316 return Sema::TDK_Success;
1318 } else if (!Param->isDependentType()) {
1319 CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1320 ArgUnqualType = CanArg.getUnqualifiedType();
1321 bool Success = (TDF & TDF_InOverloadResolution)?
1322 S.isSameOrCompatibleFunctionType(ParamUnqualType,
1324 ParamUnqualType == ArgUnqualType;
1326 return Sema::TDK_Success;
1329 switch (Param->getTypeClass()) {
1330 // Non-canonical types cannot appear here.
1331 #define NON_CANONICAL_TYPE(Class, Base) \
1332 case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1333 #define TYPE(Class, Base)
1334 #include "clang/AST/TypeNodes.def"
1336 case Type::TemplateTypeParm:
1337 case Type::SubstTemplateTypeParmPack:
1338 llvm_unreachable("Type nodes handled above");
1340 // These types cannot be dependent, so simply check whether the types are
1343 case Type::VariableArray:
1345 case Type::FunctionNoProto:
1348 case Type::ObjCObject:
1349 case Type::ObjCInterface:
1350 case Type::ObjCObjectPointer: {
1351 if (TDF & TDF_SkipNonDependent)
1352 return Sema::TDK_Success;
1354 if (TDF & TDF_IgnoreQualifiers) {
1355 Param = Param.getUnqualifiedType();
1356 Arg = Arg.getUnqualifiedType();
1359 return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1362 // _Complex T [placeholder extension]
1364 if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
1365 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1366 cast<ComplexType>(Param)->getElementType(),
1367 ComplexArg->getElementType(),
1368 Info, Deduced, TDF);
1370 return Sema::TDK_NonDeducedMismatch;
1372 // _Atomic T [extension]
1374 if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
1375 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1376 cast<AtomicType>(Param)->getValueType(),
1377 AtomicArg->getValueType(),
1378 Info, Deduced, TDF);
1380 return Sema::TDK_NonDeducedMismatch;
1383 case Type::Pointer: {
1384 QualType PointeeType;
1385 if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1386 PointeeType = PointerArg->getPointeeType();
1387 } else if (const ObjCObjectPointerType *PointerArg
1388 = Arg->getAs<ObjCObjectPointerType>()) {
1389 PointeeType = PointerArg->getPointeeType();
1391 return Sema::TDK_NonDeducedMismatch;
1394 unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
1395 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1396 cast<PointerType>(Param)->getPointeeType(),
1398 Info, Deduced, SubTDF);
1402 case Type::LValueReference: {
1403 const LValueReferenceType *ReferenceArg =
1404 Arg->getAs<LValueReferenceType>();
1406 return Sema::TDK_NonDeducedMismatch;
1408 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1409 cast<LValueReferenceType>(Param)->getPointeeType(),
1410 ReferenceArg->getPointeeType(), Info, Deduced, 0);
1414 case Type::RValueReference: {
1415 const RValueReferenceType *ReferenceArg =
1416 Arg->getAs<RValueReferenceType>();
1418 return Sema::TDK_NonDeducedMismatch;
1420 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1421 cast<RValueReferenceType>(Param)->getPointeeType(),
1422 ReferenceArg->getPointeeType(),
1426 // T [] (implied, but not stated explicitly)
1427 case Type::IncompleteArray: {
1428 const IncompleteArrayType *IncompleteArrayArg =
1429 S.Context.getAsIncompleteArrayType(Arg);
1430 if (!IncompleteArrayArg)
1431 return Sema::TDK_NonDeducedMismatch;
1433 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1434 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1435 S.Context.getAsIncompleteArrayType(Param)->getElementType(),
1436 IncompleteArrayArg->getElementType(),
1437 Info, Deduced, SubTDF);
1440 // T [integer-constant]
1441 case Type::ConstantArray: {
1442 const ConstantArrayType *ConstantArrayArg =
1443 S.Context.getAsConstantArrayType(Arg);
1444 if (!ConstantArrayArg)
1445 return Sema::TDK_NonDeducedMismatch;
1447 const ConstantArrayType *ConstantArrayParm =
1448 S.Context.getAsConstantArrayType(Param);
1449 if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
1450 return Sema::TDK_NonDeducedMismatch;
1452 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1453 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1454 ConstantArrayParm->getElementType(),
1455 ConstantArrayArg->getElementType(),
1456 Info, Deduced, SubTDF);
1460 case Type::DependentSizedArray: {
1461 const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
1463 return Sema::TDK_NonDeducedMismatch;
1465 unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1467 // Check the element type of the arrays
1468 const DependentSizedArrayType *DependentArrayParm
1469 = S.Context.getAsDependentSizedArrayType(Param);
1470 if (Sema::TemplateDeductionResult Result
1471 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1472 DependentArrayParm->getElementType(),
1473 ArrayArg->getElementType(),
1474 Info, Deduced, SubTDF))
1477 // Determine the array bound is something we can deduce.
1478 NonTypeTemplateParmDecl *NTTP
1479 = getDeducedParameterFromExpr(Info, DependentArrayParm->getSizeExpr());
1481 return Sema::TDK_Success;
1483 // We can perform template argument deduction for the given non-type
1484 // template parameter.
1485 assert(NTTP->getDepth() == Info.getDeducedDepth() &&
1486 "saw non-type template parameter with wrong depth");
1487 if (const ConstantArrayType *ConstantArrayArg
1488 = dyn_cast<ConstantArrayType>(ArrayArg)) {
1489 llvm::APSInt Size(ConstantArrayArg->getSize());
1490 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, Size,
1491 S.Context.getSizeType(),
1492 /*ArrayBound=*/true,
1495 if (const DependentSizedArrayType *DependentArrayArg
1496 = dyn_cast<DependentSizedArrayType>(ArrayArg))
1497 if (DependentArrayArg->getSizeExpr())
1498 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1499 DependentArrayArg->getSizeExpr(),
1502 // Incomplete type does not match a dependently-sized array type
1503 return Sema::TDK_NonDeducedMismatch;
1509 case Type::FunctionProto: {
1510 unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
1511 const FunctionProtoType *FunctionProtoArg =
1512 dyn_cast<FunctionProtoType>(Arg);
1513 if (!FunctionProtoArg)
1514 return Sema::TDK_NonDeducedMismatch;
1516 const FunctionProtoType *FunctionProtoParam =
1517 cast<FunctionProtoType>(Param);
1519 if (FunctionProtoParam->getTypeQuals()
1520 != FunctionProtoArg->getTypeQuals() ||
1521 FunctionProtoParam->getRefQualifier()
1522 != FunctionProtoArg->getRefQualifier() ||
1523 FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
1524 return Sema::TDK_NonDeducedMismatch;
1526 // Check return types.
1527 if (Sema::TemplateDeductionResult Result =
1528 DeduceTemplateArgumentsByTypeMatch(
1529 S, TemplateParams, FunctionProtoParam->getReturnType(),
1530 FunctionProtoArg->getReturnType(), Info, Deduced, 0))
1533 return DeduceTemplateArguments(
1534 S, TemplateParams, FunctionProtoParam->param_type_begin(),
1535 FunctionProtoParam->getNumParams(),
1536 FunctionProtoArg->param_type_begin(),
1537 FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
1540 case Type::InjectedClassName: {
1541 // Treat a template's injected-class-name as if the template
1542 // specialization type had been used.
1543 Param = cast<InjectedClassNameType>(Param)
1544 ->getInjectedSpecializationType();
1545 assert(isa<TemplateSpecializationType>(Param) &&
1546 "injected class name is not a template specialization type");
1550 // template-name<T> (where template-name refers to a class template)
1555 case Type::TemplateSpecialization: {
1556 const TemplateSpecializationType *SpecParam =
1557 cast<TemplateSpecializationType>(Param);
1559 // When Arg cannot be a derived class, we can just try to deduce template
1560 // arguments from the template-id.
1561 const RecordType *RecordT = Arg->getAs<RecordType>();
1562 if (!(TDF & TDF_DerivedClass) || !RecordT)
1563 return DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg, Info,
1566 SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1569 Sema::TemplateDeductionResult Result = DeduceTemplateArguments(
1570 S, TemplateParams, SpecParam, Arg, Info, Deduced);
1572 if (Result == Sema::TDK_Success)
1575 // We cannot inspect base classes as part of deduction when the type
1576 // is incomplete, so either instantiate any templates necessary to
1577 // complete the type, or skip over it if it cannot be completed.
1578 if (!S.isCompleteType(Info.getLocation(), Arg))
1581 // C++14 [temp.deduct.call] p4b3:
1582 // If P is a class and P has the form simple-template-id, then the
1583 // transformed A can be a derived class of the deduced A. Likewise if
1584 // P is a pointer to a class of the form simple-template-id, the
1585 // transformed A can be a pointer to a derived class pointed to by the
1588 // These alternatives are considered only if type deduction would
1589 // otherwise fail. If they yield more than one possible deduced A, the
1590 // type deduction fails.
1592 // Reset the incorrectly deduced argument from above.
1593 Deduced = DeducedOrig;
1595 // Use data recursion to crawl through the list of base classes.
1596 // Visited contains the set of nodes we have already visited, while
1597 // ToVisit is our stack of records that we still need to visit.
1598 llvm::SmallPtrSet<const RecordType *, 8> Visited;
1599 SmallVector<const RecordType *, 8> ToVisit;
1600 ToVisit.push_back(RecordT);
1601 bool Successful = false;
1602 SmallVector<DeducedTemplateArgument, 8> SuccessfulDeduced;
1603 while (!ToVisit.empty()) {
1604 // Retrieve the next class in the inheritance hierarchy.
1605 const RecordType *NextT = ToVisit.pop_back_val();
1607 // If we have already seen this type, skip it.
1608 if (!Visited.insert(NextT).second)
1611 // If this is a base class, try to perform template argument
1612 // deduction from it.
1613 if (NextT != RecordT) {
1614 TemplateDeductionInfo BaseInfo(Info.getLocation());
1615 Sema::TemplateDeductionResult BaseResult =
1616 DeduceTemplateArguments(S, TemplateParams, SpecParam,
1617 QualType(NextT, 0), BaseInfo, Deduced);
1619 // If template argument deduction for this base was successful,
1620 // note that we had some success. Otherwise, ignore any deductions
1621 // from this base class.
1622 if (BaseResult == Sema::TDK_Success) {
1623 // If we've already seen some success, then deduction fails due to
1624 // an ambiguity (temp.deduct.call p5).
1626 return Sema::TDK_MiscellaneousDeductionFailure;
1629 std::swap(SuccessfulDeduced, Deduced);
1631 Info.Param = BaseInfo.Param;
1632 Info.FirstArg = BaseInfo.FirstArg;
1633 Info.SecondArg = BaseInfo.SecondArg;
1636 Deduced = DeducedOrig;
1639 // Visit base classes
1640 CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1641 for (const auto &Base : Next->bases()) {
1642 assert(Base.getType()->isRecordType() &&
1643 "Base class that isn't a record?");
1644 ToVisit.push_back(Base.getType()->getAs<RecordType>());
1649 std::swap(SuccessfulDeduced, Deduced);
1650 return Sema::TDK_Success;
1660 // type (type::*)(T)
1665 case Type::MemberPointer: {
1666 const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1667 const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1669 return Sema::TDK_NonDeducedMismatch;
1671 QualType ParamPointeeType = MemPtrParam->getPointeeType();
1672 if (ParamPointeeType->isFunctionType())
1673 S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1674 /*IsCtorOrDtor=*/false, Info.getLocation());
1675 QualType ArgPointeeType = MemPtrArg->getPointeeType();
1676 if (ArgPointeeType->isFunctionType())
1677 S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1678 /*IsCtorOrDtor=*/false, Info.getLocation());
1680 if (Sema::TemplateDeductionResult Result
1681 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1685 TDF & TDF_IgnoreQualifiers))
1688 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1689 QualType(MemPtrParam->getClass(), 0),
1690 QualType(MemPtrArg->getClass(), 0),
1692 TDF & TDF_IgnoreQualifiers);
1695 // (clang extension)
1700 case Type::BlockPointer: {
1701 const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1702 const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
1705 return Sema::TDK_NonDeducedMismatch;
1707 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1708 BlockPtrParam->getPointeeType(),
1709 BlockPtrArg->getPointeeType(),
1713 // (clang extension)
1715 // T __attribute__(((ext_vector_type(<integral constant>))))
1716 case Type::ExtVector: {
1717 const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1718 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1719 // Make sure that the vectors have the same number of elements.
1720 if (VectorParam->getNumElements() != VectorArg->getNumElements())
1721 return Sema::TDK_NonDeducedMismatch;
1723 // Perform deduction on the element types.
1724 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1725 VectorParam->getElementType(),
1726 VectorArg->getElementType(),
1727 Info, Deduced, TDF);
1730 if (const DependentSizedExtVectorType *VectorArg
1731 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1732 // We can't check the number of elements, since the argument has a
1733 // dependent number of elements. This can only occur during partial
1736 // Perform deduction on the element types.
1737 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1738 VectorParam->getElementType(),
1739 VectorArg->getElementType(),
1740 Info, Deduced, TDF);
1743 return Sema::TDK_NonDeducedMismatch;
1746 // (clang extension)
1748 // T __attribute__(((ext_vector_type(N))))
1749 case Type::DependentSizedExtVector: {
1750 const DependentSizedExtVectorType *VectorParam
1751 = cast<DependentSizedExtVectorType>(Param);
1753 if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1754 // Perform deduction on the element types.
1755 if (Sema::TemplateDeductionResult Result
1756 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1757 VectorParam->getElementType(),
1758 VectorArg->getElementType(),
1759 Info, Deduced, TDF))
1762 // Perform deduction on the vector size, if we can.
1763 NonTypeTemplateParmDecl *NTTP
1764 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
1766 return Sema::TDK_Success;
1768 llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1769 ArgSize = VectorArg->getNumElements();
1770 // Note that we use the "array bound" rules here; just like in that
1771 // case, we don't have any particular type for the vector size, but
1772 // we can provide one if necessary.
1773 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP, ArgSize,
1774 S.Context.IntTy, true, Info,
1778 if (const DependentSizedExtVectorType *VectorArg
1779 = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1780 // Perform deduction on the element types.
1781 if (Sema::TemplateDeductionResult Result
1782 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1783 VectorParam->getElementType(),
1784 VectorArg->getElementType(),
1785 Info, Deduced, TDF))
1788 // Perform deduction on the vector size, if we can.
1789 NonTypeTemplateParmDecl *NTTP
1790 = getDeducedParameterFromExpr(Info, VectorParam->getSizeExpr());
1792 return Sema::TDK_Success;
1794 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1795 VectorArg->getSizeExpr(),
1799 return Sema::TDK_NonDeducedMismatch;
1802 case Type::TypeOfExpr:
1804 case Type::DependentName:
1805 case Type::UnresolvedUsing:
1806 case Type::Decltype:
1807 case Type::UnaryTransform:
1809 case Type::DeducedTemplateSpecialization:
1810 case Type::DependentTemplateSpecialization:
1811 case Type::PackExpansion:
1813 // No template argument deduction for these types
1814 return Sema::TDK_Success;
1817 llvm_unreachable("Invalid Type Class!");
1820 static Sema::TemplateDeductionResult
1821 DeduceTemplateArguments(Sema &S,
1822 TemplateParameterList *TemplateParams,
1823 const TemplateArgument &Param,
1824 TemplateArgument Arg,
1825 TemplateDeductionInfo &Info,
1826 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
1827 // If the template argument is a pack expansion, perform template argument
1828 // deduction against the pattern of that expansion. This only occurs during
1829 // partial ordering.
1830 if (Arg.isPackExpansion())
1831 Arg = Arg.getPackExpansionPattern();
1833 switch (Param.getKind()) {
1834 case TemplateArgument::Null:
1835 llvm_unreachable("Null template argument in parameter list");
1837 case TemplateArgument::Type:
1838 if (Arg.getKind() == TemplateArgument::Type)
1839 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1843 Info.FirstArg = Param;
1844 Info.SecondArg = Arg;
1845 return Sema::TDK_NonDeducedMismatch;
1847 case TemplateArgument::Template:
1848 if (Arg.getKind() == TemplateArgument::Template)
1849 return DeduceTemplateArguments(S, TemplateParams,
1850 Param.getAsTemplate(),
1851 Arg.getAsTemplate(), Info, Deduced);
1852 Info.FirstArg = Param;
1853 Info.SecondArg = Arg;
1854 return Sema::TDK_NonDeducedMismatch;
1856 case TemplateArgument::TemplateExpansion:
1857 llvm_unreachable("caller should handle pack expansions");
1859 case TemplateArgument::Declaration:
1860 if (Arg.getKind() == TemplateArgument::Declaration &&
1861 isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
1862 return Sema::TDK_Success;
1864 Info.FirstArg = Param;
1865 Info.SecondArg = Arg;
1866 return Sema::TDK_NonDeducedMismatch;
1868 case TemplateArgument::NullPtr:
1869 if (Arg.getKind() == TemplateArgument::NullPtr &&
1870 S.Context.hasSameType(Param.getNullPtrType(), Arg.getNullPtrType()))
1871 return Sema::TDK_Success;
1873 Info.FirstArg = Param;
1874 Info.SecondArg = Arg;
1875 return Sema::TDK_NonDeducedMismatch;
1877 case TemplateArgument::Integral:
1878 if (Arg.getKind() == TemplateArgument::Integral) {
1879 if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
1880 return Sema::TDK_Success;
1882 Info.FirstArg = Param;
1883 Info.SecondArg = Arg;
1884 return Sema::TDK_NonDeducedMismatch;
1887 if (Arg.getKind() == TemplateArgument::Expression) {
1888 Info.FirstArg = Param;
1889 Info.SecondArg = Arg;
1890 return Sema::TDK_NonDeducedMismatch;
1893 Info.FirstArg = Param;
1894 Info.SecondArg = Arg;
1895 return Sema::TDK_NonDeducedMismatch;
1897 case TemplateArgument::Expression: {
1898 if (NonTypeTemplateParmDecl *NTTP
1899 = getDeducedParameterFromExpr(Info, Param.getAsExpr())) {
1900 if (Arg.getKind() == TemplateArgument::Integral)
1901 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1902 Arg.getAsIntegral(),
1903 Arg.getIntegralType(),
1904 /*ArrayBound=*/false,
1906 if (Arg.getKind() == TemplateArgument::NullPtr)
1907 return DeduceNullPtrTemplateArgument(S, TemplateParams, NTTP,
1908 Arg.getNullPtrType(),
1910 if (Arg.getKind() == TemplateArgument::Expression)
1911 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1912 Arg.getAsExpr(), Info, Deduced);
1913 if (Arg.getKind() == TemplateArgument::Declaration)
1914 return DeduceNonTypeTemplateArgument(S, TemplateParams, NTTP,
1916 Arg.getParamTypeForDecl(),
1919 Info.FirstArg = Param;
1920 Info.SecondArg = Arg;
1921 return Sema::TDK_NonDeducedMismatch;
1924 // Can't deduce anything, but that's okay.
1925 return Sema::TDK_Success;
1927 case TemplateArgument::Pack:
1928 llvm_unreachable("Argument packs should be expanded by the caller!");
1931 llvm_unreachable("Invalid TemplateArgument Kind!");
1934 /// \brief Determine whether there is a template argument to be used for
1937 /// This routine "expands" argument packs in-place, overriding its input
1938 /// parameters so that \c Args[ArgIdx] will be the available template argument.
1940 /// \returns true if there is another template argument (which will be at
1941 /// \c Args[ArgIdx]), false otherwise.
1942 static bool hasTemplateArgumentForDeduction(ArrayRef<TemplateArgument> &Args,
1944 if (ArgIdx == Args.size())
1947 const TemplateArgument &Arg = Args[ArgIdx];
1948 if (Arg.getKind() != TemplateArgument::Pack)
1951 assert(ArgIdx == Args.size() - 1 && "Pack not at the end of argument list?");
1952 Args = Arg.pack_elements();
1954 return ArgIdx < Args.size();
1957 /// \brief Determine whether the given set of template arguments has a pack
1958 /// expansion that is not the last template argument.
1959 static bool hasPackExpansionBeforeEnd(ArrayRef<TemplateArgument> Args) {
1960 bool FoundPackExpansion = false;
1961 for (const auto &A : Args) {
1962 if (FoundPackExpansion)
1965 if (A.getKind() == TemplateArgument::Pack)
1966 return hasPackExpansionBeforeEnd(A.pack_elements());
1968 if (A.isPackExpansion())
1969 FoundPackExpansion = true;
1975 static Sema::TemplateDeductionResult
1976 DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams,
1977 ArrayRef<TemplateArgument> Params,
1978 ArrayRef<TemplateArgument> Args,
1979 TemplateDeductionInfo &Info,
1980 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
1981 bool NumberOfArgumentsMustMatch) {
1982 // C++0x [temp.deduct.type]p9:
1983 // If the template argument list of P contains a pack expansion that is not
1984 // the last template argument, the entire template argument list is a
1985 // non-deduced context.
1986 if (hasPackExpansionBeforeEnd(Params))
1987 return Sema::TDK_Success;
1989 // C++0x [temp.deduct.type]p9:
1990 // If P has a form that contains <T> or <i>, then each argument Pi of the
1991 // respective template argument list P is compared with the corresponding
1992 // argument Ai of the corresponding template argument list of A.
1993 unsigned ArgIdx = 0, ParamIdx = 0;
1994 for (; hasTemplateArgumentForDeduction(Params, ParamIdx); ++ParamIdx) {
1995 if (!Params[ParamIdx].isPackExpansion()) {
1996 // The simple case: deduce template arguments by matching Pi and Ai.
1998 // Check whether we have enough arguments.
1999 if (!hasTemplateArgumentForDeduction(Args, ArgIdx))
2000 return NumberOfArgumentsMustMatch
2001 ? Sema::TDK_MiscellaneousDeductionFailure
2002 : Sema::TDK_Success;
2004 // C++1z [temp.deduct.type]p9:
2005 // During partial ordering, if Ai was originally a pack expansion [and]
2006 // Pi is not a pack expansion, template argument deduction fails.
2007 if (Args[ArgIdx].isPackExpansion())
2008 return Sema::TDK_MiscellaneousDeductionFailure;
2010 // Perform deduction for this Pi/Ai pair.
2011 if (Sema::TemplateDeductionResult Result
2012 = DeduceTemplateArguments(S, TemplateParams,
2013 Params[ParamIdx], Args[ArgIdx],
2017 // Move to the next argument.
2022 // The parameter is a pack expansion.
2024 // C++0x [temp.deduct.type]p9:
2025 // If Pi is a pack expansion, then the pattern of Pi is compared with
2026 // each remaining argument in the template argument list of A. Each
2027 // comparison deduces template arguments for subsequent positions in the
2028 // template parameter packs expanded by Pi.
2029 TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
2031 // FIXME: If there are no remaining arguments, we can bail out early
2032 // and set any deduced parameter packs to an empty argument pack.
2033 // The latter part of this is a (minor) correctness issue.
2035 // Prepare to deduce the packs within the pattern.
2036 PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
2038 // Keep track of the deduced template arguments for each parameter pack
2039 // expanded by this pack expansion (the outer index) and for each
2040 // template argument (the inner SmallVectors).
2041 for (; hasTemplateArgumentForDeduction(Args, ArgIdx); ++ArgIdx) {
2042 // Deduce template arguments from the pattern.
2043 if (Sema::TemplateDeductionResult Result
2044 = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
2048 PackScope.nextPackElement();
2051 // Build argument packs for each of the parameter packs expanded by this
2053 if (auto Result = PackScope.finish())
2057 return Sema::TDK_Success;
2060 static Sema::TemplateDeductionResult
2061 DeduceTemplateArguments(Sema &S,
2062 TemplateParameterList *TemplateParams,
2063 const TemplateArgumentList &ParamList,
2064 const TemplateArgumentList &ArgList,
2065 TemplateDeductionInfo &Info,
2066 SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
2067 return DeduceTemplateArguments(S, TemplateParams, ParamList.asArray(),
2068 ArgList.asArray(), Info, Deduced,
2069 /*NumberOfArgumentsMustMatch*/false);
2072 /// \brief Determine whether two template arguments are the same.
2073 static bool isSameTemplateArg(ASTContext &Context,
2075 const TemplateArgument &Y,
2076 bool PackExpansionMatchesPack = false) {
2077 // If we're checking deduced arguments (X) against original arguments (Y),
2078 // we will have flattened packs to non-expansions in X.
2079 if (PackExpansionMatchesPack && X.isPackExpansion() && !Y.isPackExpansion())
2080 X = X.getPackExpansionPattern();
2082 if (X.getKind() != Y.getKind())
2085 switch (X.getKind()) {
2086 case TemplateArgument::Null:
2087 llvm_unreachable("Comparing NULL template argument");
2089 case TemplateArgument::Type:
2090 return Context.getCanonicalType(X.getAsType()) ==
2091 Context.getCanonicalType(Y.getAsType());
2093 case TemplateArgument::Declaration:
2094 return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
2096 case TemplateArgument::NullPtr:
2097 return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
2099 case TemplateArgument::Template:
2100 case TemplateArgument::TemplateExpansion:
2101 return Context.getCanonicalTemplateName(
2102 X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
2103 Context.getCanonicalTemplateName(
2104 Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
2106 case TemplateArgument::Integral:
2107 return hasSameExtendedValue(X.getAsIntegral(), Y.getAsIntegral());
2109 case TemplateArgument::Expression: {
2110 llvm::FoldingSetNodeID XID, YID;
2111 X.getAsExpr()->Profile(XID, Context, true);
2112 Y.getAsExpr()->Profile(YID, Context, true);
2116 case TemplateArgument::Pack:
2117 if (X.pack_size() != Y.pack_size())
2120 for (TemplateArgument::pack_iterator XP = X.pack_begin(),
2121 XPEnd = X.pack_end(),
2122 YP = Y.pack_begin();
2123 XP != XPEnd; ++XP, ++YP)
2124 if (!isSameTemplateArg(Context, *XP, *YP, PackExpansionMatchesPack))
2130 llvm_unreachable("Invalid TemplateArgument Kind!");
2133 /// \brief Allocate a TemplateArgumentLoc where all locations have
2134 /// been initialized to the given location.
2136 /// \param Arg The template argument we are producing template argument
2137 /// location information for.
2139 /// \param NTTPType For a declaration template argument, the type of
2140 /// the non-type template parameter that corresponds to this template
2141 /// argument. Can be null if no type sugar is available to add to the
2142 /// type from the template argument.
2144 /// \param Loc The source location to use for the resulting template
2147 Sema::getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
2148 QualType NTTPType, SourceLocation Loc) {
2149 switch (Arg.getKind()) {
2150 case TemplateArgument::Null:
2151 llvm_unreachable("Can't get a NULL template argument here");
2153 case TemplateArgument::Type:
2154 return TemplateArgumentLoc(
2155 Arg, Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
2157 case TemplateArgument::Declaration: {
2158 if (NTTPType.isNull())
2159 NTTPType = Arg.getParamTypeForDecl();
2160 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2162 return TemplateArgumentLoc(TemplateArgument(E), E);
2165 case TemplateArgument::NullPtr: {
2166 if (NTTPType.isNull())
2167 NTTPType = Arg.getNullPtrType();
2168 Expr *E = BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2170 return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2174 case TemplateArgument::Integral: {
2176 BuildExpressionFromIntegralTemplateArgument(Arg, Loc).getAs<Expr>();
2177 return TemplateArgumentLoc(TemplateArgument(E), E);
2180 case TemplateArgument::Template:
2181 case TemplateArgument::TemplateExpansion: {
2182 NestedNameSpecifierLocBuilder Builder;
2183 TemplateName Template = Arg.getAsTemplate();
2184 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
2185 Builder.MakeTrivial(Context, DTN->getQualifier(), Loc);
2186 else if (QualifiedTemplateName *QTN =
2187 Template.getAsQualifiedTemplateName())
2188 Builder.MakeTrivial(Context, QTN->getQualifier(), Loc);
2190 if (Arg.getKind() == TemplateArgument::Template)
2191 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
2194 return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(Context),
2198 case TemplateArgument::Expression:
2199 return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2201 case TemplateArgument::Pack:
2202 return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
2205 llvm_unreachable("Invalid TemplateArgument Kind!");
2209 /// \brief Convert the given deduced template argument and add it to the set of
2210 /// fully-converted template arguments.
2212 ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param,
2213 DeducedTemplateArgument Arg,
2214 NamedDecl *Template,
2215 TemplateDeductionInfo &Info,
2217 SmallVectorImpl<TemplateArgument> &Output) {
2218 auto ConvertArg = [&](DeducedTemplateArgument Arg,
2219 unsigned ArgumentPackIndex) {
2220 // Convert the deduced template argument into a template
2221 // argument that we can check, almost as if the user had written
2222 // the template argument explicitly.
2223 TemplateArgumentLoc ArgLoc =
2224 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Info.getLocation());
2226 // Check the template argument, converting it as necessary.
2227 return S.CheckTemplateArgument(
2228 Param, ArgLoc, Template, Template->getLocation(),
2229 Template->getSourceRange().getEnd(), ArgumentPackIndex, Output,
2231 ? (Arg.wasDeducedFromArrayBound() ? Sema::CTAK_DeducedFromArrayBound
2232 : Sema::CTAK_Deduced)
2233 : Sema::CTAK_Specified);
2236 if (Arg.getKind() == TemplateArgument::Pack) {
2237 // This is a template argument pack, so check each of its arguments against
2238 // the template parameter.
2239 SmallVector<TemplateArgument, 2> PackedArgsBuilder;
2240 for (const auto &P : Arg.pack_elements()) {
2241 // When converting the deduced template argument, append it to the
2242 // general output list. We need to do this so that the template argument
2243 // checking logic has all of the prior template arguments available.
2244 DeducedTemplateArgument InnerArg(P);
2245 InnerArg.setDeducedFromArrayBound(Arg.wasDeducedFromArrayBound());
2246 assert(InnerArg.getKind() != TemplateArgument::Pack &&
2247 "deduced nested pack");
2249 // We deduced arguments for some elements of this pack, but not for
2250 // all of them. This happens if we get a conditionally-non-deduced
2251 // context in a pack expansion (such as an overload set in one of the
2253 S.Diag(Param->getLocation(),
2254 diag::err_template_arg_deduced_incomplete_pack)
2258 if (ConvertArg(InnerArg, PackedArgsBuilder.size()))
2261 // Move the converted template argument into our argument pack.
2262 PackedArgsBuilder.push_back(Output.pop_back_val());
2265 // If the pack is empty, we still need to substitute into the parameter
2266 // itself, in case that substitution fails.
2267 if (PackedArgsBuilder.empty()) {
2268 LocalInstantiationScope Scope(S);
2269 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Output);
2270 MultiLevelTemplateArgumentList Args(TemplateArgs);
2272 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2273 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2275 Template->getSourceRange());
2276 if (Inst.isInvalid() ||
2277 S.SubstType(NTTP->getType(), Args, NTTP->getLocation(),
2278 NTTP->getDeclName()).isNull())
2280 } else if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2281 Sema::InstantiatingTemplate Inst(S, Template->getLocation(), Template,
2283 Template->getSourceRange());
2284 if (Inst.isInvalid() || !S.SubstDecl(TTP, S.CurContext, Args))
2287 // For type parameters, no substitution is ever required.
2290 // Create the resulting argument pack.
2292 TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
2296 return ConvertArg(Arg, 0);
2299 // FIXME: This should not be a template, but
2300 // ClassTemplatePartialSpecializationDecl sadly does not derive from
2302 template<typename TemplateDeclT>
2303 static Sema::TemplateDeductionResult ConvertDeducedTemplateArguments(
2304 Sema &S, TemplateDeclT *Template, bool IsDeduced,
2305 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2306 TemplateDeductionInfo &Info, SmallVectorImpl<TemplateArgument> &Builder,
2307 LocalInstantiationScope *CurrentInstantiationScope = nullptr,
2308 unsigned NumAlreadyConverted = 0, bool PartialOverloading = false) {
2309 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2311 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2312 NamedDecl *Param = TemplateParams->getParam(I);
2314 if (!Deduced[I].isNull()) {
2315 if (I < NumAlreadyConverted) {
2316 // We may have had explicitly-specified template arguments for a
2317 // template parameter pack (that may or may not have been extended
2318 // via additional deduced arguments).
2319 if (Param->isParameterPack() && CurrentInstantiationScope &&
2320 CurrentInstantiationScope->getPartiallySubstitutedPack() == Param) {
2321 // Forget the partially-substituted pack; its substitution is now
2323 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2324 // We still need to check the argument in case it was extended by
2327 // We have already fully type-checked and converted this
2328 // argument, because it was explicitly-specified. Just record the
2329 // presence of this argument.
2330 Builder.push_back(Deduced[I]);
2335 // We may have deduced this argument, so it still needs to be
2336 // checked and converted.
2337 if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Template, Info,
2338 IsDeduced, Builder)) {
2339 Info.Param = makeTemplateParameter(Param);
2340 // FIXME: These template arguments are temporary. Free them!
2341 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2342 return Sema::TDK_SubstitutionFailure;
2348 // C++0x [temp.arg.explicit]p3:
2349 // A trailing template parameter pack (14.5.3) not otherwise deduced will
2350 // be deduced to an empty sequence of template arguments.
2351 // FIXME: Where did the word "trailing" come from?
2352 if (Param->isTemplateParameterPack()) {
2353 // We may have had explicitly-specified template arguments for this
2354 // template parameter pack. If so, our empty deduction extends the
2355 // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2356 const TemplateArgument *ExplicitArgs;
2357 unsigned NumExplicitArgs;
2358 if (CurrentInstantiationScope &&
2359 CurrentInstantiationScope->getPartiallySubstitutedPack(
2360 &ExplicitArgs, &NumExplicitArgs) == Param) {
2361 Builder.push_back(TemplateArgument(
2362 llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
2364 // Forget the partially-substituted pack; its substitution is now
2366 CurrentInstantiationScope->ResetPartiallySubstitutedPack();
2368 // Go through the motions of checking the empty argument pack against
2369 // the parameter pack.
2370 DeducedTemplateArgument DeducedPack(TemplateArgument::getEmptyPack());
2371 if (ConvertDeducedTemplateArgument(S, Param, DeducedPack, Template,
2372 Info, IsDeduced, Builder)) {
2373 Info.Param = makeTemplateParameter(Param);
2374 // FIXME: These template arguments are temporary. Free them!
2375 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2376 return Sema::TDK_SubstitutionFailure;
2382 // Substitute into the default template argument, if available.
2383 bool HasDefaultArg = false;
2384 TemplateDecl *TD = dyn_cast<TemplateDecl>(Template);
2386 assert(isa<ClassTemplatePartialSpecializationDecl>(Template) ||
2387 isa<VarTemplatePartialSpecializationDecl>(Template));
2388 return Sema::TDK_Incomplete;
2391 TemplateArgumentLoc DefArg = S.SubstDefaultTemplateArgumentIfAvailable(
2392 TD, TD->getLocation(), TD->getSourceRange().getEnd(), Param, Builder,
2395 // If there was no default argument, deduction is incomplete.
2396 if (DefArg.getArgument().isNull()) {
2397 Info.Param = makeTemplateParameter(
2398 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2399 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2400 if (PartialOverloading) break;
2402 return HasDefaultArg ? Sema::TDK_SubstitutionFailure
2403 : Sema::TDK_Incomplete;
2406 // Check whether we can actually use the default argument.
2407 if (S.CheckTemplateArgument(Param, DefArg, TD, TD->getLocation(),
2408 TD->getSourceRange().getEnd(), 0, Builder,
2409 Sema::CTAK_Specified)) {
2410 Info.Param = makeTemplateParameter(
2411 const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2412 // FIXME: These template arguments are temporary. Free them!
2413 Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder));
2414 return Sema::TDK_SubstitutionFailure;
2417 // If we get here, we successfully used the default template argument.
2420 return Sema::TDK_Success;
2423 static DeclContext *getAsDeclContextOrEnclosing(Decl *D) {
2424 if (auto *DC = dyn_cast<DeclContext>(D))
2426 return D->getDeclContext();
2429 template<typename T> struct IsPartialSpecialization {
2430 static constexpr bool value = false;
2433 struct IsPartialSpecialization<ClassTemplatePartialSpecializationDecl> {
2434 static constexpr bool value = true;
2437 struct IsPartialSpecialization<VarTemplatePartialSpecializationDecl> {
2438 static constexpr bool value = true;
2441 /// Complete template argument deduction for a partial specialization.
2442 template <typename T>
2443 static typename std::enable_if<IsPartialSpecialization<T>::value,
2444 Sema::TemplateDeductionResult>::type
2445 FinishTemplateArgumentDeduction(
2446 Sema &S, T *Partial, bool IsPartialOrdering,
2447 const TemplateArgumentList &TemplateArgs,
2448 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2449 TemplateDeductionInfo &Info) {
2450 // Unevaluated SFINAE context.
2451 EnterExpressionEvaluationContext Unevaluated(
2452 S, Sema::ExpressionEvaluationContext::Unevaluated);
2453 Sema::SFINAETrap Trap(S);
2455 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Partial));
2457 // C++ [temp.deduct.type]p2:
2458 // [...] or if any template argument remains neither deduced nor
2459 // explicitly specified, template argument deduction fails.
2460 SmallVector<TemplateArgument, 4> Builder;
2461 if (auto Result = ConvertDeducedTemplateArguments(
2462 S, Partial, IsPartialOrdering, Deduced, Info, Builder))
2465 // Form the template argument list from the deduced template arguments.
2466 TemplateArgumentList *DeducedArgumentList
2467 = TemplateArgumentList::CreateCopy(S.Context, Builder);
2469 Info.reset(DeducedArgumentList);
2471 // Substitute the deduced template arguments into the template
2472 // arguments of the class template partial specialization, and
2473 // verify that the instantiated template arguments are both valid
2474 // and are equivalent to the template arguments originally provided
2475 // to the class template.
2476 LocalInstantiationScope InstScope(S);
2477 auto *Template = Partial->getSpecializedTemplate();
2478 const ASTTemplateArgumentListInfo *PartialTemplArgInfo =
2479 Partial->getTemplateArgsAsWritten();
2480 const TemplateArgumentLoc *PartialTemplateArgs =
2481 PartialTemplArgInfo->getTemplateArgs();
2483 TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2484 PartialTemplArgInfo->RAngleLoc);
2486 if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
2487 InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2488 unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2489 if (ParamIdx >= Partial->getTemplateParameters()->size())
2490 ParamIdx = Partial->getTemplateParameters()->size() - 1;
2492 Decl *Param = const_cast<NamedDecl *>(
2493 Partial->getTemplateParameters()->getParam(ParamIdx));
2494 Info.Param = makeTemplateParameter(Param);
2495 Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2496 return Sema::TDK_SubstitutionFailure;
2499 SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2500 if (S.CheckTemplateArgumentList(Template, Partial->getLocation(), InstArgs,
2501 false, ConvertedInstArgs))
2502 return Sema::TDK_SubstitutionFailure;
2504 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2505 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2506 TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2507 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2508 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2509 Info.FirstArg = TemplateArgs[I];
2510 Info.SecondArg = InstArg;
2511 return Sema::TDK_NonDeducedMismatch;
2515 if (Trap.hasErrorOccurred())
2516 return Sema::TDK_SubstitutionFailure;
2518 return Sema::TDK_Success;
2521 /// Complete template argument deduction for a class or variable template,
2522 /// when partial ordering against a partial specialization.
2523 // FIXME: Factor out duplication with partial specialization version above.
2524 static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(
2525 Sema &S, TemplateDecl *Template, bool PartialOrdering,
2526 const TemplateArgumentList &TemplateArgs,
2527 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2528 TemplateDeductionInfo &Info) {
2529 // Unevaluated SFINAE context.
2530 EnterExpressionEvaluationContext Unevaluated(
2531 S, Sema::ExpressionEvaluationContext::Unevaluated);
2532 Sema::SFINAETrap Trap(S);
2534 Sema::ContextRAII SavedContext(S, getAsDeclContextOrEnclosing(Template));
2536 // C++ [temp.deduct.type]p2:
2537 // [...] or if any template argument remains neither deduced nor
2538 // explicitly specified, template argument deduction fails.
2539 SmallVector<TemplateArgument, 4> Builder;
2540 if (auto Result = ConvertDeducedTemplateArguments(
2541 S, Template, /*IsDeduced*/PartialOrdering, Deduced, Info, Builder))
2544 // Check that we produced the correct argument list.
2545 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2546 for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2547 TemplateArgument InstArg = Builder[I];
2548 if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg,
2549 /*PackExpansionMatchesPack*/true)) {
2550 Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2551 Info.FirstArg = TemplateArgs[I];
2552 Info.SecondArg = InstArg;
2553 return Sema::TDK_NonDeducedMismatch;
2557 if (Trap.hasErrorOccurred())
2558 return Sema::TDK_SubstitutionFailure;
2560 return Sema::TDK_Success;
2564 /// \brief Perform template argument deduction to determine whether
2565 /// the given template arguments match the given class template
2566 /// partial specialization per C++ [temp.class.spec.match].
2567 Sema::TemplateDeductionResult
2568 Sema::DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
2569 const TemplateArgumentList &TemplateArgs,
2570 TemplateDeductionInfo &Info) {
2571 if (Partial->isInvalidDecl())
2574 // C++ [temp.class.spec.match]p2:
2575 // A partial specialization matches a given actual template
2576 // argument list if the template arguments of the partial
2577 // specialization can be deduced from the actual template argument
2580 // Unevaluated SFINAE context.
2581 EnterExpressionEvaluationContext Unevaluated(
2582 *this, Sema::ExpressionEvaluationContext::Unevaluated);
2583 SFINAETrap Trap(*this);
2585 SmallVector<DeducedTemplateArgument, 4> Deduced;
2586 Deduced.resize(Partial->getTemplateParameters()->size());
2587 if (TemplateDeductionResult Result
2588 = ::DeduceTemplateArguments(*this,
2589 Partial->getTemplateParameters(),
2590 Partial->getTemplateArgs(),
2591 TemplateArgs, Info, Deduced))
2594 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2595 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2597 if (Inst.isInvalid())
2598 return TDK_InstantiationDepth;
2600 if (Trap.hasErrorOccurred())
2601 return Sema::TDK_SubstitutionFailure;
2603 return ::FinishTemplateArgumentDeduction(
2604 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
2607 /// \brief Perform template argument deduction to determine whether
2608 /// the given template arguments match the given variable template
2609 /// partial specialization per C++ [temp.class.spec.match].
2610 Sema::TemplateDeductionResult
2611 Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
2612 const TemplateArgumentList &TemplateArgs,
2613 TemplateDeductionInfo &Info) {
2614 if (Partial->isInvalidDecl())
2617 // C++ [temp.class.spec.match]p2:
2618 // A partial specialization matches a given actual template
2619 // argument list if the template arguments of the partial
2620 // specialization can be deduced from the actual template argument
2623 // Unevaluated SFINAE context.
2624 EnterExpressionEvaluationContext Unevaluated(
2625 *this, Sema::ExpressionEvaluationContext::Unevaluated);
2626 SFINAETrap Trap(*this);
2628 SmallVector<DeducedTemplateArgument, 4> Deduced;
2629 Deduced.resize(Partial->getTemplateParameters()->size());
2630 if (TemplateDeductionResult Result = ::DeduceTemplateArguments(
2631 *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2632 TemplateArgs, Info, Deduced))
2635 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2636 InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2638 if (Inst.isInvalid())
2639 return TDK_InstantiationDepth;
2641 if (Trap.hasErrorOccurred())
2642 return Sema::TDK_SubstitutionFailure;
2644 return ::FinishTemplateArgumentDeduction(
2645 *this, Partial, /*PartialOrdering=*/false, TemplateArgs, Deduced, Info);
2648 /// \brief Determine whether the given type T is a simple-template-id type.
2649 static bool isSimpleTemplateIdType(QualType T) {
2650 if (const TemplateSpecializationType *Spec
2651 = T->getAs<TemplateSpecializationType>())
2652 return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
2657 /// \brief Substitute the explicitly-provided template arguments into the
2658 /// given function template according to C++ [temp.arg.explicit].
2660 /// \param FunctionTemplate the function template into which the explicit
2661 /// template arguments will be substituted.
2663 /// \param ExplicitTemplateArgs the explicitly-specified template
2666 /// \param Deduced the deduced template arguments, which will be populated
2667 /// with the converted and checked explicit template arguments.
2669 /// \param ParamTypes will be populated with the instantiated function
2672 /// \param FunctionType if non-NULL, the result type of the function template
2673 /// will also be instantiated and the pointed-to value will be updated with
2674 /// the instantiated function type.
2676 /// \param Info if substitution fails for any reason, this object will be
2677 /// populated with more information about the failure.
2679 /// \returns TDK_Success if substitution was successful, or some failure
2681 Sema::TemplateDeductionResult
2682 Sema::SubstituteExplicitTemplateArguments(
2683 FunctionTemplateDecl *FunctionTemplate,
2684 TemplateArgumentListInfo &ExplicitTemplateArgs,
2685 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2686 SmallVectorImpl<QualType> &ParamTypes,
2687 QualType *FunctionType,
2688 TemplateDeductionInfo &Info) {
2689 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2690 TemplateParameterList *TemplateParams
2691 = FunctionTemplate->getTemplateParameters();
2693 if (ExplicitTemplateArgs.size() == 0) {
2694 // No arguments to substitute; just copy over the parameter types and
2695 // fill in the function type.
2696 for (auto P : Function->parameters())
2697 ParamTypes.push_back(P->getType());
2700 *FunctionType = Function->getType();
2704 // Unevaluated SFINAE context.
2705 EnterExpressionEvaluationContext Unevaluated(
2706 *this, Sema::ExpressionEvaluationContext::Unevaluated);
2707 SFINAETrap Trap(*this);
2709 // C++ [temp.arg.explicit]p3:
2710 // Template arguments that are present shall be specified in the
2711 // declaration order of their corresponding template-parameters. The
2712 // template argument list shall not specify more template-arguments than
2713 // there are corresponding template-parameters.
2714 SmallVector<TemplateArgument, 4> Builder;
2716 // Enter a new template instantiation context where we check the
2717 // explicitly-specified template arguments against this function template,
2718 // and then substitute them into the function parameter types.
2719 SmallVector<TemplateArgument, 4> DeducedArgs;
2720 InstantiatingTemplate Inst(
2721 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
2722 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
2723 if (Inst.isInvalid())
2724 return TDK_InstantiationDepth;
2726 if (CheckTemplateArgumentList(FunctionTemplate, SourceLocation(),
2727 ExplicitTemplateArgs, true, Builder, false) ||
2728 Trap.hasErrorOccurred()) {
2729 unsigned Index = Builder.size();
2730 if (Index >= TemplateParams->size())
2731 Index = TemplateParams->size() - 1;
2732 Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
2733 return TDK_InvalidExplicitArguments;
2736 // Form the template argument list from the explicitly-specified
2737 // template arguments.
2738 TemplateArgumentList *ExplicitArgumentList
2739 = TemplateArgumentList::CreateCopy(Context, Builder);
2740 Info.reset(ExplicitArgumentList);
2742 // Template argument deduction and the final substitution should be
2743 // done in the context of the templated declaration. Explicit
2744 // argument substitution, on the other hand, needs to happen in the
2746 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2748 // If we deduced template arguments for a template parameter pack,
2749 // note that the template argument pack is partially substituted and record
2750 // the explicit template arguments. They'll be used as part of deduction
2751 // for this template parameter pack.
2752 for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2753 const TemplateArgument &Arg = Builder[I];
2754 if (Arg.getKind() == TemplateArgument::Pack) {
2755 CurrentInstantiationScope->SetPartiallySubstitutedPack(
2756 TemplateParams->getParam(I),
2763 const FunctionProtoType *Proto
2764 = Function->getType()->getAs<FunctionProtoType>();
2765 assert(Proto && "Function template does not have a prototype?");
2767 // Isolate our substituted parameters from our caller.
2768 LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2770 ExtParameterInfoBuilder ExtParamInfos;
2772 // Instantiate the types of each of the function parameters given the
2773 // explicitly-specified template arguments. If the function has a trailing
2774 // return type, substitute it after the arguments to ensure we substitute
2775 // in lexical order.
2776 if (Proto->hasTrailingReturn()) {
2777 if (SubstParmTypes(Function->getLocation(), Function->parameters(),
2778 Proto->getExtParameterInfosOrNull(),
2779 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2780 ParamTypes, /*params*/ nullptr, ExtParamInfos))
2781 return TDK_SubstitutionFailure;
2784 // Instantiate the return type.
2785 QualType ResultType;
2787 // C++11 [expr.prim.general]p3:
2788 // If a declaration declares a member function or member function
2789 // template of a class X, the expression this is a prvalue of type
2790 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2791 // and the end of the function-definition, member-declarator, or
2793 unsigned ThisTypeQuals = 0;
2794 CXXRecordDecl *ThisContext = nullptr;
2795 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2796 ThisContext = Method->getParent();
2797 ThisTypeQuals = Method->getTypeQualifiers();
2800 CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
2801 getLangOpts().CPlusPlus11);
2804 SubstType(Proto->getReturnType(),
2805 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2806 Function->getTypeSpecStartLoc(), Function->getDeclName());
2807 if (ResultType.isNull() || Trap.hasErrorOccurred())
2808 return TDK_SubstitutionFailure;
2811 // Instantiate the types of each of the function parameters given the
2812 // explicitly-specified template arguments if we didn't do so earlier.
2813 if (!Proto->hasTrailingReturn() &&
2814 SubstParmTypes(Function->getLocation(), Function->parameters(),
2815 Proto->getExtParameterInfosOrNull(),
2816 MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2817 ParamTypes, /*params*/ nullptr, ExtParamInfos))
2818 return TDK_SubstitutionFailure;
2821 auto EPI = Proto->getExtProtoInfo();
2822 EPI.ExtParameterInfos = ExtParamInfos.getPointerOrNull(ParamTypes.size());
2823 *FunctionType = BuildFunctionType(ResultType, ParamTypes,
2824 Function->getLocation(),
2825 Function->getDeclName(),
2827 if (FunctionType->isNull() || Trap.hasErrorOccurred())
2828 return TDK_SubstitutionFailure;
2831 // C++ [temp.arg.explicit]p2:
2832 // Trailing template arguments that can be deduced (14.8.2) may be
2833 // omitted from the list of explicit template-arguments. If all of the
2834 // template arguments can be deduced, they may all be omitted; in this
2835 // case, the empty template argument list <> itself may also be omitted.
2837 // Take all of the explicitly-specified arguments and put them into
2838 // the set of deduced template arguments. Explicitly-specified
2839 // parameter packs, however, will be set to NULL since the deduction
2840 // mechanisms handle explicitly-specified argument packs directly.
2841 Deduced.reserve(TemplateParams->size());
2842 for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2843 const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2844 if (Arg.getKind() == TemplateArgument::Pack)
2845 Deduced.push_back(DeducedTemplateArgument());
2847 Deduced.push_back(Arg);
2853 /// \brief Check whether the deduced argument type for a call to a function
2854 /// template matches the actual argument type per C++ [temp.deduct.call]p4.
2856 CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg,
2857 QualType DeducedA) {
2858 ASTContext &Context = S.Context;
2860 QualType A = OriginalArg.OriginalArgType;
2861 QualType OriginalParamType = OriginalArg.OriginalParamType;
2863 // Check for type equality (top-level cv-qualifiers are ignored).
2864 if (Context.hasSameUnqualifiedType(A, DeducedA))
2867 // Strip off references on the argument types; they aren't needed for
2868 // the following checks.
2869 if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2870 DeducedA = DeducedARef->getPointeeType();
2871 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2872 A = ARef->getPointeeType();
2874 // C++ [temp.deduct.call]p4:
2875 // [...] However, there are three cases that allow a difference:
2876 // - If the original P is a reference type, the deduced A (i.e., the
2877 // type referred to by the reference) can be more cv-qualified than
2878 // the transformed A.
2879 if (const ReferenceType *OriginalParamRef
2880 = OriginalParamType->getAs<ReferenceType>()) {
2881 // We don't want to keep the reference around any more.
2882 OriginalParamType = OriginalParamRef->getPointeeType();
2884 // FIXME: Resolve core issue (no number yet): if the original P is a
2885 // reference type and the transformed A is function type "noexcept F",
2886 // the deduced A can be F.
2888 if (A->isFunctionType() && S.IsFunctionConversion(A, DeducedA, Tmp))
2891 Qualifiers AQuals = A.getQualifiers();
2892 Qualifiers DeducedAQuals = DeducedA.getQualifiers();
2894 // Under Objective-C++ ARC, the deduced type may have implicitly
2895 // been given strong or (when dealing with a const reference)
2896 // unsafe_unretained lifetime. If so, update the original
2897 // qualifiers to include this lifetime.
2898 if (S.getLangOpts().ObjCAutoRefCount &&
2899 ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2900 AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2901 (DeducedAQuals.hasConst() &&
2902 DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2903 AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
2906 if (AQuals == DeducedAQuals) {
2907 // Qualifiers match; there's nothing to do.
2908 } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
2911 // Qualifiers are compatible, so have the argument type adopt the
2912 // deduced argument type's qualifiers as if we had performed the
2913 // qualification conversion.
2914 A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2918 // - The transformed A can be another pointer or pointer to member
2919 // type that can be converted to the deduced A via a function pointer
2920 // conversion and/or a qualification conversion.
2922 // Also allow conversions which merely strip __attribute__((noreturn)) from
2923 // function types (recursively).
2924 bool ObjCLifetimeConversion = false;
2926 if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
2927 (S.IsQualificationConversion(A, DeducedA, false,
2928 ObjCLifetimeConversion) ||
2929 S.IsFunctionConversion(A, DeducedA, ResultTy)))
2932 // - If P is a class and P has the form simple-template-id, then the
2933 // transformed A can be a derived class of the deduced A. [...]
2934 // [...] Likewise, if P is a pointer to a class of the form
2935 // simple-template-id, the transformed A can be a pointer to a
2936 // derived class pointed to by the deduced A.
2937 if (const PointerType *OriginalParamPtr
2938 = OriginalParamType->getAs<PointerType>()) {
2939 if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2940 if (const PointerType *APtr = A->getAs<PointerType>()) {
2941 if (A->getPointeeType()->isRecordType()) {
2942 OriginalParamType = OriginalParamPtr->getPointeeType();
2943 DeducedA = DeducedAPtr->getPointeeType();
2944 A = APtr->getPointeeType();
2950 if (Context.hasSameUnqualifiedType(A, DeducedA))
2953 if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
2954 S.IsDerivedFrom(SourceLocation(), A, DeducedA))
2960 /// Find the pack index for a particular parameter index in an instantiation of
2961 /// a function template with specific arguments.
2963 /// \return The pack index for whichever pack produced this parameter, or -1
2964 /// if this was not produced by a parameter. Intended to be used as the
2965 /// ArgumentPackSubstitutionIndex for further substitutions.
2966 // FIXME: We should track this in OriginalCallArgs so we don't need to
2967 // reconstruct it here.
2968 static unsigned getPackIndexForParam(Sema &S,
2969 FunctionTemplateDecl *FunctionTemplate,
2970 const MultiLevelTemplateArgumentList &Args,
2971 unsigned ParamIdx) {
2973 for (auto *PD : FunctionTemplate->getTemplatedDecl()->parameters()) {
2974 if (PD->isParameterPack()) {
2975 unsigned NumExpansions =
2976 S.getNumArgumentsInExpansion(PD->getType(), Args).getValueOr(1);
2977 if (Idx + NumExpansions > ParamIdx)
2978 return ParamIdx - Idx;
2979 Idx += NumExpansions;
2981 if (Idx == ParamIdx)
2982 return -1; // Not a pack expansion
2987 llvm_unreachable("parameter index would not be produced from template");
2990 /// \brief Finish template argument deduction for a function template,
2991 /// checking the deduced template arguments for completeness and forming
2992 /// the function template specialization.
2994 /// \param OriginalCallArgs If non-NULL, the original call arguments against
2995 /// which the deduced argument types should be compared.
2996 Sema::TemplateDeductionResult Sema::FinishTemplateArgumentDeduction(
2997 FunctionTemplateDecl *FunctionTemplate,
2998 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2999 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
3000 TemplateDeductionInfo &Info,
3001 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
3002 bool PartialOverloading, llvm::function_ref<bool()> CheckNonDependent) {
3003 // Unevaluated SFINAE context.
3004 EnterExpressionEvaluationContext Unevaluated(
3005 *this, Sema::ExpressionEvaluationContext::Unevaluated);
3006 SFINAETrap Trap(*this);
3008 // Enter a new template instantiation context while we instantiate the
3009 // actual function declaration.
3010 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
3011 InstantiatingTemplate Inst(
3012 *this, Info.getLocation(), FunctionTemplate, DeducedArgs,
3013 CodeSynthesisContext::DeducedTemplateArgumentSubstitution, Info);
3014 if (Inst.isInvalid())
3015 return TDK_InstantiationDepth;
3017 ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
3019 // C++ [temp.deduct.type]p2:
3020 // [...] or if any template argument remains neither deduced nor
3021 // explicitly specified, template argument deduction fails.
3022 SmallVector<TemplateArgument, 4> Builder;
3023 if (auto Result = ConvertDeducedTemplateArguments(
3024 *this, FunctionTemplate, /*IsDeduced*/true, Deduced, Info, Builder,
3025 CurrentInstantiationScope, NumExplicitlySpecified,
3026 PartialOverloading))
3029 // C++ [temp.deduct.call]p10: [DR1391]
3030 // If deduction succeeds for all parameters that contain
3031 // template-parameters that participate in template argument deduction,
3032 // and all template arguments are explicitly specified, deduced, or
3033 // obtained from default template arguments, remaining parameters are then
3034 // compared with the corresponding arguments. For each remaining parameter
3035 // P with a type that was non-dependent before substitution of any
3036 // explicitly-specified template arguments, if the corresponding argument
3037 // A cannot be implicitly converted to P, deduction fails.
3038 if (CheckNonDependent())
3039 return TDK_NonDependentConversionFailure;
3041 // Form the template argument list from the deduced template arguments.
3042 TemplateArgumentList *DeducedArgumentList
3043 = TemplateArgumentList::CreateCopy(Context, Builder);
3044 Info.reset(DeducedArgumentList);
3046 // Substitute the deduced template arguments into the function template
3047 // declaration to produce the function template specialization.
3048 DeclContext *Owner = FunctionTemplate->getDeclContext();
3049 if (FunctionTemplate->getFriendObjectKind())
3050 Owner = FunctionTemplate->getLexicalDeclContext();
3051 MultiLevelTemplateArgumentList SubstArgs(*DeducedArgumentList);
3052 Specialization = cast_or_null<FunctionDecl>(
3053 SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner, SubstArgs));
3054 if (!Specialization || Specialization->isInvalidDecl())
3055 return TDK_SubstitutionFailure;
3057 assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
3058 FunctionTemplate->getCanonicalDecl());
3060 // If the template argument list is owned by the function template
3061 // specialization, release it.
3062 if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
3063 !Trap.hasErrorOccurred())
3066 // There may have been an error that did not prevent us from constructing a
3067 // declaration. Mark the declaration invalid and return with a substitution
3069 if (Trap.hasErrorOccurred()) {
3070 Specialization->setInvalidDecl(true);
3071 return TDK_SubstitutionFailure;
3074 if (OriginalCallArgs) {
3075 // C++ [temp.deduct.call]p4:
3076 // In general, the deduction process attempts to find template argument
3077 // values that will make the deduced A identical to A (after the type A
3078 // is transformed as described above). [...]
3079 llvm::SmallDenseMap<std::pair<unsigned, QualType>, QualType> DeducedATypes;
3080 for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
3081 OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
3083 auto ParamIdx = OriginalArg.ArgIdx;
3084 if (ParamIdx >= Specialization->getNumParams())
3085 // FIXME: This presumably means a pack ended up smaller than we
3086 // expected while deducing. Should this not result in deduction
3087 // failure? Can it even happen?
3091 if (!OriginalArg.DecomposedParam) {
3092 // P is one of the function parameters, just look up its substituted
3094 DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
3096 // P is a decomposed element of a parameter corresponding to a
3097 // braced-init-list argument. Substitute back into P to find the
3099 QualType &CacheEntry =
3100 DeducedATypes[{ParamIdx, OriginalArg.OriginalParamType}];
3101 if (CacheEntry.isNull()) {
3102 ArgumentPackSubstitutionIndexRAII PackIndex(
3103 *this, getPackIndexForParam(*this, FunctionTemplate, SubstArgs,
3106 SubstType(OriginalArg.OriginalParamType, SubstArgs,
3107 Specialization->getTypeSpecStartLoc(),
3108 Specialization->getDeclName());
3110 DeducedA = CacheEntry;
3113 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
3114 Info.FirstArg = TemplateArgument(DeducedA);
3115 Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
3116 Info.CallArgIndex = OriginalArg.ArgIdx;
3117 return OriginalArg.DecomposedParam ? TDK_DeducedMismatchNested
3118 : TDK_DeducedMismatch;
3123 // If we suppressed any diagnostics while performing template argument
3124 // deduction, and if we haven't already instantiated this declaration,
3125 // keep track of these diagnostics. They'll be emitted if this specialization
3126 // is actually used.
3127 if (Info.diag_begin() != Info.diag_end()) {
3128 SuppressedDiagnosticsMap::iterator
3129 Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
3130 if (Pos == SuppressedDiagnostics.end())
3131 SuppressedDiagnostics[Specialization->getCanonicalDecl()]
3132 .append(Info.diag_begin(), Info.diag_end());
3138 /// Gets the type of a function for template-argument-deducton
3139 /// purposes when it's considered as part of an overload set.
3140 static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R,
3142 // We may need to deduce the return type of the function now.
3143 if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
3144 S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
3147 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
3148 if (Method->isInstance()) {
3149 // An instance method that's referenced in a form that doesn't
3150 // look like a member pointer is just invalid.
3151 if (!R.HasFormOfMemberPointer) return QualType();
3153 return S.Context.getMemberPointerType(Fn->getType(),
3154 S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
3157 if (!R.IsAddressOfOperand) return Fn->getType();
3158 return S.Context.getPointerType(Fn->getType());
3161 /// Apply the deduction rules for overload sets.
3163 /// \return the null type if this argument should be treated as an
3164 /// undeduced context
3166 ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams,
3167 Expr *Arg, QualType ParamType,
3168 bool ParamWasReference) {
3170 OverloadExpr::FindResult R = OverloadExpr::find(Arg);
3172 OverloadExpr *Ovl = R.Expression;
3174 // C++0x [temp.deduct.call]p4
3176 if (ParamWasReference)
3177 TDF |= TDF_ParamWithReferenceType;
3178 if (R.IsAddressOfOperand)
3179 TDF |= TDF_IgnoreQualifiers;
3181 // C++0x [temp.deduct.call]p6:
3182 // When P is a function type, pointer to function type, or pointer
3183 // to member function type:
3185 if (!ParamType->isFunctionType() &&
3186 !ParamType->isFunctionPointerType() &&
3187 !ParamType->isMemberFunctionPointerType()) {
3188 if (Ovl->hasExplicitTemplateArgs()) {
3189 // But we can still look for an explicit specialization.
3190 if (FunctionDecl *ExplicitSpec
3191 = S.ResolveSingleFunctionTemplateSpecialization(Ovl))
3192 return GetTypeOfFunction(S, R, ExplicitSpec);
3196 if (FunctionDecl *Viable =
3197 S.resolveAddressOfOnlyViableOverloadCandidate(Arg, DAP))
3198 return GetTypeOfFunction(S, R, Viable);
3203 // Gather the explicit template arguments, if any.
3204 TemplateArgumentListInfo ExplicitTemplateArgs;
3205 if (Ovl->hasExplicitTemplateArgs())
3206 Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
3208 for (UnresolvedSetIterator I = Ovl->decls_begin(),
3209 E = Ovl->decls_end(); I != E; ++I) {
3210 NamedDecl *D = (*I)->getUnderlyingDecl();
3212 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3213 // - If the argument is an overload set containing one or more
3214 // function templates, the parameter is treated as a
3215 // non-deduced context.
3216 if (!Ovl->hasExplicitTemplateArgs())
3219 // Otherwise, see if we can resolve a function type
3220 FunctionDecl *Specialization = nullptr;
3221 TemplateDeductionInfo Info(Ovl->getNameLoc());
3222 if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3223 Specialization, Info))
3229 FunctionDecl *Fn = cast<FunctionDecl>(D);
3230 QualType ArgType = GetTypeOfFunction(S, R, Fn);
3231 if (ArgType.isNull()) continue;
3233 // Function-to-pointer conversion.
3234 if (!ParamWasReference && ParamType->isPointerType() &&
3235 ArgType->isFunctionType())
3236 ArgType = S.Context.getPointerType(ArgType);
3238 // - If the argument is an overload set (not containing function
3239 // templates), trial argument deduction is attempted using each
3240 // of the members of the set. If deduction succeeds for only one
3241 // of the overload set members, that member is used as the
3242 // argument value for the deduction. If deduction succeeds for
3243 // more than one member of the overload set the parameter is
3244 // treated as a non-deduced context.
3246 // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3247 // Type deduction is done independently for each P/A pair, and
3248 // the deduced template argument values are then combined.
3249 // So we do not reject deductions which were made elsewhere.
3250 SmallVector<DeducedTemplateArgument, 8>
3251 Deduced(TemplateParams->size());
3252 TemplateDeductionInfo Info(Ovl->getNameLoc());
3253 Sema::TemplateDeductionResult Result
3254 = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3255 ArgType, Info, Deduced, TDF);
3256 if (Result) continue;
3257 if (!Match.isNull()) return QualType();
3264 /// \brief Perform the adjustments to the parameter and argument types
3265 /// described in C++ [temp.deduct.call].
3267 /// \returns true if the caller should not attempt to perform any template
3268 /// argument deduction based on this P/A pair because the argument is an
3269 /// overloaded function set that could not be resolved.
3270 static bool AdjustFunctionParmAndArgTypesForDeduction(
3271 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3272 QualType &ParamType, QualType &ArgType, Expr *Arg, unsigned &TDF) {
3273 // C++0x [temp.deduct.call]p3:
3274 // If P is a cv-qualified type, the top level cv-qualifiers of P's type
3275 // are ignored for type deduction.
3276 if (ParamType.hasQualifiers())
3277 ParamType = ParamType.getUnqualifiedType();
3279 // [...] If P is a reference type, the type referred to by P is
3280 // used for type deduction.
3281 const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
3283 ParamType = ParamRefType->getPointeeType();
3285 // Overload sets usually make this parameter an undeduced context,
3286 // but there are sometimes special circumstances. Typically
3287 // involving a template-id-expr.
3288 if (ArgType == S.Context.OverloadTy) {
3289 ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3291 ParamRefType != nullptr);
3292 if (ArgType.isNull())
3297 // If the argument has incomplete array type, try to complete its type.
3298 if (ArgType->isIncompleteArrayType()) {
3299 S.completeExprArrayBound(Arg);
3300 ArgType = Arg->getType();
3303 // C++1z [temp.deduct.call]p3:
3304 // If P is a forwarding reference and the argument is an lvalue, the type
3305 // "lvalue reference to A" is used in place of A for type deduction.
3306 if (isForwardingReference(QualType(ParamRefType, 0), FirstInnerIndex) &&
3308 ArgType = S.Context.getLValueReferenceType(ArgType);
3310 // C++ [temp.deduct.call]p2:
3311 // If P is not a reference type:
3312 // - If A is an array type, the pointer type produced by the
3313 // array-to-pointer standard conversion (4.2) is used in place of
3314 // A for type deduction; otherwise,
3315 if (ArgType->isArrayType())
3316 ArgType = S.Context.getArrayDecayedType(ArgType);
3317 // - If A is a function type, the pointer type produced by the
3318 // function-to-pointer standard conversion (4.3) is used in place
3319 // of A for type deduction; otherwise,
3320 else if (ArgType->isFunctionType())
3321 ArgType = S.Context.getPointerType(ArgType);
3323 // - If A is a cv-qualified type, the top level cv-qualifiers of A's
3324 // type are ignored for type deduction.
3325 ArgType = ArgType.getUnqualifiedType();
3329 // C++0x [temp.deduct.call]p4:
3330 // In general, the deduction process attempts to find template argument
3331 // values that will make the deduced A identical to A (after the type A
3332 // is transformed as described above). [...]
3333 TDF = TDF_SkipNonDependent;
3335 // - If the original P is a reference type, the deduced A (i.e., the
3336 // type referred to by the reference) can be more cv-qualified than
3337 // the transformed A.
3339 TDF |= TDF_ParamWithReferenceType;
3340 // - The transformed A can be another pointer or pointer to member
3341 // type that can be converted to the deduced A via a qualification
3342 // conversion (4.4).
3343 if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3344 ArgType->isObjCObjectPointerType())
3345 TDF |= TDF_IgnoreQualifiers;
3346 // - If P is a class and P has the form simple-template-id, then the
3347 // transformed A can be a derived class of the deduced A. Likewise,
3348 // if P is a pointer to a class of the form simple-template-id, the
3349 // transformed A can be a pointer to a derived class pointed to by
3351 if (isSimpleTemplateIdType(ParamType) ||
3352 (isa<PointerType>(ParamType) &&
3353 isSimpleTemplateIdType(
3354 ParamType->getAs<PointerType>()->getPointeeType())))
3355 TDF |= TDF_DerivedClass;
3361 hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate,
3364 static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
3365 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3366 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
3367 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3368 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
3369 bool DecomposedParam, unsigned ArgIdx, unsigned TDF);
3371 /// \brief Attempt template argument deduction from an initializer list
3372 /// deemed to be an argument in a function call.
3373 static Sema::TemplateDeductionResult DeduceFromInitializerList(
3374 Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType,
3375 InitListExpr *ILE, TemplateDeductionInfo &Info,
3376 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3377 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs, unsigned ArgIdx,
3379 // C++ [temp.deduct.call]p1: (CWG 1591)
3380 // If removing references and cv-qualifiers from P gives
3381 // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is
3382 // a non-empty initializer list, then deduction is performed instead for
3383 // each element of the initializer list, taking P0 as a function template
3384 // parameter type and the initializer element as its argument
3386 // We've already removed references and cv-qualifiers here.
3387 if (!ILE->getNumInits())
3388 return Sema::TDK_Success;
3391 auto *ArrTy = S.Context.getAsArrayType(AdjustedParamType);
3393 ElTy = ArrTy->getElementType();
3394 else if (!S.isStdInitializerList(AdjustedParamType, &ElTy)) {
3395 // Otherwise, an initializer list argument causes the parameter to be
3396 // considered a non-deduced context
3397 return Sema::TDK_Success;
3400 // Deduction only needs to be done for dependent types.
3401 if (ElTy->isDependentType()) {
3402 for (Expr *E : ILE->inits()) {
3403 if (auto Result = DeduceTemplateArgumentsFromCallArgument(
3404 S, TemplateParams, 0, ElTy, E, Info, Deduced, OriginalCallArgs, true,
3410 // in the P0[N] case, if N is a non-type template parameter, N is deduced
3411 // from the length of the initializer list.
3412 if (auto *DependentArrTy = dyn_cast_or_null<DependentSizedArrayType>(ArrTy)) {
3413 // Determine the array bound is something we can deduce.
3414 if (NonTypeTemplateParmDecl *NTTP =
3415 getDeducedParameterFromExpr(Info, DependentArrTy->getSizeExpr())) {
3416 // We can perform template argument deduction for the given non-type
3417 // template parameter.
3418 // C++ [temp.deduct.type]p13:
3419 // The type of N in the type T[N] is std::size_t.
3420 QualType T = S.Context.getSizeType();
3421 llvm::APInt Size(S.Context.getIntWidth(T), ILE->getNumInits());
3422 if (auto Result = DeduceNonTypeTemplateArgument(
3423 S, TemplateParams, NTTP, llvm::APSInt(Size), T,
3424 /*ArrayBound=*/true, Info, Deduced))
3429 return Sema::TDK_Success;
3432 /// \brief Perform template argument deduction per [temp.deduct.call] for a
3433 /// single parameter / argument pair.
3434 static Sema::TemplateDeductionResult DeduceTemplateArgumentsFromCallArgument(
3435 Sema &S, TemplateParameterList *TemplateParams, unsigned FirstInnerIndex,
3436 QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info,
3437 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3438 SmallVectorImpl<Sema::OriginalCallArg> &OriginalCallArgs,
3439 bool DecomposedParam, unsigned ArgIdx, unsigned TDF) {
3440 QualType ArgType = Arg->getType();
3441 QualType OrigParamType = ParamType;
3443 // If P is a reference type [...]
3444 // If P is a cv-qualified type [...]
3445 if (AdjustFunctionParmAndArgTypesForDeduction(
3446 S, TemplateParams, FirstInnerIndex, ParamType, ArgType, Arg, TDF))
3447 return Sema::TDK_Success;
3449 // If [...] the argument is a non-empty initializer list [...]
3450 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg))
3451 return DeduceFromInitializerList(S, TemplateParams, ParamType, ILE, Info,
3452 Deduced, OriginalCallArgs, ArgIdx, TDF);
3454 // [...] the deduction process attempts to find template argument values
3455 // that will make the deduced A identical to A
3457 // Keep track of the argument type and corresponding parameter index,
3458 // so we can check for compatibility between the deduced A and A.
3459 OriginalCallArgs.push_back(
3460 Sema::OriginalCallArg(OrigParamType, DecomposedParam, ArgIdx, ArgType));
3461 return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3462 ArgType, Info, Deduced, TDF);
3465 /// \brief Perform template argument deduction from a function call
3466 /// (C++ [temp.deduct.call]).
3468 /// \param FunctionTemplate the function template for which we are performing
3469 /// template argument deduction.
3471 /// \param ExplicitTemplateArgs the explicit template arguments provided
3474 /// \param Args the function call arguments
3476 /// \param Specialization if template argument deduction was successful,
3477 /// this will be set to the function template specialization produced by
3478 /// template argument deduction.
3480 /// \param Info the argument will be updated to provide additional information
3481 /// about template argument deduction.
3483 /// \param CheckNonDependent A callback to invoke to check conversions for
3484 /// non-dependent parameters, between deduction and substitution, per DR1391.
3485 /// If this returns true, substitution will be skipped and we return
3486 /// TDK_NonDependentConversionFailure. The callback is passed the parameter
3487 /// types (after substituting explicit template arguments).
3489 /// \returns the result of template argument deduction.
3490 Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3491 FunctionTemplateDecl *FunctionTemplate,
3492 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3493 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3494 bool PartialOverloading,
3495 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent) {
3496 if (FunctionTemplate->isInvalidDecl())
3499 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3500 unsigned NumParams = Function->getNumParams();
3502 unsigned FirstInnerIndex = getFirstInnerIndex(FunctionTemplate);
3504 // C++ [temp.deduct.call]p1:
3505 // Template argument deduction is done by comparing each function template
3506 // parameter type (call it P) with the type of the corresponding argument
3507 // of the call (call it A) as described below.
3508 if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
3509 return TDK_TooFewArguments;
3510 else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
3511 const FunctionProtoType *Proto
3512 = Function->getType()->getAs<FunctionProtoType>();
3513 if (Proto->isTemplateVariadic())
3515 else if (!Proto->isVariadic())
3516 return TDK_TooManyArguments;
3519 // The types of the parameters from which we will perform template argument
3521 LocalInstantiationScope InstScope(*this);
3522 TemplateParameterList *TemplateParams
3523 = FunctionTemplate->getTemplateParameters();
3524 SmallVector<DeducedTemplateArgument, 4> Deduced;
3525 SmallVector<QualType, 8> ParamTypes;
3526 unsigned NumExplicitlySpecified = 0;
3527 if (ExplicitTemplateArgs) {
3528 TemplateDeductionResult Result =
3529 SubstituteExplicitTemplateArguments(FunctionTemplate,
3530 *ExplicitTemplateArgs,
3538 NumExplicitlySpecified = Deduced.size();
3540 // Just fill in the parameter types from the function declaration.
3541 for (unsigned I = 0; I != NumParams; ++I)
3542 ParamTypes.push_back(Function->getParamDecl(I)->getType());
3545 SmallVector<OriginalCallArg, 8> OriginalCallArgs;
3547 // Deduce an argument of type ParamType from an expression with index ArgIdx.
3548 auto DeduceCallArgument = [&](QualType ParamType, unsigned ArgIdx) {
3549 // C++ [demp.deduct.call]p1: (DR1391)
3550 // Template argument deduction is done by comparing each function template
3551 // parameter that contains template-parameters that participate in
3552 // template argument deduction ...
3553 if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3554 return Sema::TDK_Success;
3556 // ... with the type of the corresponding argument
3557 return DeduceTemplateArgumentsFromCallArgument(
3558 *this, TemplateParams, FirstInnerIndex, ParamType, Args[ArgIdx], Info, Deduced,
3559 OriginalCallArgs, /*Decomposed*/false, ArgIdx, /*TDF*/ 0);
3562 // Deduce template arguments from the function parameters.
3563 Deduced.resize(TemplateParams->size());
3564 SmallVector<QualType, 8> ParamTypesForArgChecking;
3565 for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size(), ArgIdx = 0;
3566 ParamIdx != NumParamTypes; ++ParamIdx) {
3567 QualType ParamType = ParamTypes[ParamIdx];
3569 const PackExpansionType *ParamExpansion =
3570 dyn_cast<PackExpansionType>(ParamType);
3571 if (!ParamExpansion) {
3572 // Simple case: matching a function parameter to a function argument.
3573 if (ArgIdx >= Args.size())
3576 ParamTypesForArgChecking.push_back(ParamType);
3577 if (auto Result = DeduceCallArgument(ParamType, ArgIdx++))
3583 QualType ParamPattern = ParamExpansion->getPattern();
3584 PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3587 // C++0x [temp.deduct.call]p1:
3588 // For a function parameter pack that occurs at the end of the
3589 // parameter-declaration-list, the type A of each remaining argument of
3590 // the call is compared with the type P of the declarator-id of the
3591 // function parameter pack. Each comparison deduces template arguments
3592 // for subsequent positions in the template parameter packs expanded by
3593 // the function parameter pack. When a function parameter pack appears
3594 // in a non-deduced context [not at the end of the list], the type of
3595 // that parameter pack is never deduced.
3597 // FIXME: The above rule allows the size of the parameter pack to change
3598 // after we skip it (in the non-deduced case). That makes no sense, so
3599 // we instead notionally deduce the pack against N arguments, where N is
3600 // the length of the explicitly-specified pack if it's expanded by the
3601 // parameter pack and 0 otherwise, and we treat each deduction as a
3602 // non-deduced context.
3603 if (ParamIdx + 1 == NumParamTypes) {
3604 for (; ArgIdx < Args.size(); PackScope.nextPackElement(), ++ArgIdx) {
3605 ParamTypesForArgChecking.push_back(ParamPattern);
3606 if (auto Result = DeduceCallArgument(ParamPattern, ArgIdx))
3610 // If the parameter type contains an explicitly-specified pack that we
3611 // could not expand, skip the number of parameters notionally created
3612 // by the expansion.
3613 Optional<unsigned> NumExpansions = ParamExpansion->getNumExpansions();
3614 if (NumExpansions && !PackScope.isPartiallyExpanded()) {
3615 for (unsigned I = 0; I != *NumExpansions && ArgIdx < Args.size();
3617 ParamTypesForArgChecking.push_back(ParamPattern);
3618 // FIXME: Should we add OriginalCallArgs for these? What if the
3619 // corresponding argument is a list?
3620 PackScope.nextPackElement();
3625 // Build argument packs for each of the parameter packs expanded by this
3627 if (auto Result = PackScope.finish())
3631 return FinishTemplateArgumentDeduction(
3632 FunctionTemplate, Deduced, NumExplicitlySpecified, Specialization, Info,
3633 &OriginalCallArgs, PartialOverloading,
3634 [&]() { return CheckNonDependent(ParamTypesForArgChecking); });
3637 QualType Sema::adjustCCAndNoReturn(QualType ArgFunctionType,
3638 QualType FunctionType,
3639 bool AdjustExceptionSpec) {
3640 if (ArgFunctionType.isNull())
3641 return ArgFunctionType;
3643 const FunctionProtoType *FunctionTypeP =
3644 FunctionType->castAs<FunctionProtoType>();
3645 const FunctionProtoType *ArgFunctionTypeP =
3646 ArgFunctionType->getAs<FunctionProtoType>();
3648 FunctionProtoType::ExtProtoInfo EPI = ArgFunctionTypeP->getExtProtoInfo();
3649 bool Rebuild = false;
3651 CallingConv CC = FunctionTypeP->getCallConv();
3652 if (EPI.ExtInfo.getCC() != CC) {
3653 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC);
3657 bool NoReturn = FunctionTypeP->getNoReturnAttr();
3658 if (EPI.ExtInfo.getNoReturn() != NoReturn) {
3659 EPI.ExtInfo = EPI.ExtInfo.withNoReturn(NoReturn);
3663 if (AdjustExceptionSpec && (FunctionTypeP->hasExceptionSpec() ||
3664 ArgFunctionTypeP->hasExceptionSpec())) {
3665 EPI.ExceptionSpec = FunctionTypeP->getExtProtoInfo().ExceptionSpec;
3670 return ArgFunctionType;
3672 return Context.getFunctionType(ArgFunctionTypeP->getReturnType(),
3673 ArgFunctionTypeP->getParamTypes(), EPI);
3676 /// \brief Deduce template arguments when taking the address of a function
3677 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3680 /// \param FunctionTemplate the function template for which we are performing
3681 /// template argument deduction.
3683 /// \param ExplicitTemplateArgs the explicitly-specified template
3686 /// \param ArgFunctionType the function type that will be used as the
3687 /// "argument" type (A) when performing template argument deduction from the
3688 /// function template's function type. This type may be NULL, if there is no
3689 /// argument type to compare against, in C++0x [temp.arg.explicit]p3.
3691 /// \param Specialization if template argument deduction was successful,
3692 /// this will be set to the function template specialization produced by
3693 /// template argument deduction.
3695 /// \param Info the argument will be updated to provide additional information
3696 /// about template argument deduction.
3698 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
3699 /// the address of a function template per [temp.deduct.funcaddr] and
3700 /// [over.over]. If \c false, we are looking up a function template
3701 /// specialization based on its signature, per [temp.deduct.decl].
3703 /// \returns the result of template argument deduction.
3704 Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
3705 FunctionTemplateDecl *FunctionTemplate,
3706 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType,
3707 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3708 bool IsAddressOfFunction) {
3709 if (FunctionTemplate->isInvalidDecl())
3712 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3713 TemplateParameterList *TemplateParams
3714 = FunctionTemplate->getTemplateParameters();
3715 QualType FunctionType = Function->getType();
3717 // When taking the address of a function, we require convertibility of
3718 // the resulting function type. Otherwise, we allow arbitrary mismatches
3719 // of calling convention, noreturn, and noexcept.
3720 if (!IsAddressOfFunction)
3721 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType,
3722 /*AdjustExceptionSpec*/true);
3724 // Substitute any explicit template arguments.
3725 LocalInstantiationScope InstScope(*this);
3726 SmallVector<DeducedTemplateArgument, 4> Deduced;
3727 unsigned NumExplicitlySpecified = 0;
3728 SmallVector<QualType, 4> ParamTypes;
3729 if (ExplicitTemplateArgs) {
3730 if (TemplateDeductionResult Result
3731 = SubstituteExplicitTemplateArguments(FunctionTemplate,
3732 *ExplicitTemplateArgs,
3733 Deduced, ParamTypes,
3734 &FunctionType, Info))
3737 NumExplicitlySpecified = Deduced.size();
3740 // Unevaluated SFINAE context.
3741 EnterExpressionEvaluationContext Unevaluated(
3742 *this, Sema::ExpressionEvaluationContext::Unevaluated);
3743 SFINAETrap Trap(*this);
3745 Deduced.resize(TemplateParams->size());
3747 // If the function has a deduced return type, substitute it for a dependent
3748 // type so that we treat it as a non-deduced context in what follows. If we
3749 // are looking up by signature, the signature type should also have a deduced
3750 // return type, which we instead expect to exactly match.
3751 bool HasDeducedReturnType = false;
3752 if (getLangOpts().CPlusPlus14 && IsAddressOfFunction &&
3753 Function->getReturnType()->getContainedAutoType()) {
3754 FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
3755 HasDeducedReturnType = true;
3758 if (!ArgFunctionType.isNull()) {
3759 unsigned TDF = TDF_TopLevelParameterTypeList;
3760 if (IsAddressOfFunction)
3761 TDF |= TDF_InOverloadResolution;
3762 // Deduce template arguments from the function type.
3763 if (TemplateDeductionResult Result
3764 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3765 FunctionType, ArgFunctionType,
3766 Info, Deduced, TDF))
3770 if (TemplateDeductionResult Result
3771 = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3772 NumExplicitlySpecified,
3773 Specialization, Info))
3776 // If the function has a deduced return type, deduce it now, so we can check
3777 // that the deduced function type matches the requested type.
3778 if (HasDeducedReturnType &&
3779 Specialization->getReturnType()->isUndeducedType() &&
3780 DeduceReturnType(Specialization, Info.getLocation(), false))
3781 return TDK_MiscellaneousDeductionFailure;
3783 // If the function has a dependent exception specification, resolve it now,
3784 // so we can check that the exception specification matches.
3785 auto *SpecializationFPT =
3786 Specialization->getType()->castAs<FunctionProtoType>();
3787 if (getLangOpts().CPlusPlus1z &&
3788 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
3789 !ResolveExceptionSpec(Info.getLocation(), SpecializationFPT))
3790 return TDK_MiscellaneousDeductionFailure;
3792 // Adjust the exception specification of the argument again to match the
3793 // substituted and resolved type we just formed. (Calling convention and
3794 // noreturn can't be dependent, so we don't actually need this for them
3796 QualType SpecializationType = Specialization->getType();
3797 if (!IsAddressOfFunction)
3798 ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, SpecializationType,
3799 /*AdjustExceptionSpec*/true);
3801 // If the requested function type does not match the actual type of the
3802 // specialization with respect to arguments of compatible pointer to function
3803 // types, template argument deduction fails.
3804 if (!ArgFunctionType.isNull()) {
3805 if (IsAddressOfFunction &&
3806 !isSameOrCompatibleFunctionType(
3807 Context.getCanonicalType(SpecializationType),
3808 Context.getCanonicalType(ArgFunctionType)))
3809 return TDK_MiscellaneousDeductionFailure;
3811 if (!IsAddressOfFunction &&
3812 !Context.hasSameType(SpecializationType, ArgFunctionType))
3813 return TDK_MiscellaneousDeductionFailure;
3819 /// \brief Given a function declaration (e.g. a generic lambda conversion
3820 /// function) that contains an 'auto' in its result type, substitute it
3821 /// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3822 /// to replace 'auto' with and not the actual result type you want
3823 /// to set the function to.
3825 SubstAutoWithinFunctionReturnType(FunctionDecl *F,
3826 QualType TypeToReplaceAutoWith, Sema &S) {
3827 assert(!TypeToReplaceAutoWith->getContainedAutoType());
3828 QualType AutoResultType = F->getReturnType();
3829 assert(AutoResultType->getContainedAutoType());
3830 QualType DeducedResultType = S.SubstAutoType(AutoResultType,
3831 TypeToReplaceAutoWith);
3832 S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3835 /// \brief Given a specialized conversion operator of a generic lambda
3836 /// create the corresponding specializations of the call operator and
3837 /// the static-invoker. If the return type of the call operator is auto,
3838 /// deduce its return type and check if that matches the
3839 /// return type of the destination function ptr.
3841 static inline Sema::TemplateDeductionResult
3842 SpecializeCorrespondingLambdaCallOperatorAndInvoker(
3843 CXXConversionDecl *ConversionSpecialized,
3844 SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3845 QualType ReturnTypeOfDestFunctionPtr,
3846 TemplateDeductionInfo &TDInfo,
3849 CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
3850 assert(LambdaClass && LambdaClass->isGenericLambda());
3852 CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
3853 QualType CallOpResultType = CallOpGeneric->getReturnType();
3854 const bool GenericLambdaCallOperatorHasDeducedReturnType =
3855 CallOpResultType->getContainedAutoType();
3857 FunctionTemplateDecl *CallOpTemplate =
3858 CallOpGeneric->getDescribedFunctionTemplate();
3860 FunctionDecl *CallOpSpecialized = nullptr;
3861 // Use the deduced arguments of the conversion function, to specialize our
3862 // generic lambda's call operator.
3863 if (Sema::TemplateDeductionResult Result
3864 = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3866 0, CallOpSpecialized, TDInfo))
3869 // If we need to deduce the return type, do so (instantiates the callop).
3870 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3871 CallOpSpecialized->getReturnType()->isUndeducedType())
3872 S.DeduceReturnType(CallOpSpecialized,
3873 CallOpSpecialized->getPointOfInstantiation(),
3876 // Check to see if the return type of the destination ptr-to-function
3877 // matches the return type of the call operator.
3878 if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
3879 ReturnTypeOfDestFunctionPtr))
3880 return Sema::TDK_NonDeducedMismatch;
3881 // Since we have succeeded in matching the source and destination
3882 // ptr-to-functions (now including return type), and have successfully
3883 // specialized our corresponding call operator, we are ready to
3884 // specialize the static invoker with the deduced arguments of our
3886 FunctionDecl *InvokerSpecialized = nullptr;
3887 FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3888 getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3891 Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3893 S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
3894 InvokerSpecialized, TDInfo);
3895 assert(Result == Sema::TDK_Success &&
3896 "If the call operator succeeded so should the invoker!");
3897 // Set the result type to match the corresponding call operator
3898 // specialization's result type.
3899 if (GenericLambdaCallOperatorHasDeducedReturnType &&
3900 InvokerSpecialized->getReturnType()->isUndeducedType()) {
3901 // Be sure to get the type to replace 'auto' with and not
3902 // the full result type of the call op specialization
3903 // to substitute into the 'auto' of the invoker and conversion
3906 // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3907 // We don't want to subst 'int*' into 'auto' to get int**.
3909 QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3910 ->getContainedAutoType()
3912 SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3913 TypeToReplaceAutoWith, S);
3914 SubstAutoWithinFunctionReturnType(ConversionSpecialized,
3915 TypeToReplaceAutoWith, S);
3918 // Ensure that static invoker doesn't have a const qualifier.
3919 // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
3920 // do not use the CallOperator's TypeSourceInfo which allows
3921 // the const qualifier to leak through.
3922 const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3923 getType().getTypePtr()->castAs<FunctionProtoType>();
3924 FunctionProtoType::ExtProtoInfo EPI = InvokerFPT->getExtProtoInfo();
3926 InvokerSpecialized->setType(S.Context.getFunctionType(
3927 InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
3928 return Sema::TDK_Success;
3930 /// \brief Deduce template arguments for a templated conversion
3931 /// function (C++ [temp.deduct.conv]) and, if successful, produce a
3932 /// conversion function template specialization.
3933 Sema::TemplateDeductionResult
3934 Sema::DeduceTemplateArguments(FunctionTemplateDecl *ConversionTemplate,
3936 CXXConversionDecl *&Specialization,
3937 TemplateDeductionInfo &Info) {
3938 if (ConversionTemplate->isInvalidDecl())
3941 CXXConversionDecl *ConversionGeneric
3942 = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3944 QualType FromType = ConversionGeneric->getConversionType();
3946 // Canonicalize the types for deduction.
3947 QualType P = Context.getCanonicalType(FromType);
3948 QualType A = Context.getCanonicalType(ToType);
3950 // C++0x [temp.deduct.conv]p2:
3951 // If P is a reference type, the type referred to by P is used for
3953 if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3954 P = PRef->getPointeeType();
3956 // C++0x [temp.deduct.conv]p4:
3957 // [...] If A is a reference type, the type referred to by A is used
3958 // for type deduction.
3959 if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3960 A = ARef->getPointeeType().getUnqualifiedType();
3961 // C++ [temp.deduct.conv]p3:
3963 // If A is not a reference type:
3965 assert(!A->isReferenceType() && "Reference types were handled above");
3967 // - If P is an array type, the pointer type produced by the
3968 // array-to-pointer standard conversion (4.2) is used in place
3969 // of P for type deduction; otherwise,
3970 if (P->isArrayType())
3971 P = Context.getArrayDecayedType(P);
3972 // - If P is a function type, the pointer type produced by the
3973 // function-to-pointer standard conversion (4.3) is used in
3974 // place of P for type deduction; otherwise,
3975 else if (P->isFunctionType())
3976 P = Context.getPointerType(P);
3977 // - If P is a cv-qualified type, the top level cv-qualifiers of
3978 // P's type are ignored for type deduction.
3980 P = P.getUnqualifiedType();
3982 // C++0x [temp.deduct.conv]p4:
3983 // If A is a cv-qualified type, the top level cv-qualifiers of A's
3984 // type are ignored for type deduction. If A is a reference type, the type
3985 // referred to by A is used for type deduction.
3986 A = A.getUnqualifiedType();
3989 // Unevaluated SFINAE context.
3990 EnterExpressionEvaluationContext Unevaluated(
3991 *this, Sema::ExpressionEvaluationContext::Unevaluated);
3992 SFINAETrap Trap(*this);
3994 // C++ [temp.deduct.conv]p1:
3995 // Template argument deduction is done by comparing the return
3996 // type of the template conversion function (call it P) with the
3997 // type that is required as the result of the conversion (call it
3998 // A) as described in 14.8.2.4.
3999 TemplateParameterList *TemplateParams
4000 = ConversionTemplate->getTemplateParameters();
4001 SmallVector<DeducedTemplateArgument, 4> Deduced;
4002 Deduced.resize(TemplateParams->size());
4004 // C++0x [temp.deduct.conv]p4:
4005 // In general, the deduction process attempts to find template
4006 // argument values that will make the deduced A identical to
4007 // A. However, there are two cases that allow a difference:
4009 // - If the original A is a reference type, A can be more
4010 // cv-qualified than the deduced A (i.e., the type referred to
4011 // by the reference)
4012 if (ToType->isReferenceType())
4013 TDF |= TDF_ParamWithReferenceType;
4014 // - The deduced A can be another pointer or pointer to member
4015 // type that can be converted to A via a qualification
4018 // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
4019 // both P and A are pointers or member pointers. In this case, we
4020 // just ignore cv-qualifiers completely).
4021 if ((P->isPointerType() && A->isPointerType()) ||
4022 (P->isMemberPointerType() && A->isMemberPointerType()))
4023 TDF |= TDF_IgnoreQualifiers;
4024 if (TemplateDeductionResult Result
4025 = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
4026 P, A, Info, Deduced, TDF))
4029 // Create an Instantiation Scope for finalizing the operator.
4030 LocalInstantiationScope InstScope(*this);
4031 // Finish template argument deduction.
4032 FunctionDecl *ConversionSpecialized = nullptr;
4033 TemplateDeductionResult Result
4034 = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
4035 ConversionSpecialized, Info);
4036 Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
4038 // If the conversion operator is being invoked on a lambda closure to convert
4039 // to a ptr-to-function, use the deduced arguments from the conversion
4040 // function to specialize the corresponding call operator.
4041 // e.g., int (*fp)(int) = [](auto a) { return a; };
4042 if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
4044 // Get the return type of the destination ptr-to-function we are converting
4045 // to. This is necessary for matching the lambda call operator's return
4046 // type to that of the destination ptr-to-function's return type.
4047 assert(A->isPointerType() &&
4048 "Can only convert from lambda to ptr-to-function");
4049 const FunctionType *ToFunType =
4050 A->getPointeeType().getTypePtr()->getAs<FunctionType>();
4051 const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
4053 // Create the corresponding specializations of the call operator and
4054 // the static-invoker; and if the return type is auto,
4055 // deduce the return type and check if it matches the
4056 // DestFunctionPtrReturnType.
4058 // auto L = [](auto a) { return f(a); };
4059 // int (*fp)(int) = L;
4060 // char (*fp2)(int) = L; <-- Not OK.
4062 Result = SpecializeCorrespondingLambdaCallOperatorAndInvoker(
4063 Specialization, Deduced, DestFunctionPtrReturnType,
4069 /// \brief Deduce template arguments for a function template when there is
4070 /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
4072 /// \param FunctionTemplate the function template for which we are performing
4073 /// template argument deduction.
4075 /// \param ExplicitTemplateArgs the explicitly-specified template
4078 /// \param Specialization if template argument deduction was successful,
4079 /// this will be set to the function template specialization produced by
4080 /// template argument deduction.
4082 /// \param Info the argument will be updated to provide additional information
4083 /// about template argument deduction.
4085 /// \param IsAddressOfFunction If \c true, we are deducing as part of taking
4086 /// the address of a function template in a context where we do not have a
4087 /// target type, per [over.over]. If \c false, we are looking up a function
4088 /// template specialization based on its signature, which only happens when
4089 /// deducing a function parameter type from an argument that is a template-id
4090 /// naming a function template specialization.
4092 /// \returns the result of template argument deduction.
4093 Sema::TemplateDeductionResult Sema::DeduceTemplateArguments(
4094 FunctionTemplateDecl *FunctionTemplate,
4095 TemplateArgumentListInfo *ExplicitTemplateArgs,
4096 FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
4097 bool IsAddressOfFunction) {
4098 return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
4099 QualType(), Specialization, Info,
4100 IsAddressOfFunction);
4104 /// Substitute the 'auto' specifier or deduced template specialization type
4105 /// specifier within a type for a given replacement type.
4106 class SubstituteDeducedTypeTransform :
4107 public TreeTransform<SubstituteDeducedTypeTransform> {
4108 QualType Replacement;
4111 SubstituteDeducedTypeTransform(Sema &SemaRef, QualType Replacement,
4112 bool UseTypeSugar = true)
4113 : TreeTransform<SubstituteDeducedTypeTransform>(SemaRef),
4114 Replacement(Replacement), UseTypeSugar(UseTypeSugar) {}
4116 QualType TransformDesugared(TypeLocBuilder &TLB, DeducedTypeLoc TL) {
4117 assert(isa<TemplateTypeParmType>(Replacement) &&
4118 "unexpected unsugared replacement kind");
4119 QualType Result = Replacement;
4120 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
4121 NewTL.setNameLoc(TL.getNameLoc());
4125 QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
4126 // If we're building the type pattern to deduce against, don't wrap the
4127 // substituted type in an AutoType. Certain template deduction rules
4128 // apply only when a template type parameter appears directly (and not if
4129 // the parameter is found through desugaring). For instance:
4130 // auto &&lref = lvalue;
4131 // must transform into "rvalue reference to T" not "rvalue reference to
4132 // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
4134 // FIXME: Is this still necessary?
4136 return TransformDesugared(TLB, TL);
4138 QualType Result = SemaRef.Context.getAutoType(
4139 Replacement, TL.getTypePtr()->getKeyword(), Replacement.isNull());
4140 auto NewTL = TLB.push<AutoTypeLoc>(Result);
4141 NewTL.setNameLoc(TL.getNameLoc());
4145 QualType TransformDeducedTemplateSpecializationType(
4146 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
4148 return TransformDesugared(TLB, TL);
4150 QualType Result = SemaRef.Context.getDeducedTemplateSpecializationType(
4151 TL.getTypePtr()->getTemplateName(),
4152 Replacement, Replacement.isNull());
4153 auto NewTL = TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
4154 NewTL.setNameLoc(TL.getNameLoc());
4158 ExprResult TransformLambdaExpr(LambdaExpr *E) {
4159 // Lambdas never need to be transformed.
4163 QualType Apply(TypeLoc TL) {
4164 // Create some scratch storage for the transformed type locations.
4165 // FIXME: We're just going to throw this information away. Don't build it.
4167 TLB.reserve(TL.getFullDataSize());
4168 return TransformType(TLB, TL);
4173 Sema::DeduceAutoResult
4174 Sema::DeduceAutoType(TypeSourceInfo *Type, Expr *&Init, QualType &Result,
4175 Optional<unsigned> DependentDeductionDepth) {
4176 return DeduceAutoType(Type->getTypeLoc(), Init, Result,
4177 DependentDeductionDepth);
4180 /// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
4182 /// Note that this is done even if the initializer is dependent. (This is
4183 /// necessary to support partial ordering of templates using 'auto'.)
4184 /// A dependent type will be produced when deducing from a dependent type.
4186 /// \param Type the type pattern using the auto type-specifier.
4187 /// \param Init the initializer for the variable whose type is to be deduced.
4188 /// \param Result if type deduction was successful, this will be set to the
4190 /// \param DependentDeductionDepth Set if we should permit deduction in
4191 /// dependent cases. This is necessary for template partial ordering with
4192 /// 'auto' template parameters. The value specified is the template
4193 /// parameter depth at which we should perform 'auto' deduction.
4194 Sema::DeduceAutoResult
4195 Sema::DeduceAutoType(TypeLoc Type, Expr *&Init, QualType &Result,
4196 Optional<unsigned> DependentDeductionDepth) {
4197 if (Init->getType()->isNonOverloadPlaceholderType()) {
4198 ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4199 if (NonPlaceholder.isInvalid())
4200 return DAR_FailedAlreadyDiagnosed;
4201 Init = NonPlaceholder.get();
4204 if (!DependentDeductionDepth &&
4205 (Type.getType()->isDependentType() || Init->isTypeDependent())) {
4206 Result = SubstituteDeducedTypeTransform(*this, QualType()).Apply(Type);
4207 assert(!Result.isNull() && "substituting DependentTy can't fail");
4208 return DAR_Succeeded;
4211 // Find the depth of template parameter to synthesize.
4212 unsigned Depth = DependentDeductionDepth.getValueOr(0);
4214 // If this is a 'decltype(auto)' specifier, do the decltype dance.
4215 // Since 'decltype(auto)' can only occur at the top of the type, we
4216 // don't need to go digging for it.
4217 if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
4218 if (AT->isDecltypeAuto()) {
4219 if (isa<InitListExpr>(Init)) {
4220 Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4221 return DAR_FailedAlreadyDiagnosed;
4224 QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
4225 if (Deduced.isNull())
4226 return DAR_FailedAlreadyDiagnosed;
4227 // FIXME: Support a non-canonical deduced type for 'auto'.
4228 Deduced = Context.getCanonicalType(Deduced);
4229 Result = SubstituteDeducedTypeTransform(*this, Deduced).Apply(Type);
4230 if (Result.isNull())
4231 return DAR_FailedAlreadyDiagnosed;
4232 return DAR_Succeeded;
4233 } else if (!getLangOpts().CPlusPlus) {
4234 if (isa<InitListExpr>(Init)) {
4235 Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4236 return DAR_FailedAlreadyDiagnosed;
4241 SourceLocation Loc = Init->getExprLoc();
4243 LocalInstantiationScope InstScope(*this);
4245 // Build template<class TemplParam> void Func(FuncParam);
4246 TemplateTypeParmDecl *TemplParam = TemplateTypeParmDecl::Create(
4247 Context, nullptr, SourceLocation(), Loc, Depth, 0, nullptr, false, false);
4248 QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4249 NamedDecl *TemplParamPtr = TemplParam;
4250 FixedSizeTemplateParameterListStorage<1, false> TemplateParamsSt(
4251 Loc, Loc, TemplParamPtr, Loc, nullptr);
4253 QualType FuncParam =
4254 SubstituteDeducedTypeTransform(*this, TemplArg, /*UseTypeSugar*/false)
4256 assert(!FuncParam.isNull() &&
4257 "substituting template parameter for 'auto' failed");
4259 // Deduce type of TemplParam in Func(Init)
4260 SmallVector<DeducedTemplateArgument, 1> Deduced;
4263 TemplateDeductionInfo Info(Loc, Depth);
4265 // If deduction failed, don't diagnose if the initializer is dependent; it
4266 // might acquire a matching type in the instantiation.
4267 auto DeductionFailed = [&]() -> DeduceAutoResult {
4268 if (Init->isTypeDependent()) {
4269 Result = SubstituteDeducedTypeTransform(*this, QualType()).Apply(Type);
4270 assert(!Result.isNull() && "substituting DependentTy can't fail");
4271 return DAR_Succeeded;
4276 SmallVector<OriginalCallArg, 4> OriginalCallArgs;
4278 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
4280 // Notionally, we substitute std::initializer_list<T> for 'auto' and deduce
4281 // against that. Such deduction only succeeds if removing cv-qualifiers and
4282 // references results in std::initializer_list<T>.
4283 if (!Type.getType().getNonReferenceType()->getAs<AutoType>())
4286 for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
4287 if (DeduceTemplateArgumentsFromCallArgument(
4288 *this, TemplateParamsSt.get(), 0, TemplArg, InitList->getInit(i),
4289 Info, Deduced, OriginalCallArgs, /*Decomposed*/ true,
4290 /*ArgIdx*/ 0, /*TDF*/ 0))
4291 return DeductionFailed();
4294 if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4295 Diag(Loc, diag::err_auto_bitfield);
4296 return DAR_FailedAlreadyDiagnosed;
4299 if (DeduceTemplateArgumentsFromCallArgument(
4300 *this, TemplateParamsSt.get(), 0, FuncParam, Init, Info, Deduced,
4301 OriginalCallArgs, /*Decomposed*/ false, /*ArgIdx*/ 0, /*TDF*/ 0))
4302 return DeductionFailed();
4305 // Could be null if somehow 'auto' appears in a non-deduced context.
4306 if (Deduced[0].getKind() != TemplateArgument::Type)
4307 return DeductionFailed();
4309 QualType DeducedType = Deduced[0].getAsType();
4312 DeducedType = BuildStdInitializerList(DeducedType, Loc);
4313 if (DeducedType.isNull())
4314 return DAR_FailedAlreadyDiagnosed;
4317 Result = SubstituteDeducedTypeTransform(*this, DeducedType).Apply(Type);
4318 if (Result.isNull())
4319 return DAR_FailedAlreadyDiagnosed;
4321 // Check that the deduced argument type is compatible with the original
4322 // argument type per C++ [temp.deduct.call]p4.
4323 QualType DeducedA = InitList ? Deduced[0].getAsType() : Result;
4324 for (const OriginalCallArg &OriginalArg : OriginalCallArgs) {
4325 assert((bool)InitList == OriginalArg.DecomposedParam &&
4326 "decomposed non-init-list in auto deduction?");
4327 if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
4328 Result = QualType();
4329 return DeductionFailed();
4333 return DAR_Succeeded;
4336 QualType Sema::SubstAutoType(QualType TypeWithAuto,
4337 QualType TypeToReplaceAuto) {
4338 if (TypeToReplaceAuto->isDependentType())
4339 TypeToReplaceAuto = QualType();
4340 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
4341 .TransformType(TypeWithAuto);
4344 TypeSourceInfo *Sema::SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
4345 QualType TypeToReplaceAuto) {
4346 if (TypeToReplaceAuto->isDependentType())
4347 TypeToReplaceAuto = QualType();
4348 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto)
4349 .TransformType(TypeWithAuto);
4352 QualType Sema::ReplaceAutoType(QualType TypeWithAuto,
4353 QualType TypeToReplaceAuto) {
4354 return SubstituteDeducedTypeTransform(*this, TypeToReplaceAuto,
4355 /*UseTypeSugar*/ false)
4356 .TransformType(TypeWithAuto);
4359 void Sema::DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init) {
4360 if (isa<InitListExpr>(Init))
4361 Diag(VDecl->getLocation(),
4362 VDecl->isInitCapture()
4363 ? diag::err_init_capture_deduction_failure_from_init_list
4364 : diag::err_auto_var_deduction_failure_from_init_list)
4365 << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4367 Diag(VDecl->getLocation(),
4368 VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4369 : diag::err_auto_var_deduction_failure)
4370 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4371 << Init->getSourceRange();
4374 bool Sema::DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
4376 assert(FD->getReturnType()->isUndeducedType());
4378 if (FD->getTemplateInstantiationPattern())
4379 InstantiateFunctionDefinition(Loc, FD);
4381 bool StillUndeduced = FD->getReturnType()->isUndeducedType();
4382 if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4383 Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4384 Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4387 return StillUndeduced;
4390 /// \brief If this is a non-static member function,
4392 AddImplicitObjectParameterType(ASTContext &Context,
4393 CXXMethodDecl *Method,
4394 SmallVectorImpl<QualType> &ArgTypes) {
4395 // C++11 [temp.func.order]p3:
4396 // [...] The new parameter is of type "reference to cv A," where cv are
4397 // the cv-qualifiers of the function template (if any) and A is
4398 // the class of which the function template is a member.
4400 // The standard doesn't say explicitly, but we pick the appropriate kind of
4401 // reference type based on [over.match.funcs]p4.
4402 QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4403 ArgTy = Context.getQualifiedType(ArgTy,
4404 Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
4405 if (Method->getRefQualifier() == RQ_RValue)
4406 ArgTy = Context.getRValueReferenceType(ArgTy);
4408 ArgTy = Context.getLValueReferenceType(ArgTy);
4409 ArgTypes.push_back(ArgTy);
4412 /// \brief Determine whether the function template \p FT1 is at least as
4413 /// specialized as \p FT2.
4414 static bool isAtLeastAsSpecializedAs(Sema &S,
4416 FunctionTemplateDecl *FT1,
4417 FunctionTemplateDecl *FT2,
4418 TemplatePartialOrderingContext TPOC,
4419 unsigned NumCallArguments1) {
4420 FunctionDecl *FD1 = FT1->getTemplatedDecl();
4421 FunctionDecl *FD2 = FT2->getTemplatedDecl();
4422 const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4423 const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
4425 assert(Proto1 && Proto2 && "Function templates must have prototypes");
4426 TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
4427 SmallVector<DeducedTemplateArgument, 4> Deduced;
4428 Deduced.resize(TemplateParams->size());
4430 // C++0x [temp.deduct.partial]p3:
4431 // The types used to determine the ordering depend on the context in which
4432 // the partial ordering is done:
4433 TemplateDeductionInfo Info(Loc);
4434 SmallVector<QualType, 4> Args2;
4437 // - In the context of a function call, the function parameter types are
4439 CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4440 CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
4442 // C++11 [temp.func.order]p3:
4443 // [...] If only one of the function templates is a non-static
4444 // member, that function template is considered to have a new
4445 // first parameter inserted in its function parameter list. The
4446 // new parameter is of type "reference to cv A," where cv are
4447 // the cv-qualifiers of the function template (if any) and A is
4448 // the class of which the function template is a member.
4450 // Note that we interpret this to mean "if one of the function
4451 // templates is a non-static member and the other is a non-member";
4452 // otherwise, the ordering rules for static functions against non-static
4453 // functions don't make any sense.
4455 // C++98/03 doesn't have this provision but we've extended DR532 to cover
4456 // it as wording was broken prior to it.
4457 SmallVector<QualType, 4> Args1;
4459 unsigned NumComparedArguments = NumCallArguments1;
4461 if (!Method2 && Method1 && !Method1->isStatic()) {
4462 // Compare 'this' from Method1 against first parameter from Method2.
4463 AddImplicitObjectParameterType(S.Context, Method1, Args1);
4464 ++NumComparedArguments;
4465 } else if (!Method1 && Method2 && !Method2->isStatic()) {
4466 // Compare 'this' from Method2 against first parameter from Method1.
4467 AddImplicitObjectParameterType(S.Context, Method2, Args2);
4470 Args1.insert(Args1.end(), Proto1->param_type_begin(),
4471 Proto1->param_type_end());
4472 Args2.insert(Args2.end(), Proto2->param_type_begin(),
4473 Proto2->param_type_end());
4475 // C++ [temp.func.order]p5:
4476 // The presence of unused ellipsis and default arguments has no effect on
4477 // the partial ordering of function templates.
4478 if (Args1.size() > NumComparedArguments)
4479 Args1.resize(NumComparedArguments);
4480 if (Args2.size() > NumComparedArguments)
4481 Args2.resize(NumComparedArguments);
4482 if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4483 Args1.data(), Args1.size(), Info, Deduced,
4484 TDF_None, /*PartialOrdering=*/true))
4490 case TPOC_Conversion:
4491 // - In the context of a call to a conversion operator, the return types
4492 // of the conversion function templates are used.
4493 if (DeduceTemplateArgumentsByTypeMatch(
4494 S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4495 Info, Deduced, TDF_None,
4496 /*PartialOrdering=*/true))
4501 // - In other contexts (14.6.6.2) the function template's function type
4503 if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4504 FD2->getType(), FD1->getType(),
4505 Info, Deduced, TDF_None,
4506 /*PartialOrdering=*/true))
4511 // C++0x [temp.deduct.partial]p11:
4512 // In most cases, all template parameters must have values in order for
4513 // deduction to succeed, but for partial ordering purposes a template
4514 // parameter may remain without a value provided it is not used in the
4515 // types being used for partial ordering. [ Note: a template parameter used
4516 // in a non-deduced context is considered used. -end note]
4517 unsigned ArgIdx = 0, NumArgs = Deduced.size();
4518 for (; ArgIdx != NumArgs; ++ArgIdx)
4519 if (Deduced[ArgIdx].isNull())
4522 // FIXME: We fail to implement [temp.deduct.type]p1 along this path. We need
4523 // to substitute the deduced arguments back into the template and check that
4524 // we get the right type.
4526 if (ArgIdx == NumArgs) {
4527 // All template arguments were deduced. FT1 is at least as specialized
4532 // Figure out which template parameters were used.
4533 llvm::SmallBitVector UsedParameters(TemplateParams->size());
4536 for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4537 ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
4538 TemplateParams->getDepth(),
4542 case TPOC_Conversion:
4543 ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4544 TemplateParams->getDepth(), UsedParameters);
4548 ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
4549 TemplateParams->getDepth(),
4554 for (; ArgIdx != NumArgs; ++ArgIdx)
4555 // If this argument had no value deduced but was used in one of the types
4556 // used for partial ordering, then deduction fails.
4557 if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4563 /// \brief Determine whether this a function template whose parameter-type-list
4564 /// ends with a function parameter pack.
4565 static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl) {
4566 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4567 unsigned NumParams = Function->getNumParams();
4571 ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4572 if (!Last->isParameterPack())
4575 // Make sure that no previous parameter is a parameter pack.
4576 while (--NumParams > 0) {
4577 if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4584 /// \brief Returns the more specialized function template according
4585 /// to the rules of function template partial ordering (C++ [temp.func.order]).
4587 /// \param FT1 the first function template
4589 /// \param FT2 the second function template
4591 /// \param TPOC the context in which we are performing partial ordering of
4592 /// function templates.
4594 /// \param NumCallArguments1 The number of arguments in the call to FT1, used
4595 /// only when \c TPOC is \c TPOC_Call.
4597 /// \param NumCallArguments2 The number of arguments in the call to FT2, used
4598 /// only when \c TPOC is \c TPOC_Call.
4600 /// \returns the more specialized function template. If neither
4601 /// template is more specialized, returns NULL.
4602 FunctionTemplateDecl *
4603 Sema::getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
4604 FunctionTemplateDecl *FT2,
4606 TemplatePartialOrderingContext TPOC,
4607 unsigned NumCallArguments1,
4608 unsigned NumCallArguments2) {
4609 bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
4611 bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
4614 if (Better1 != Better2) // We have a clear winner
4615 return Better1 ? FT1 : FT2;
4617 if (!Better1 && !Better2) // Neither is better than the other
4620 // FIXME: This mimics what GCC implements, but doesn't match up with the
4621 // proposed resolution for core issue 692. This area needs to be sorted out,
4622 // but for now we attempt to maintain compatibility.
4623 bool Variadic1 = isVariadicFunctionTemplate(FT1);
4624 bool Variadic2 = isVariadicFunctionTemplate(FT2);
4625 if (Variadic1 != Variadic2)
4626 return Variadic1? FT2 : FT1;
4631 /// \brief Determine if the two templates are equivalent.
4632 static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2) {
4639 return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4642 /// \brief Retrieve the most specialized of the given function template
4643 /// specializations.
4645 /// \param SpecBegin the start iterator of the function template
4646 /// specializations that we will be comparing.
4648 /// \param SpecEnd the end iterator of the function template
4649 /// specializations, paired with \p SpecBegin.
4651 /// \param Loc the location where the ambiguity or no-specializations
4652 /// diagnostic should occur.
4654 /// \param NoneDiag partial diagnostic used to diagnose cases where there are
4655 /// no matching candidates.
4657 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4660 /// \param CandidateDiag partial diagnostic used for each function template
4661 /// specialization that is a candidate in the ambiguous ordering. One parameter
4662 /// in this diagnostic should be unbound, which will correspond to the string
4663 /// describing the template arguments for the function template specialization.
4665 /// \returns the most specialized function template specialization, if
4666 /// found. Otherwise, returns SpecEnd.
4667 UnresolvedSetIterator Sema::getMostSpecialized(
4668 UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4669 TemplateSpecCandidateSet &FailedCandidates,
4670 SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4671 const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4672 bool Complain, QualType TargetType) {
4673 if (SpecBegin == SpecEnd) {
4675 Diag(Loc, NoneDiag);
4676 FailedCandidates.NoteCandidates(*this, Loc);
4681 if (SpecBegin + 1 == SpecEnd)
4684 // Find the function template that is better than all of the templates it
4685 // has been compared to.
4686 UnresolvedSetIterator Best = SpecBegin;
4687 FunctionTemplateDecl *BestTemplate
4688 = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
4689 assert(BestTemplate && "Not a function template specialization?");
4690 for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4691 FunctionTemplateDecl *Challenger
4692 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
4693 assert(Challenger && "Not a function template specialization?");
4694 if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
4695 Loc, TPOC_Other, 0, 0),
4698 BestTemplate = Challenger;
4702 // Make sure that the "best" function template is more specialized than all
4704 bool Ambiguous = false;
4705 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4706 FunctionTemplateDecl *Challenger
4707 = cast<FunctionDecl>(*I)->getPrimaryTemplate();
4709 !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
4710 Loc, TPOC_Other, 0, 0),
4718 // We found an answer. Return it.
4722 // Diagnose the ambiguity.
4724 Diag(Loc, AmbigDiag);
4726 // FIXME: Can we order the candidates in some sane way?
4727 for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4728 PartialDiagnostic PD = CandidateDiag;
4729 const auto *FD = cast<FunctionDecl>(*I);
4730 PD << FD << getTemplateArgumentBindingsText(
4731 FD->getPrimaryTemplate()->getTemplateParameters(),
4732 *FD->getTemplateSpecializationArgs());
4733 if (!TargetType.isNull())
4734 HandleFunctionTypeMismatch(PD, FD->getType(), TargetType);
4735 Diag((*I)->getLocation(), PD);
4742 /// Determine whether one partial specialization, P1, is at least as
4743 /// specialized than another, P2.
4745 /// \tparam TemplateLikeDecl The kind of P2, which must be a
4746 /// TemplateDecl or {Class,Var}TemplatePartialSpecializationDecl.
4747 /// \param T1 The injected-class-name of P1 (faked for a variable template).
4748 /// \param T2 The injected-class-name of P2 (faked for a variable template).
4749 template<typename TemplateLikeDecl>
4750 static bool isAtLeastAsSpecializedAs(Sema &S, QualType T1, QualType T2,
4751 TemplateLikeDecl *P2,
4752 TemplateDeductionInfo &Info) {
4753 // C++ [temp.class.order]p1:
4754 // For two class template partial specializations, the first is at least as
4755 // specialized as the second if, given the following rewrite to two
4756 // function templates, the first function template is at least as
4757 // specialized as the second according to the ordering rules for function
4758 // templates (14.6.6.2):
4759 // - the first function template has the same template parameters as the
4760 // first partial specialization and has a single function parameter
4761 // whose type is a class template specialization with the template
4762 // arguments of the first partial specialization, and
4763 // - the second function template has the same template parameters as the
4764 // second partial specialization and has a single function parameter
4765 // whose type is a class template specialization with the template
4766 // arguments of the second partial specialization.
4768 // Rather than synthesize function templates, we merely perform the
4769 // equivalent partial ordering by performing deduction directly on
4770 // the template arguments of the class template partial
4771 // specializations. This computation is slightly simpler than the
4772 // general problem of function template partial ordering, because
4773 // class template partial specializations are more constrained. We
4774 // know that every template parameter is deducible from the class
4775 // template partial specialization's template arguments, for
4777 SmallVector<DeducedTemplateArgument, 4> Deduced;
4779 // Determine whether P1 is at least as specialized as P2.
4780 Deduced.resize(P2->getTemplateParameters()->size());
4781 if (DeduceTemplateArgumentsByTypeMatch(S, P2->getTemplateParameters(),
4782 T2, T1, Info, Deduced, TDF_None,
4783 /*PartialOrdering=*/true))
4786 SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4788 Sema::InstantiatingTemplate Inst(S, Info.getLocation(), P2, DeducedArgs,
4790 auto *TST1 = T1->castAs<TemplateSpecializationType>();
4791 if (FinishTemplateArgumentDeduction(
4792 S, P2, /*PartialOrdering=*/true,
4793 TemplateArgumentList(TemplateArgumentList::OnStack,
4794 TST1->template_arguments()),
4801 /// \brief Returns the more specialized class template partial specialization
4802 /// according to the rules of partial ordering of class template partial
4803 /// specializations (C++ [temp.class.order]).
4805 /// \param PS1 the first class template partial specialization
4807 /// \param PS2 the second class template partial specialization
4809 /// \returns the more specialized class template partial specialization. If
4810 /// neither partial specialization is more specialized, returns NULL.
4811 ClassTemplatePartialSpecializationDecl *
4812 Sema::getMoreSpecializedPartialSpecialization(
4813 ClassTemplatePartialSpecializationDecl *PS1,
4814 ClassTemplatePartialSpecializationDecl *PS2,
4815 SourceLocation Loc) {
4816 QualType PT1 = PS1->getInjectedSpecializationType();
4817 QualType PT2 = PS2->getInjectedSpecializationType();
4819 TemplateDeductionInfo Info(Loc);
4820 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4821 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
4823 if (Better1 == Better2)
4826 return Better1 ? PS1 : PS2;
4829 bool Sema::isMoreSpecializedThanPrimary(
4830 ClassTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4831 ClassTemplateDecl *Primary = Spec->getSpecializedTemplate();
4832 QualType PrimaryT = Primary->getInjectedClassNameSpecialization();
4833 QualType PartialT = Spec->getInjectedSpecializationType();
4834 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
4836 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
4837 Info.clearSFINAEDiagnostic();
4843 VarTemplatePartialSpecializationDecl *
4844 Sema::getMoreSpecializedPartialSpecialization(
4845 VarTemplatePartialSpecializationDecl *PS1,
4846 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc) {
4847 // Pretend the variable template specializations are class template
4848 // specializations and form a fake injected class name type for comparison.
4849 assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
4850 "the partial specializations being compared should specialize"
4851 " the same template.");
4852 TemplateName Name(PS1->getSpecializedTemplate());
4853 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4854 QualType PT1 = Context.getTemplateSpecializationType(
4855 CanonTemplate, PS1->getTemplateArgs().asArray());
4856 QualType PT2 = Context.getTemplateSpecializationType(
4857 CanonTemplate, PS2->getTemplateArgs().asArray());
4859 TemplateDeductionInfo Info(Loc);
4860 bool Better1 = isAtLeastAsSpecializedAs(*this, PT1, PT2, PS2, Info);
4861 bool Better2 = isAtLeastAsSpecializedAs(*this, PT2, PT1, PS1, Info);
4863 if (Better1 == Better2)
4866 return Better1 ? PS1 : PS2;
4869 bool Sema::isMoreSpecializedThanPrimary(
4870 VarTemplatePartialSpecializationDecl *Spec, TemplateDeductionInfo &Info) {
4871 TemplateDecl *Primary = Spec->getSpecializedTemplate();
4872 // FIXME: Cache the injected template arguments rather than recomputing
4873 // them for each partial specialization.
4874 SmallVector<TemplateArgument, 8> PrimaryArgs;
4875 Context.getInjectedTemplateArgs(Primary->getTemplateParameters(),
4878 TemplateName CanonTemplate =
4879 Context.getCanonicalTemplateName(TemplateName(Primary));
4880 QualType PrimaryT = Context.getTemplateSpecializationType(
4881 CanonTemplate, PrimaryArgs);
4882 QualType PartialT = Context.getTemplateSpecializationType(
4883 CanonTemplate, Spec->getTemplateArgs().asArray());
4884 if (!isAtLeastAsSpecializedAs(*this, PartialT, PrimaryT, Primary, Info))
4886 if (isAtLeastAsSpecializedAs(*this, PrimaryT, PartialT, Spec, Info)) {
4887 Info.clearSFINAEDiagnostic();
4893 bool Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
4894 TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc) {
4895 // C++1z [temp.arg.template]p4: (DR 150)
4896 // A template template-parameter P is at least as specialized as a
4897 // template template-argument A if, given the following rewrite to two
4898 // function templates...
4900 // Rather than synthesize function templates, we merely perform the
4901 // equivalent partial ordering by performing deduction directly on
4902 // the template parameter lists of the template template parameters.
4904 // Given an invented class template X with the template parameter list of
4905 // A (including default arguments):
4906 TemplateName X = Context.getCanonicalTemplateName(TemplateName(AArg));
4907 TemplateParameterList *A = AArg->getTemplateParameters();
4909 // - Each function template has a single function parameter whose type is
4910 // a specialization of X with template arguments corresponding to the
4911 // template parameters from the respective function template
4912 SmallVector<TemplateArgument, 8> AArgs;
4913 Context.getInjectedTemplateArgs(A, AArgs);
4915 // Check P's arguments against A's parameter list. This will fill in default
4916 // template arguments as needed. AArgs are already correct by construction.
4917 // We can't just use CheckTemplateIdType because that will expand alias
4919 SmallVector<TemplateArgument, 4> PArgs;
4921 SFINAETrap Trap(*this);
4923 Context.getInjectedTemplateArgs(P, PArgs);
4924 TemplateArgumentListInfo PArgList(P->getLAngleLoc(), P->getRAngleLoc());
4925 for (unsigned I = 0, N = P->size(); I != N; ++I) {
4926 // Unwrap packs that getInjectedTemplateArgs wrapped around pack
4927 // expansions, to form an "as written" argument list.
4928 TemplateArgument Arg = PArgs[I];
4929 if (Arg.getKind() == TemplateArgument::Pack) {
4930 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion());
4931 Arg = *Arg.pack_begin();
4933 PArgList.addArgument(getTrivialTemplateArgumentLoc(
4934 Arg, QualType(), P->getParam(I)->getLocation()));
4938 // C++1z [temp.arg.template]p3:
4939 // If the rewrite produces an invalid type, then P is not at least as
4940 // specialized as A.
4941 if (CheckTemplateArgumentList(AArg, Loc, PArgList, false, PArgs) ||
4942 Trap.hasErrorOccurred())
4946 QualType AType = Context.getTemplateSpecializationType(X, AArgs);
4947 QualType PType = Context.getTemplateSpecializationType(X, PArgs);
4949 // ... the function template corresponding to P is at least as specialized
4950 // as the function template corresponding to A according to the partial
4951 // ordering rules for function templates.
4952 TemplateDeductionInfo Info(Loc, A->getDepth());
4953 return isAtLeastAsSpecializedAs(*this, PType, AType, AArg, Info);
4956 /// \brief Mark the template parameters that are used by the given
4959 MarkUsedTemplateParameters(ASTContext &Ctx,
4963 llvm::SmallBitVector &Used) {
4964 // We can deduce from a pack expansion.
4965 if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4966 E = Expansion->getPattern();
4968 // Skip through any implicit casts we added while type-checking, and any
4969 // substitutions performed by template alias expansion.
4971 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4972 E = ICE->getSubExpr();
4973 else if (const SubstNonTypeTemplateParmExpr *Subst =
4974 dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4975 E = Subst->getReplacement();
4980 // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
4981 // find other occurrences of template parameters.
4982 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
4986 const NonTypeTemplateParmDecl *NTTP
4987 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4991 if (NTTP->getDepth() == Depth)
4992 Used[NTTP->getIndex()] = true;
4994 // In C++1z mode, additional arguments may be deduced from the type of a
4995 // non-type argument.
4996 if (Ctx.getLangOpts().CPlusPlus1z)
4997 MarkUsedTemplateParameters(Ctx, NTTP->getType(), OnlyDeduced, Depth, Used);
5000 /// \brief Mark the template parameters that are used by the given
5001 /// nested name specifier.
5003 MarkUsedTemplateParameters(ASTContext &Ctx,
5004 NestedNameSpecifier *NNS,
5007 llvm::SmallBitVector &Used) {
5011 MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
5013 MarkUsedTemplateParameters(Ctx, QualType(NNS->getAsType(), 0),
5014 OnlyDeduced, Depth, Used);
5017 /// \brief Mark the template parameters that are used by the given
5020 MarkUsedTemplateParameters(ASTContext &Ctx,
5024 llvm::SmallBitVector &Used) {
5025 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
5026 if (TemplateTemplateParmDecl *TTP
5027 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
5028 if (TTP->getDepth() == Depth)
5029 Used[TTP->getIndex()] = true;
5034 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName())
5035 MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
5037 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName())
5038 MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
5042 /// \brief Mark the template parameters that are used by the given
5045 MarkUsedTemplateParameters(ASTContext &Ctx, QualType T,
5048 llvm::SmallBitVector &Used) {
5052 // Non-dependent types have nothing deducible
5053 if (!T->isDependentType())
5056 T = Ctx.getCanonicalType(T);
5057 switch (T->getTypeClass()) {
5059 MarkUsedTemplateParameters(Ctx,
5060 cast<PointerType>(T)->getPointeeType(),
5066 case Type::BlockPointer:
5067 MarkUsedTemplateParameters(Ctx,
5068 cast<BlockPointerType>(T)->getPointeeType(),
5074 case Type::LValueReference:
5075 case Type::RValueReference:
5076 MarkUsedTemplateParameters(Ctx,
5077 cast<ReferenceType>(T)->getPointeeType(),
5083 case Type::MemberPointer: {
5084 const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
5085 MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
5087 MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
5088 OnlyDeduced, Depth, Used);
5092 case Type::DependentSizedArray:
5093 MarkUsedTemplateParameters(Ctx,
5094 cast<DependentSizedArrayType>(T)->getSizeExpr(),
5095 OnlyDeduced, Depth, Used);
5096 // Fall through to check the element type
5099 case Type::ConstantArray:
5100 case Type::IncompleteArray:
5101 MarkUsedTemplateParameters(Ctx,
5102 cast<ArrayType>(T)->getElementType(),
5103 OnlyDeduced, Depth, Used);
5107 case Type::ExtVector:
5108 MarkUsedTemplateParameters(Ctx,
5109 cast<VectorType>(T)->getElementType(),
5110 OnlyDeduced, Depth, Used);
5113 case Type::DependentSizedExtVector: {
5114 const DependentSizedExtVectorType *VecType
5115 = cast<DependentSizedExtVectorType>(T);
5116 MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
5118 MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
5123 case Type::FunctionProto: {
5124 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
5125 MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
5127 for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
5128 MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
5133 case Type::TemplateTypeParm: {
5134 const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
5135 if (TTP->getDepth() == Depth)
5136 Used[TTP->getIndex()] = true;
5140 case Type::SubstTemplateTypeParmPack: {
5141 const SubstTemplateTypeParmPackType *Subst
5142 = cast<SubstTemplateTypeParmPackType>(T);
5143 MarkUsedTemplateParameters(Ctx,
5144 QualType(Subst->getReplacedParameter(), 0),
5145 OnlyDeduced, Depth, Used);
5146 MarkUsedTemplateParameters(Ctx, Subst->getArgumentPack(),
5147 OnlyDeduced, Depth, Used);
5151 case Type::InjectedClassName:
5152 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
5155 case Type::TemplateSpecialization: {
5156 const TemplateSpecializationType *Spec
5157 = cast<TemplateSpecializationType>(T);
5158 MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
5161 // C++0x [temp.deduct.type]p9:
5162 // If the template argument list of P contains a pack expansion that is
5163 // not the last template argument, the entire template argument list is a
5164 // non-deduced context.
5166 hasPackExpansionBeforeEnd(Spec->template_arguments()))
5169 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
5170 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
5177 MarkUsedTemplateParameters(Ctx,
5178 cast<ComplexType>(T)->getElementType(),
5179 OnlyDeduced, Depth, Used);
5184 MarkUsedTemplateParameters(Ctx,
5185 cast<AtomicType>(T)->getValueType(),
5186 OnlyDeduced, Depth, Used);
5189 case Type::DependentName:
5191 MarkUsedTemplateParameters(Ctx,
5192 cast<DependentNameType>(T)->getQualifier(),
5193 OnlyDeduced, Depth, Used);
5196 case Type::DependentTemplateSpecialization: {
5197 // C++14 [temp.deduct.type]p5:
5198 // The non-deduced contexts are:
5199 // -- The nested-name-specifier of a type that was specified using a
5202 // C++14 [temp.deduct.type]p6:
5203 // When a type name is specified in a way that includes a non-deduced
5204 // context, all of the types that comprise that type name are also
5209 const DependentTemplateSpecializationType *Spec
5210 = cast<DependentTemplateSpecializationType>(T);
5212 MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
5213 OnlyDeduced, Depth, Used);
5215 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
5216 MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
5223 MarkUsedTemplateParameters(Ctx,
5224 cast<TypeOfType>(T)->getUnderlyingType(),
5225 OnlyDeduced, Depth, Used);
5228 case Type::TypeOfExpr:
5230 MarkUsedTemplateParameters(Ctx,
5231 cast<TypeOfExprType>(T)->getUnderlyingExpr(),
5232 OnlyDeduced, Depth, Used);
5235 case Type::Decltype:
5237 MarkUsedTemplateParameters(Ctx,
5238 cast<DecltypeType>(T)->getUnderlyingExpr(),
5239 OnlyDeduced, Depth, Used);
5242 case Type::UnaryTransform:
5244 MarkUsedTemplateParameters(Ctx,
5245 cast<UnaryTransformType>(T)->getUnderlyingType(),
5246 OnlyDeduced, Depth, Used);
5249 case Type::PackExpansion:
5250 MarkUsedTemplateParameters(Ctx,
5251 cast<PackExpansionType>(T)->getPattern(),
5252 OnlyDeduced, Depth, Used);
5256 case Type::DeducedTemplateSpecialization:
5257 MarkUsedTemplateParameters(Ctx,
5258 cast<DeducedType>(T)->getDeducedType(),
5259 OnlyDeduced, Depth, Used);
5261 // None of these types have any template parameters in them.
5263 case Type::VariableArray:
5264 case Type::FunctionNoProto:
5267 case Type::ObjCInterface:
5268 case Type::ObjCObject:
5269 case Type::ObjCObjectPointer:
5270 case Type::UnresolvedUsing:
5272 #define TYPE(Class, Base)
5273 #define ABSTRACT_TYPE(Class, Base)
5274 #define DEPENDENT_TYPE(Class, Base)
5275 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5276 #include "clang/AST/TypeNodes.def"
5281 /// \brief Mark the template parameters that are used by this
5282 /// template argument.
5284 MarkUsedTemplateParameters(ASTContext &Ctx,
5285 const TemplateArgument &TemplateArg,
5288 llvm::SmallBitVector &Used) {
5289 switch (TemplateArg.getKind()) {
5290 case TemplateArgument::Null:
5291 case TemplateArgument::Integral:
5292 case TemplateArgument::Declaration:
5295 case TemplateArgument::NullPtr:
5296 MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
5300 case TemplateArgument::Type:
5301 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
5305 case TemplateArgument::Template:
5306 case TemplateArgument::TemplateExpansion:
5307 MarkUsedTemplateParameters(Ctx,
5308 TemplateArg.getAsTemplateOrTemplatePattern(),
5309 OnlyDeduced, Depth, Used);
5312 case TemplateArgument::Expression:
5313 MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
5317 case TemplateArgument::Pack:
5318 for (const auto &P : TemplateArg.pack_elements())
5319 MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
5324 /// \brief Mark which template parameters can be deduced from a given
5325 /// template argument list.
5327 /// \param TemplateArgs the template argument list from which template
5328 /// parameters will be deduced.
5330 /// \param Used a bit vector whose elements will be set to \c true
5331 /// to indicate when the corresponding template parameter will be
5334 Sema::MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
5335 bool OnlyDeduced, unsigned Depth,
5336 llvm::SmallBitVector &Used) {
5337 // C++0x [temp.deduct.type]p9:
5338 // If the template argument list of P contains a pack expansion that is not
5339 // the last template argument, the entire template argument list is a
5340 // non-deduced context.
5342 hasPackExpansionBeforeEnd(TemplateArgs.asArray()))
5345 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
5346 ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
5350 /// \brief Marks all of the template parameters that will be deduced by a
5351 /// call to the given function template.
5352 void Sema::MarkDeducedTemplateParameters(
5353 ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5354 llvm::SmallBitVector &Deduced) {
5355 TemplateParameterList *TemplateParams
5356 = FunctionTemplate->getTemplateParameters();
5358 Deduced.resize(TemplateParams->size());
5360 FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5361 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
5362 ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
5363 true, TemplateParams->getDepth(), Deduced);
5366 bool hasDeducibleTemplateParameters(Sema &S,
5367 FunctionTemplateDecl *FunctionTemplate,
5369 if (!T->isDependentType())
5372 TemplateParameterList *TemplateParams
5373 = FunctionTemplate->getTemplateParameters();
5374 llvm::SmallBitVector Deduced(TemplateParams->size());
5375 ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
5378 return Deduced.any();