clang  3.8.0
SemaTemplateDeduction.cpp
Go to the documentation of this file.
1 //===------- SemaTemplateDeduction.cpp - Template Argument Deduction ------===/
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===/
8 //
9 // This file implements C++ template argument deduction.
10 //
11 //===----------------------------------------------------------------------===/
12 
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/Sema/DeclSpec.h"
23 #include "clang/Sema/Sema.h"
24 #include "clang/Sema/Template.h"
25 #include "llvm/ADT/SmallBitVector.h"
26 #include <algorithm>
27 
28 namespace clang {
29  using namespace sema;
30  /// \brief Various flags that control template argument deduction.
31  ///
32  /// These flags can be bitwise-OR'd together.
34  /// \brief No template argument deduction flags, which indicates the
35  /// strictest results for template argument deduction (as used for, e.g.,
36  /// matching class template partial specializations).
37  TDF_None = 0,
38  /// \brief Within template argument deduction from a function call, we are
39  /// matching with a parameter type for which the original parameter was
40  /// a reference.
42  /// \brief Within template argument deduction from a function call, we
43  /// are matching in a case where we ignore cv-qualifiers.
45  /// \brief Within template argument deduction from a function call,
46  /// we are matching in a case where we can perform template argument
47  /// deduction from a template-id of a derived class of the argument type.
49  /// \brief Allow non-dependent types to differ, e.g., when performing
50  /// template argument deduction from a function call where conversions
51  /// may apply.
53  /// \brief Whether we are performing template argument deduction for
54  /// parameters and arguments in a top-level template argument
56  /// \brief Within template argument deduction from overload resolution per
57  /// C++ [over.over] allow matching function types that are compatible in
58  /// terms of noreturn and default calling convention adjustments.
60  };
61 }
62 
63 using namespace clang;
64 
65 /// \brief Compare two APSInts, extending and switching the sign as
66 /// necessary to compare their values regardless of underlying type.
67 static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y) {
68  if (Y.getBitWidth() > X.getBitWidth())
69  X = X.extend(Y.getBitWidth());
70  else if (Y.getBitWidth() < X.getBitWidth())
71  Y = Y.extend(X.getBitWidth());
72 
73  // If there is a signedness mismatch, correct it.
74  if (X.isSigned() != Y.isSigned()) {
75  // If the signed value is negative, then the values cannot be the same.
76  if ((Y.isSigned() && Y.isNegative()) || (X.isSigned() && X.isNegative()))
77  return false;
78 
79  Y.setIsSigned(true);
80  X.setIsSigned(true);
81  }
82 
83  return X == Y;
84 }
85 
88  TemplateParameterList *TemplateParams,
89  const TemplateArgument &Param,
90  TemplateArgument Arg,
91  TemplateDeductionInfo &Info,
92  SmallVectorImpl<DeducedTemplateArgument> &Deduced);
93 
96  TemplateParameterList *TemplateParams,
97  QualType Param,
98  QualType Arg,
99  TemplateDeductionInfo &Info,
100  SmallVectorImpl<DeducedTemplateArgument> &
101  Deduced,
102  unsigned TDF,
103  bool PartialOrdering = false);
104 
107  TemplateParameterList *TemplateParams,
108  const TemplateArgument *Params, unsigned NumParams,
109  const TemplateArgument *Args, unsigned NumArgs,
110  TemplateDeductionInfo &Info,
111  SmallVectorImpl<DeducedTemplateArgument> &Deduced);
112 
113 /// \brief If the given expression is of a form that permits the deduction
114 /// of a non-type template parameter, return the declaration of that
115 /// non-type template parameter.
117  // If we are within an alias template, the expression may have undergone
118  // any number of parameter substitutions already.
119  while (1) {
120  if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(E))
121  E = IC->getSubExpr();
122  else if (SubstNonTypeTemplateParmExpr *Subst =
123  dyn_cast<SubstNonTypeTemplateParmExpr>(E))
124  E = Subst->getReplacement();
125  else
126  break;
127  }
128 
129  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
130  return dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
131 
132  return nullptr;
133 }
134 
135 /// \brief Determine whether two declaration pointers refer to the same
136 /// declaration.
137 static bool isSameDeclaration(Decl *X, Decl *Y) {
138  if (NamedDecl *NX = dyn_cast<NamedDecl>(X))
139  X = NX->getUnderlyingDecl();
140  if (NamedDecl *NY = dyn_cast<NamedDecl>(Y))
141  Y = NY->getUnderlyingDecl();
142 
143  return X->getCanonicalDecl() == Y->getCanonicalDecl();
144 }
145 
146 /// \brief Verify that the given, deduced template arguments are compatible.
147 ///
148 /// \returns The deduced template argument, or a NULL template argument if
149 /// the deduced template arguments were incompatible.
152  const DeducedTemplateArgument &X,
153  const DeducedTemplateArgument &Y) {
154  // We have no deduction for one or both of the arguments; they're compatible.
155  if (X.isNull())
156  return Y;
157  if (Y.isNull())
158  return X;
159 
160  switch (X.getKind()) {
162  llvm_unreachable("Non-deduced template arguments handled above");
163 
165  // If two template type arguments have the same type, they're compatible.
166  if (Y.getKind() == TemplateArgument::Type &&
167  Context.hasSameType(X.getAsType(), Y.getAsType()))
168  return X;
169 
170  return DeducedTemplateArgument();
171 
173  // If we deduced a constant in one case and either a dependent expression or
174  // declaration in another case, keep the integral constant.
175  // If both are integral constants with the same value, keep that value.
180  return DeducedTemplateArgument(X,
183 
184  // All other combinations are incompatible.
185  return DeducedTemplateArgument();
186 
188  if (Y.getKind() == TemplateArgument::Template &&
190  return X;
191 
192  // All other combinations are incompatible.
193  return DeducedTemplateArgument();
194 
199  return X;
200 
201  // All other combinations are incompatible.
202  return DeducedTemplateArgument();
203 
205  // If we deduced a dependent expression in one case and either an integral
206  // constant or a declaration in another case, keep the integral constant
207  // or declaration.
208  if (Y.getKind() == TemplateArgument::Integral ||
212 
214  // Compare the expressions for equality
215  llvm::FoldingSetNodeID ID1, ID2;
216  X.getAsExpr()->Profile(ID1, Context, true);
217  Y.getAsExpr()->Profile(ID2, Context, true);
218  if (ID1 == ID2)
219  return X;
220  }
221 
222  // All other combinations are incompatible.
223  return DeducedTemplateArgument();
224 
226  // If we deduced a declaration and a dependent expression, keep the
227  // declaration.
229  return X;
230 
231  // If we deduced a declaration and an integral constant, keep the
232  // integral constant.
234  return Y;
235 
236  // If we deduced two declarations, make sure they they refer to the
237  // same declaration.
240  return X;
241 
242  // All other combinations are incompatible.
243  return DeducedTemplateArgument();
244 
246  // If we deduced a null pointer and a dependent expression, keep the
247  // null pointer.
249  return X;
250 
251  // If we deduced a null pointer and an integral constant, keep the
252  // integral constant.
254  return Y;
255 
256  // If we deduced two null pointers, make sure they have the same type.
257  if (Y.getKind() == TemplateArgument::NullPtr &&
258  Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
259  return X;
260 
261  // All other combinations are incompatible.
262  return DeducedTemplateArgument();
263 
265  if (Y.getKind() != TemplateArgument::Pack ||
266  X.pack_size() != Y.pack_size())
267  return DeducedTemplateArgument();
268 
270  XAEnd = X.pack_end(),
271  YA = Y.pack_begin();
272  XA != XAEnd; ++XA, ++YA) {
273  // FIXME: Do we need to merge the results together here?
274  if (checkDeducedTemplateArguments(Context,
277  .isNull())
278  return DeducedTemplateArgument();
279  }
280 
281  return X;
282  }
283 
284  llvm_unreachable("Invalid TemplateArgument Kind!");
285 }
286 
287 /// \brief Deduce the value of the given non-type template parameter
288 /// from the given constant.
292  llvm::APSInt Value, QualType ValueType,
293  bool DeducedFromArrayBound,
294  TemplateDeductionInfo &Info,
295  SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
296  assert(NTTP->getDepth() == 0 &&
297  "Cannot deduce non-type template argument with depth > 0");
298 
299  DeducedTemplateArgument NewDeduced(S.Context, Value, ValueType,
300  DeducedFromArrayBound);
302  Deduced[NTTP->getIndex()],
303  NewDeduced);
304  if (Result.isNull()) {
305  Info.Param = NTTP;
306  Info.FirstArg = Deduced[NTTP->getIndex()];
307  Info.SecondArg = NewDeduced;
308  return Sema::TDK_Inconsistent;
309  }
310 
311  Deduced[NTTP->getIndex()] = Result;
312  return Sema::TDK_Success;
313 }
314 
315 /// \brief Deduce the value of the given non-type template parameter
316 /// from the given type- or value-dependent expression.
317 ///
318 /// \returns true if deduction succeeded, false otherwise.
322  Expr *Value,
323  TemplateDeductionInfo &Info,
324  SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
325  assert(NTTP->getDepth() == 0 &&
326  "Cannot deduce non-type template argument with depth > 0");
327  assert((Value->isTypeDependent() || Value->isValueDependent()) &&
328  "Expression template argument must be type- or value-dependent.");
329 
330  DeducedTemplateArgument NewDeduced(Value);
332  Deduced[NTTP->getIndex()],
333  NewDeduced);
334 
335  if (Result.isNull()) {
336  Info.Param = NTTP;
337  Info.FirstArg = Deduced[NTTP->getIndex()];
338  Info.SecondArg = NewDeduced;
339  return Sema::TDK_Inconsistent;
340  }
341 
342  Deduced[NTTP->getIndex()] = Result;
343  return Sema::TDK_Success;
344 }
345 
346 /// \brief Deduce the value of the given non-type template parameter
347 /// from the given declaration.
348 ///
349 /// \returns true if deduction succeeded, false otherwise.
353  ValueDecl *D,
354  TemplateDeductionInfo &Info,
355  SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
356  assert(NTTP->getDepth() == 0 &&
357  "Cannot deduce non-type template argument with depth > 0");
358 
359  D = D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
360  TemplateArgument New(D, NTTP->getType());
361  DeducedTemplateArgument NewDeduced(New);
363  Deduced[NTTP->getIndex()],
364  NewDeduced);
365  if (Result.isNull()) {
366  Info.Param = NTTP;
367  Info.FirstArg = Deduced[NTTP->getIndex()];
368  Info.SecondArg = NewDeduced;
369  return Sema::TDK_Inconsistent;
370  }
371 
372  Deduced[NTTP->getIndex()] = Result;
373  return Sema::TDK_Success;
374 }
375 
378  TemplateParameterList *TemplateParams,
379  TemplateName Param,
380  TemplateName Arg,
381  TemplateDeductionInfo &Info,
382  SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
383  TemplateDecl *ParamDecl = Param.getAsTemplateDecl();
384  if (!ParamDecl) {
385  // The parameter type is dependent and is not a template template parameter,
386  // so there is nothing that we can deduce.
387  return Sema::TDK_Success;
388  }
389 
390  if (TemplateTemplateParmDecl *TempParam
391  = dyn_cast<TemplateTemplateParmDecl>(ParamDecl)) {
394  Deduced[TempParam->getIndex()],
395  NewDeduced);
396  if (Result.isNull()) {
397  Info.Param = TempParam;
398  Info.FirstArg = Deduced[TempParam->getIndex()];
399  Info.SecondArg = NewDeduced;
400  return Sema::TDK_Inconsistent;
401  }
402 
403  Deduced[TempParam->getIndex()] = Result;
404  return Sema::TDK_Success;
405  }
406 
407  // Verify that the two template names are equivalent.
408  if (S.Context.hasSameTemplateName(Param, Arg))
409  return Sema::TDK_Success;
410 
411  // Mismatch of non-dependent template parameter to argument.
412  Info.FirstArg = TemplateArgument(Param);
413  Info.SecondArg = TemplateArgument(Arg);
415 }
416 
417 /// \brief Deduce the template arguments by comparing the template parameter
418 /// type (which is a template-id) with the template argument type.
419 ///
420 /// \param S the Sema
421 ///
422 /// \param TemplateParams the template parameters that we are deducing
423 ///
424 /// \param Param the parameter type
425 ///
426 /// \param Arg the argument type
427 ///
428 /// \param Info information about the template argument deduction itself
429 ///
430 /// \param Deduced the deduced template arguments
431 ///
432 /// \returns the result of template argument deduction so far. Note that a
433 /// "success" result means that template argument deduction has not yet failed,
434 /// but it may still fail, later, for other reasons.
437  TemplateParameterList *TemplateParams,
438  const TemplateSpecializationType *Param,
439  QualType Arg,
440  TemplateDeductionInfo &Info,
441  SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
442  assert(Arg.isCanonical() && "Argument type must be canonical");
443 
444  // Check whether the template argument is a dependent template-id.
445  if (const TemplateSpecializationType *SpecArg
446  = dyn_cast<TemplateSpecializationType>(Arg)) {
447  // Perform template argument deduction for the template name.
449  = DeduceTemplateArguments(S, TemplateParams,
450  Param->getTemplateName(),
451  SpecArg->getTemplateName(),
452  Info, Deduced))
453  return Result;
454 
455 
456  // Perform template argument deduction on each template
457  // argument. Ignore any missing/extra arguments, since they could be
458  // filled in by default arguments.
459  return DeduceTemplateArguments(S, TemplateParams,
460  Param->getArgs(), Param->getNumArgs(),
461  SpecArg->getArgs(), SpecArg->getNumArgs(),
462  Info, Deduced);
463  }
464 
465  // If the argument type is a class template specialization, we
466  // perform template argument deduction using its template
467  // arguments.
468  const RecordType *RecordArg = dyn_cast<RecordType>(Arg);
469  if (!RecordArg) {
470  Info.FirstArg = TemplateArgument(QualType(Param, 0));
471  Info.SecondArg = TemplateArgument(Arg);
473  }
474 
476  = dyn_cast<ClassTemplateSpecializationDecl>(RecordArg->getDecl());
477  if (!SpecArg) {
478  Info.FirstArg = TemplateArgument(QualType(Param, 0));
479  Info.SecondArg = TemplateArgument(Arg);
481  }
482 
483  // Perform template argument deduction for the template name.
486  TemplateParams,
487  Param->getTemplateName(),
489  Info, Deduced))
490  return Result;
491 
492  // Perform template argument deduction for the template arguments.
493  return DeduceTemplateArguments(S, TemplateParams,
494  Param->getArgs(), Param->getNumArgs(),
495  SpecArg->getTemplateArgs().data(),
496  SpecArg->getTemplateArgs().size(),
497  Info, Deduced);
498 }
499 
500 /// \brief Determines whether the given type is an opaque type that
501 /// might be more qualified when instantiated.
503  switch (T->getTypeClass()) {
504  case Type::TypeOfExpr:
505  case Type::TypeOf:
506  case Type::DependentName:
507  case Type::Decltype:
508  case Type::UnresolvedUsing:
509  case Type::TemplateTypeParm:
510  return true;
511 
512  case Type::ConstantArray:
513  case Type::IncompleteArray:
514  case Type::VariableArray:
515  case Type::DependentSizedArray:
517  cast<ArrayType>(T)->getElementType());
518 
519  default:
520  return false;
521  }
522 }
523 
524 /// \brief Retrieve the depth and index of a template parameter.
525 static std::pair<unsigned, unsigned>
527  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
528  return std::make_pair(TTP->getDepth(), TTP->getIndex());
529 
530  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
531  return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
532 
533  TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
534  return std::make_pair(TTP->getDepth(), TTP->getIndex());
535 }
536 
537 /// \brief Retrieve the depth and index of an unexpanded parameter pack.
538 static std::pair<unsigned, unsigned>
540  if (const TemplateTypeParmType *TTP
541  = UPP.first.dyn_cast<const TemplateTypeParmType *>())
542  return std::make_pair(TTP->getDepth(), TTP->getIndex());
543 
544  return getDepthAndIndex(UPP.first.get<NamedDecl *>());
545 }
546 
547 /// \brief Helper function to build a TemplateParameter when we don't
548 /// know its type statically.
550  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(D))
551  return TemplateParameter(TTP);
552  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D))
553  return TemplateParameter(NTTP);
554 
555  return TemplateParameter(cast<TemplateTemplateParmDecl>(D));
556 }
557 
558 /// A pack that we're currently deducing.
560  DeducedPack(unsigned Index) : Index(Index), Outer(nullptr) {}
561 
562  // The index of the pack.
563  unsigned Index;
564 
565  // The old value of the pack before we started deducing it.
567 
568  // A deferred value of this pack from an inner deduction, that couldn't be
569  // deduced because this deduction hadn't happened yet.
571 
572  // The new value of the pack.
574 
575  // The outer deduction for this pack, if any.
577 };
578 
579 namespace {
580 /// A scope in which we're performing pack deduction.
581 class PackDeductionScope {
582 public:
583  PackDeductionScope(Sema &S, TemplateParameterList *TemplateParams,
586  : S(S), TemplateParams(TemplateParams), Deduced(Deduced), Info(Info) {
587  // Compute the set of template parameter indices that correspond to
588  // parameter packs expanded by the pack expansion.
589  {
590  llvm::SmallBitVector SawIndices(TemplateParams->size());
592  S.collectUnexpandedParameterPacks(Pattern, Unexpanded);
593  for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
594  unsigned Depth, Index;
595  std::tie(Depth, Index) = getDepthAndIndex(Unexpanded[I]);
596  if (Depth == 0 && !SawIndices[Index]) {
597  SawIndices[Index] = true;
598 
599  // Save the deduced template argument for the parameter pack expanded
600  // by this pack expansion, then clear out the deduction.
601  DeducedPack Pack(Index);
602  Pack.Saved = Deduced[Index];
603  Deduced[Index] = TemplateArgument();
604 
605  Packs.push_back(Pack);
606  }
607  }
608  }
609  assert(!Packs.empty() && "Pack expansion without unexpanded packs?");
610 
611  for (auto &Pack : Packs) {
612  if (Info.PendingDeducedPacks.size() > Pack.Index)
613  Pack.Outer = Info.PendingDeducedPacks[Pack.Index];
614  else
615  Info.PendingDeducedPacks.resize(Pack.Index + 1);
616  Info.PendingDeducedPacks[Pack.Index] = &Pack;
617 
619  // If the template argument pack was explicitly specified, add that to
620  // the set of deduced arguments.
621  const TemplateArgument *ExplicitArgs;
622  unsigned NumExplicitArgs;
623  NamedDecl *PartiallySubstitutedPack =
625  &ExplicitArgs, &NumExplicitArgs);
626  if (PartiallySubstitutedPack &&
627  getDepthAndIndex(PartiallySubstitutedPack).second == Pack.Index)
628  Pack.New.append(ExplicitArgs, ExplicitArgs + NumExplicitArgs);
629  }
630  }
631  }
632 
633  ~PackDeductionScope() {
634  for (auto &Pack : Packs)
635  Info.PendingDeducedPacks[Pack.Index] = Pack.Outer;
636  }
637 
638  /// Move to deducing the next element in each pack that is being deduced.
639  void nextPackElement() {
640  // Capture the deduced template arguments for each parameter pack expanded
641  // by this pack expansion, add them to the list of arguments we've deduced
642  // for that pack, then clear out the deduced argument.
643  for (auto &Pack : Packs) {
644  DeducedTemplateArgument &DeducedArg = Deduced[Pack.Index];
645  if (!DeducedArg.isNull()) {
646  Pack.New.push_back(DeducedArg);
647  DeducedArg = DeducedTemplateArgument();
648  }
649  }
650  }
651 
652  /// \brief Finish template argument deduction for a set of argument packs,
653  /// producing the argument packs and checking for consistency with prior
654  /// deductions.
655  Sema::TemplateDeductionResult finish(bool HasAnyArguments) {
656  // Build argument packs for each of the parameter packs expanded by this
657  // pack expansion.
658  for (auto &Pack : Packs) {
659  // Put back the old value for this pack.
660  Deduced[Pack.Index] = Pack.Saved;
661 
662  // Build or find a new value for this pack.
663  DeducedTemplateArgument NewPack;
664  if (HasAnyArguments && Pack.New.empty()) {
665  if (Pack.DeferredDeduction.isNull()) {
666  // We were not able to deduce anything for this parameter pack
667  // (because it only appeared in non-deduced contexts), so just
668  // restore the saved argument pack.
669  continue;
670  }
671 
672  NewPack = Pack.DeferredDeduction;
673  Pack.DeferredDeduction = TemplateArgument();
674  } else if (Pack.New.empty()) {
675  // If we deduced an empty argument pack, create it now.
677  } else {
678  TemplateArgument *ArgumentPack =
679  new (S.Context) TemplateArgument[Pack.New.size()];
680  std::copy(Pack.New.begin(), Pack.New.end(), ArgumentPack);
681  NewPack = DeducedTemplateArgument(
682  TemplateArgument(llvm::makeArrayRef(ArgumentPack, Pack.New.size())),
683  Pack.New[0].wasDeducedFromArrayBound());
684  }
685 
686  // Pick where we're going to put the merged pack.
688  if (Pack.Outer) {
689  if (Pack.Outer->DeferredDeduction.isNull()) {
690  // Defer checking this pack until we have a complete pack to compare
691  // it against.
692  Pack.Outer->DeferredDeduction = NewPack;
693  continue;
694  }
695  Loc = &Pack.Outer->DeferredDeduction;
696  } else {
697  Loc = &Deduced[Pack.Index];
698  }
699 
700  // Check the new pack matches any previous value.
701  DeducedTemplateArgument OldPack = *Loc;
703  checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
704 
705  // If we deferred a deduction of this pack, check that one now too.
706  if (!Result.isNull() && !Pack.DeferredDeduction.isNull()) {
707  OldPack = Result;
708  NewPack = Pack.DeferredDeduction;
709  Result = checkDeducedTemplateArguments(S.Context, OldPack, NewPack);
710  }
711 
712  if (Result.isNull()) {
713  Info.Param =
714  makeTemplateParameter(TemplateParams->getParam(Pack.Index));
715  Info.FirstArg = OldPack;
716  Info.SecondArg = NewPack;
717  return Sema::TDK_Inconsistent;
718  }
719 
720  *Loc = Result;
721  }
722 
723  return Sema::TDK_Success;
724  }
725 
726 private:
727  Sema &S;
728  TemplateParameterList *TemplateParams;
730  TemplateDeductionInfo &Info;
731 
733 };
734 } // namespace
735 
736 /// \brief Deduce the template arguments by comparing the list of parameter
737 /// types to the list of argument types, as in the parameter-type-lists of
738 /// function types (C++ [temp.deduct.type]p10).
739 ///
740 /// \param S The semantic analysis object within which we are deducing
741 ///
742 /// \param TemplateParams The template parameters that we are deducing
743 ///
744 /// \param Params The list of parameter types
745 ///
746 /// \param NumParams The number of types in \c Params
747 ///
748 /// \param Args The list of argument types
749 ///
750 /// \param NumArgs The number of types in \c Args
751 ///
752 /// \param Info information about the template argument deduction itself
753 ///
754 /// \param Deduced the deduced template arguments
755 ///
756 /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
757 /// how template argument deduction is performed.
758 ///
759 /// \param PartialOrdering If true, we are performing template argument
760 /// deduction for during partial ordering for a call
761 /// (C++0x [temp.deduct.partial]).
762 ///
763 /// \returns the result of template argument deduction so far. Note that a
764 /// "success" result means that template argument deduction has not yet failed,
765 /// but it may still fail, later, for other reasons.
768  TemplateParameterList *TemplateParams,
769  const QualType *Params, unsigned NumParams,
770  const QualType *Args, unsigned NumArgs,
771  TemplateDeductionInfo &Info,
772  SmallVectorImpl<DeducedTemplateArgument> &Deduced,
773  unsigned TDF,
774  bool PartialOrdering = false) {
775  // Fast-path check to see if we have too many/too few arguments.
776  if (NumParams != NumArgs &&
777  !(NumParams && isa<PackExpansionType>(Params[NumParams - 1])) &&
778  !(NumArgs && isa<PackExpansionType>(Args[NumArgs - 1])))
780 
781  // C++0x [temp.deduct.type]p10:
782  // Similarly, if P has a form that contains (T), then each parameter type
783  // Pi of the respective parameter-type- list of P is compared with the
784  // corresponding parameter type Ai of the corresponding parameter-type-list
785  // of A. [...]
786  unsigned ArgIdx = 0, ParamIdx = 0;
787  for (; ParamIdx != NumParams; ++ParamIdx) {
788  // Check argument types.
789  const PackExpansionType *Expansion
790  = dyn_cast<PackExpansionType>(Params[ParamIdx]);
791  if (!Expansion) {
792  // Simple case: compare the parameter and argument types at this point.
793 
794  // Make sure we have an argument.
795  if (ArgIdx >= NumArgs)
797 
798  if (isa<PackExpansionType>(Args[ArgIdx])) {
799  // C++0x [temp.deduct.type]p22:
800  // If the original function parameter associated with A is a function
801  // parameter pack and the function parameter associated with P is not
802  // a function parameter pack, then template argument deduction fails.
804  }
805 
807  = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
808  Params[ParamIdx], Args[ArgIdx],
809  Info, Deduced, TDF,
810  PartialOrdering))
811  return Result;
812 
813  ++ArgIdx;
814  continue;
815  }
816 
817  // C++0x [temp.deduct.type]p5:
818  // The non-deduced contexts are:
819  // - A function parameter pack that does not occur at the end of the
820  // parameter-declaration-clause.
821  if (ParamIdx + 1 < NumParams)
822  return Sema::TDK_Success;
823 
824  // C++0x [temp.deduct.type]p10:
825  // If the parameter-declaration corresponding to Pi is a function
826  // parameter pack, then the type of its declarator- id is compared with
827  // each remaining parameter type in the parameter-type-list of A. Each
828  // comparison deduces template arguments for subsequent positions in the
829  // template parameter packs expanded by the function parameter pack.
830 
831  QualType Pattern = Expansion->getPattern();
832  PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
833 
834  bool HasAnyArguments = false;
835  for (; ArgIdx < NumArgs; ++ArgIdx) {
836  HasAnyArguments = true;
837 
838  // Deduce template arguments from the pattern.
840  = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, Pattern,
841  Args[ArgIdx], Info, Deduced,
842  TDF, PartialOrdering))
843  return Result;
844 
845  PackScope.nextPackElement();
846  }
847 
848  // Build argument packs for each of the parameter packs expanded by this
849  // pack expansion.
850  if (auto Result = PackScope.finish(HasAnyArguments))
851  return Result;
852  }
853 
854  // Make sure we don't have any extra arguments.
855  if (ArgIdx < NumArgs)
857 
858  return Sema::TDK_Success;
859 }
860 
861 /// \brief Determine whether the parameter has qualifiers that are either
862 /// inconsistent with or a superset of the argument's qualifiers.
864  QualType ArgType) {
865  Qualifiers ParamQs = ParamType.getQualifiers();
866  Qualifiers ArgQs = ArgType.getQualifiers();
867 
868  if (ParamQs == ArgQs)
869  return false;
870 
871  // Mismatched (but not missing) Objective-C GC attributes.
872  if (ParamQs.getObjCGCAttr() != ArgQs.getObjCGCAttr() &&
873  ParamQs.hasObjCGCAttr())
874  return true;
875 
876  // Mismatched (but not missing) address spaces.
877  if (ParamQs.getAddressSpace() != ArgQs.getAddressSpace() &&
878  ParamQs.hasAddressSpace())
879  return true;
880 
881  // Mismatched (but not missing) Objective-C lifetime qualifiers.
882  if (ParamQs.getObjCLifetime() != ArgQs.getObjCLifetime() &&
883  ParamQs.hasObjCLifetime())
884  return true;
885 
886  // CVR qualifier superset.
887  return (ParamQs.getCVRQualifiers() != ArgQs.getCVRQualifiers()) &&
888  ((ParamQs.getCVRQualifiers() | ArgQs.getCVRQualifiers())
889  == ParamQs.getCVRQualifiers());
890 }
891 
892 /// \brief Compare types for equality with respect to possibly compatible
893 /// function types (noreturn adjustment, implicit calling conventions). If any
894 /// of parameter and argument is not a function, just perform type comparison.
895 ///
896 /// \param Param the template parameter type.
897 ///
898 /// \param Arg the argument type.
900  CanQualType Arg) {
901  const FunctionType *ParamFunction = Param->getAs<FunctionType>(),
902  *ArgFunction = Arg->getAs<FunctionType>();
903 
904  // Just compare if not functions.
905  if (!ParamFunction || !ArgFunction)
906  return Param == Arg;
907 
908  // Noreturn adjustment.
909  QualType AdjustedParam;
910  if (IsNoReturnConversion(Param, Arg, AdjustedParam))
911  return Arg == Context.getCanonicalType(AdjustedParam);
912 
913  // FIXME: Compatible calling conventions.
914 
915  return Param == Arg;
916 }
917 
918 /// \brief Deduce the template arguments by comparing the parameter type and
919 /// the argument type (C++ [temp.deduct.type]).
920 ///
921 /// \param S the semantic analysis object within which we are deducing
922 ///
923 /// \param TemplateParams the template parameters that we are deducing
924 ///
925 /// \param ParamIn the parameter type
926 ///
927 /// \param ArgIn the argument type
928 ///
929 /// \param Info information about the template argument deduction itself
930 ///
931 /// \param Deduced the deduced template arguments
932 ///
933 /// \param TDF bitwise OR of the TemplateDeductionFlags bits that describe
934 /// how template argument deduction is performed.
935 ///
936 /// \param PartialOrdering Whether we're performing template argument deduction
937 /// in the context of partial ordering (C++0x [temp.deduct.partial]).
938 ///
939 /// \returns the result of template argument deduction so far. Note that a
940 /// "success" result means that template argument deduction has not yet failed,
941 /// but it may still fail, later, for other reasons.
944  TemplateParameterList *TemplateParams,
945  QualType ParamIn, QualType ArgIn,
946  TemplateDeductionInfo &Info,
947  SmallVectorImpl<DeducedTemplateArgument> &Deduced,
948  unsigned TDF,
949  bool PartialOrdering) {
950  // We only want to look at the canonical types, since typedefs and
951  // sugar are not part of template argument deduction.
952  QualType Param = S.Context.getCanonicalType(ParamIn);
953  QualType Arg = S.Context.getCanonicalType(ArgIn);
954 
955  // If the argument type is a pack expansion, look at its pattern.
956  // This isn't explicitly called out
957  if (const PackExpansionType *ArgExpansion
958  = dyn_cast<PackExpansionType>(Arg))
959  Arg = ArgExpansion->getPattern();
960 
961  if (PartialOrdering) {
962  // C++11 [temp.deduct.partial]p5:
963  // Before the partial ordering is done, certain transformations are
964  // performed on the types used for partial ordering:
965  // - If P is a reference type, P is replaced by the type referred to.
966  const ReferenceType *ParamRef = Param->getAs<ReferenceType>();
967  if (ParamRef)
968  Param = ParamRef->getPointeeType();
969 
970  // - If A is a reference type, A is replaced by the type referred to.
971  const ReferenceType *ArgRef = Arg->getAs<ReferenceType>();
972  if (ArgRef)
973  Arg = ArgRef->getPointeeType();
974 
975  if (ParamRef && ArgRef && S.Context.hasSameUnqualifiedType(Param, Arg)) {
976  // C++11 [temp.deduct.partial]p9:
977  // If, for a given type, deduction succeeds in both directions (i.e.,
978  // the types are identical after the transformations above) and both
979  // P and A were reference types [...]:
980  // - if [one type] was an lvalue reference and [the other type] was
981  // not, [the other type] is not considered to be at least as
982  // specialized as [the first type]
983  // - if [one type] is more cv-qualified than [the other type],
984  // [the other type] is not considered to be at least as specialized
985  // as [the first type]
986  // Objective-C ARC adds:
987  // - [one type] has non-trivial lifetime, [the other type] has
988  // __unsafe_unretained lifetime, and the types are otherwise
989  // identical
990  //
991  // A is "considered to be at least as specialized" as P iff deduction
992  // succeeds, so we model this as a deduction failure. Note that
993  // [the first type] is P and [the other type] is A here; the standard
994  // gets this backwards.
995  Qualifiers ParamQuals = Param.getQualifiers();
996  Qualifiers ArgQuals = Arg.getQualifiers();
997  if ((ParamRef->isLValueReferenceType() &&
998  !ArgRef->isLValueReferenceType()) ||
999  ParamQuals.isStrictSupersetOf(ArgQuals) ||
1000  (ParamQuals.hasNonTrivialObjCLifetime() &&
1002  ParamQuals.withoutObjCLifetime() ==
1003  ArgQuals.withoutObjCLifetime())) {
1004  Info.FirstArg = TemplateArgument(ParamIn);
1005  Info.SecondArg = TemplateArgument(ArgIn);
1007  }
1008  }
1009 
1010  // C++11 [temp.deduct.partial]p7:
1011  // Remove any top-level cv-qualifiers:
1012  // - If P is a cv-qualified type, P is replaced by the cv-unqualified
1013  // version of P.
1014  Param = Param.getUnqualifiedType();
1015  // - If A is a cv-qualified type, A is replaced by the cv-unqualified
1016  // version of A.
1017  Arg = Arg.getUnqualifiedType();
1018  } else {
1019  // C++0x [temp.deduct.call]p4 bullet 1:
1020  // - If the original P is a reference type, the deduced A (i.e., the type
1021  // referred to by the reference) can be more cv-qualified than the
1022  // transformed A.
1023  if (TDF & TDF_ParamWithReferenceType) {
1024  Qualifiers Quals;
1025  QualType UnqualParam = S.Context.getUnqualifiedArrayType(Param, Quals);
1026  Quals.setCVRQualifiers(Quals.getCVRQualifiers() &
1027  Arg.getCVRQualifiers());
1028  Param = S.Context.getQualifiedType(UnqualParam, Quals);
1029  }
1030 
1031  if ((TDF & TDF_TopLevelParameterTypeList) && !Param->isFunctionType()) {
1032  // C++0x [temp.deduct.type]p10:
1033  // If P and A are function types that originated from deduction when
1034  // taking the address of a function template (14.8.2.2) or when deducing
1035  // template arguments from a function declaration (14.8.2.6) and Pi and
1036  // Ai are parameters of the top-level parameter-type-list of P and A,
1037  // respectively, Pi is adjusted if it is an rvalue reference to a
1038  // cv-unqualified template parameter and Ai is an lvalue reference, in
1039  // which case the type of Pi is changed to be the template parameter
1040  // type (i.e., T&& is changed to simply T). [ Note: As a result, when
1041  // Pi is T&& and Ai is X&, the adjusted Pi will be T, causing T to be
1042  // deduced as X&. - end note ]
1043  TDF &= ~TDF_TopLevelParameterTypeList;
1044 
1045  if (const RValueReferenceType *ParamRef
1046  = Param->getAs<RValueReferenceType>()) {
1047  if (isa<TemplateTypeParmType>(ParamRef->getPointeeType()) &&
1048  !ParamRef->getPointeeType().getQualifiers())
1049  if (Arg->isLValueReferenceType())
1050  Param = ParamRef->getPointeeType();
1051  }
1052  }
1053  }
1054 
1055  // C++ [temp.deduct.type]p9:
1056  // A template type argument T, a template template argument TT or a
1057  // template non-type argument i can be deduced if P and A have one of
1058  // the following forms:
1059  //
1060  // T
1061  // cv-list T
1062  if (const TemplateTypeParmType *TemplateTypeParm
1063  = Param->getAs<TemplateTypeParmType>()) {
1064  // Just skip any attempts to deduce from a placeholder type.
1065  if (Arg->isPlaceholderType())
1066  return Sema::TDK_Success;
1067 
1068  unsigned Index = TemplateTypeParm->getIndex();
1069  bool RecanonicalizeArg = false;
1070 
1071  // If the argument type is an array type, move the qualifiers up to the
1072  // top level, so they can be matched with the qualifiers on the parameter.
1073  if (isa<ArrayType>(Arg)) {
1074  Qualifiers Quals;
1075  Arg = S.Context.getUnqualifiedArrayType(Arg, Quals);
1076  if (Quals) {
1077  Arg = S.Context.getQualifiedType(Arg, Quals);
1078  RecanonicalizeArg = true;
1079  }
1080  }
1081 
1082  // The argument type can not be less qualified than the parameter
1083  // type.
1084  if (!(TDF & TDF_IgnoreQualifiers) &&
1086  Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1087  Info.FirstArg = TemplateArgument(Param);
1088  Info.SecondArg = TemplateArgument(Arg);
1089  return Sema::TDK_Underqualified;
1090  }
1091 
1092  assert(TemplateTypeParm->getDepth() == 0 && "Can't deduce with depth > 0");
1093  assert(Arg != S.Context.OverloadTy && "Unresolved overloaded function");
1094  QualType DeducedType = Arg;
1095 
1096  // Remove any qualifiers on the parameter from the deduced type.
1097  // We checked the qualifiers for consistency above.
1098  Qualifiers DeducedQs = DeducedType.getQualifiers();
1099  Qualifiers ParamQs = Param.getQualifiers();
1100  DeducedQs.removeCVRQualifiers(ParamQs.getCVRQualifiers());
1101  if (ParamQs.hasObjCGCAttr())
1102  DeducedQs.removeObjCGCAttr();
1103  if (ParamQs.hasAddressSpace())
1104  DeducedQs.removeAddressSpace();
1105  if (ParamQs.hasObjCLifetime())
1106  DeducedQs.removeObjCLifetime();
1107 
1108  // Objective-C ARC:
1109  // If template deduction would produce a lifetime qualifier on a type
1110  // that is not a lifetime type, template argument deduction fails.
1111  if (ParamQs.hasObjCLifetime() && !DeducedType->isObjCLifetimeType() &&
1112  !DeducedType->isDependentType()) {
1113  Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1114  Info.FirstArg = TemplateArgument(Param);
1115  Info.SecondArg = TemplateArgument(Arg);
1116  return Sema::TDK_Underqualified;
1117  }
1118 
1119  // Objective-C ARC:
1120  // If template deduction would produce an argument type with lifetime type
1121  // but no lifetime qualifier, the __strong lifetime qualifier is inferred.
1122  if (S.getLangOpts().ObjCAutoRefCount &&
1123  DeducedType->isObjCLifetimeType() &&
1124  !DeducedQs.hasObjCLifetime())
1126 
1127  DeducedType = S.Context.getQualifiedType(DeducedType.getUnqualifiedType(),
1128  DeducedQs);
1129 
1130  if (RecanonicalizeArg)
1131  DeducedType = S.Context.getCanonicalType(DeducedType);
1132 
1133  DeducedTemplateArgument NewDeduced(DeducedType);
1135  Deduced[Index],
1136  NewDeduced);
1137  if (Result.isNull()) {
1138  Info.Param = cast<TemplateTypeParmDecl>(TemplateParams->getParam(Index));
1139  Info.FirstArg = Deduced[Index];
1140  Info.SecondArg = NewDeduced;
1141  return Sema::TDK_Inconsistent;
1142  }
1143 
1144  Deduced[Index] = Result;
1145  return Sema::TDK_Success;
1146  }
1147 
1148  // Set up the template argument deduction information for a failure.
1149  Info.FirstArg = TemplateArgument(ParamIn);
1150  Info.SecondArg = TemplateArgument(ArgIn);
1151 
1152  // If the parameter is an already-substituted template parameter
1153  // pack, do nothing: we don't know which of its arguments to look
1154  // at, so we have to wait until all of the parameter packs in this
1155  // expansion have arguments.
1156  if (isa<SubstTemplateTypeParmPackType>(Param))
1157  return Sema::TDK_Success;
1158 
1159  // Check the cv-qualifiers on the parameter and argument types.
1160  CanQualType CanParam = S.Context.getCanonicalType(Param);
1161  CanQualType CanArg = S.Context.getCanonicalType(Arg);
1162  if (!(TDF & TDF_IgnoreQualifiers)) {
1163  if (TDF & TDF_ParamWithReferenceType) {
1164  if (hasInconsistentOrSupersetQualifiersOf(Param, Arg))
1166  } else if (!IsPossiblyOpaquelyQualifiedType(Param)) {
1167  if (Param.getCVRQualifiers() != Arg.getCVRQualifiers())
1169  }
1170 
1171  // If the parameter type is not dependent, there is nothing to deduce.
1172  if (!Param->isDependentType()) {
1173  if (!(TDF & TDF_SkipNonDependent)) {
1174  bool NonDeduced = (TDF & TDF_InOverloadResolution)?
1175  !S.isSameOrCompatibleFunctionType(CanParam, CanArg) :
1176  Param != Arg;
1177  if (NonDeduced) {
1179  }
1180  }
1181  return Sema::TDK_Success;
1182  }
1183  } else if (!Param->isDependentType()) {
1184  CanQualType ParamUnqualType = CanParam.getUnqualifiedType(),
1185  ArgUnqualType = CanArg.getUnqualifiedType();
1186  bool Success = (TDF & TDF_InOverloadResolution)?
1187  S.isSameOrCompatibleFunctionType(ParamUnqualType,
1188  ArgUnqualType) :
1189  ParamUnqualType == ArgUnqualType;
1190  if (Success)
1191  return Sema::TDK_Success;
1192  }
1193 
1194  switch (Param->getTypeClass()) {
1195  // Non-canonical types cannot appear here.
1196 #define NON_CANONICAL_TYPE(Class, Base) \
1197  case Type::Class: llvm_unreachable("deducing non-canonical type: " #Class);
1198 #define TYPE(Class, Base)
1199 #include "clang/AST/TypeNodes.def"
1200 
1201  case Type::TemplateTypeParm:
1202  case Type::SubstTemplateTypeParmPack:
1203  llvm_unreachable("Type nodes handled above");
1204 
1205  // These types cannot be dependent, so simply check whether the types are
1206  // the same.
1207  case Type::Builtin:
1208  case Type::VariableArray:
1209  case Type::Vector:
1210  case Type::FunctionNoProto:
1211  case Type::Record:
1212  case Type::Enum:
1213  case Type::ObjCObject:
1214  case Type::ObjCInterface:
1215  case Type::ObjCObjectPointer: {
1216  if (TDF & TDF_SkipNonDependent)
1217  return Sema::TDK_Success;
1218 
1219  if (TDF & TDF_IgnoreQualifiers) {
1220  Param = Param.getUnqualifiedType();
1221  Arg = Arg.getUnqualifiedType();
1222  }
1223 
1224  return Param == Arg? Sema::TDK_Success : Sema::TDK_NonDeducedMismatch;
1225  }
1226 
1227  // _Complex T [placeholder extension]
1228  case Type::Complex:
1229  if (const ComplexType *ComplexArg = Arg->getAs<ComplexType>())
1230  return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1231  cast<ComplexType>(Param)->getElementType(),
1232  ComplexArg->getElementType(),
1233  Info, Deduced, TDF);
1234 
1236 
1237  // _Atomic T [extension]
1238  case Type::Atomic:
1239  if (const AtomicType *AtomicArg = Arg->getAs<AtomicType>())
1240  return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1241  cast<AtomicType>(Param)->getValueType(),
1242  AtomicArg->getValueType(),
1243  Info, Deduced, TDF);
1244 
1246 
1247  // T *
1248  case Type::Pointer: {
1249  QualType PointeeType;
1250  if (const PointerType *PointerArg = Arg->getAs<PointerType>()) {
1251  PointeeType = PointerArg->getPointeeType();
1252  } else if (const ObjCObjectPointerType *PointerArg
1253  = Arg->getAs<ObjCObjectPointerType>()) {
1254  PointeeType = PointerArg->getPointeeType();
1255  } else {
1257  }
1258 
1259  unsigned SubTDF = TDF & (TDF_IgnoreQualifiers | TDF_DerivedClass);
1260  return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1261  cast<PointerType>(Param)->getPointeeType(),
1262  PointeeType,
1263  Info, Deduced, SubTDF);
1264  }
1265 
1266  // T &
1267  case Type::LValueReference: {
1268  const LValueReferenceType *ReferenceArg =
1269  Arg->getAs<LValueReferenceType>();
1270  if (!ReferenceArg)
1272 
1273  return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1274  cast<LValueReferenceType>(Param)->getPointeeType(),
1275  ReferenceArg->getPointeeType(), Info, Deduced, 0);
1276  }
1277 
1278  // T && [C++0x]
1279  case Type::RValueReference: {
1280  const RValueReferenceType *ReferenceArg =
1281  Arg->getAs<RValueReferenceType>();
1282  if (!ReferenceArg)
1284 
1285  return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1286  cast<RValueReferenceType>(Param)->getPointeeType(),
1287  ReferenceArg->getPointeeType(),
1288  Info, Deduced, 0);
1289  }
1290 
1291  // T [] (implied, but not stated explicitly)
1292  case Type::IncompleteArray: {
1293  const IncompleteArrayType *IncompleteArrayArg =
1295  if (!IncompleteArrayArg)
1297 
1298  unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1299  return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1301  IncompleteArrayArg->getElementType(),
1302  Info, Deduced, SubTDF);
1303  }
1304 
1305  // T [integer-constant]
1306  case Type::ConstantArray: {
1307  const ConstantArrayType *ConstantArrayArg =
1309  if (!ConstantArrayArg)
1311 
1312  const ConstantArrayType *ConstantArrayParm =
1314  if (ConstantArrayArg->getSize() != ConstantArrayParm->getSize())
1315  return Sema::TDK_NonDeducedMismatch;
1316 
1317  unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1318  return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1319  ConstantArrayParm->getElementType(),
1320  ConstantArrayArg->getElementType(),
1321  Info, Deduced, SubTDF);
1322  }
1323 
1324  // type [i]
1325  case Type::DependentSizedArray: {
1326  const ArrayType *ArrayArg = S.Context.getAsArrayType(Arg);
1327  if (!ArrayArg)
1329 
1330  unsigned SubTDF = TDF & TDF_IgnoreQualifiers;
1331 
1332  // Check the element type of the arrays
1333  const DependentSizedArrayType *DependentArrayParm
1336  = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1337  DependentArrayParm->getElementType(),
1338  ArrayArg->getElementType(),
1339  Info, Deduced, SubTDF))
1340  return Result;
1341 
1342  // Determine the array bound is something we can deduce.
1344  = getDeducedParameterFromExpr(DependentArrayParm->getSizeExpr());
1345  if (!NTTP)
1346  return Sema::TDK_Success;
1347 
1348  // We can perform template argument deduction for the given non-type
1349  // template parameter.
1350  assert(NTTP->getDepth() == 0 &&
1351  "Cannot deduce non-type template argument at depth > 0");
1352  if (const ConstantArrayType *ConstantArrayArg
1353  = dyn_cast<ConstantArrayType>(ArrayArg)) {
1354  llvm::APSInt Size(ConstantArrayArg->getSize());
1355  return DeduceNonTypeTemplateArgument(S, NTTP, Size,
1356  S.Context.getSizeType(),
1357  /*ArrayBound=*/true,
1358  Info, Deduced);
1359  }
1360  if (const DependentSizedArrayType *DependentArrayArg
1361  = dyn_cast<DependentSizedArrayType>(ArrayArg))
1362  if (DependentArrayArg->getSizeExpr())
1363  return DeduceNonTypeTemplateArgument(S, NTTP,
1364  DependentArrayArg->getSizeExpr(),
1365  Info, Deduced);
1366 
1367  // Incomplete type does not match a dependently-sized array type
1369  }
1370 
1371  // type(*)(T)
1372  // T(*)()
1373  // T(*)(T)
1374  case Type::FunctionProto: {
1375  unsigned SubTDF = TDF & TDF_TopLevelParameterTypeList;
1376  const FunctionProtoType *FunctionProtoArg =
1377  dyn_cast<FunctionProtoType>(Arg);
1378  if (!FunctionProtoArg)
1380 
1381  const FunctionProtoType *FunctionProtoParam =
1382  cast<FunctionProtoType>(Param);
1383 
1384  if (FunctionProtoParam->getTypeQuals()
1385  != FunctionProtoArg->getTypeQuals() ||
1386  FunctionProtoParam->getRefQualifier()
1387  != FunctionProtoArg->getRefQualifier() ||
1388  FunctionProtoParam->isVariadic() != FunctionProtoArg->isVariadic())
1389  return Sema::TDK_NonDeducedMismatch;
1390 
1391  // Check return types.
1394  S, TemplateParams, FunctionProtoParam->getReturnType(),
1395  FunctionProtoArg->getReturnType(), Info, Deduced, 0))
1396  return Result;
1397 
1398  return DeduceTemplateArguments(
1399  S, TemplateParams, FunctionProtoParam->param_type_begin(),
1400  FunctionProtoParam->getNumParams(),
1401  FunctionProtoArg->param_type_begin(),
1402  FunctionProtoArg->getNumParams(), Info, Deduced, SubTDF);
1403  }
1404 
1405  case Type::InjectedClassName: {
1406  // Treat a template's injected-class-name as if the template
1407  // specialization type had been used.
1408  Param = cast<InjectedClassNameType>(Param)
1409  ->getInjectedSpecializationType();
1410  assert(isa<TemplateSpecializationType>(Param) &&
1411  "injected class name is not a template specialization type");
1412  // fall through
1413  }
1414 
1415  // template-name<T> (where template-name refers to a class template)
1416  // template-name<i>
1417  // TT<T>
1418  // TT<i>
1419  // TT<>
1420  case Type::TemplateSpecialization: {
1421  const TemplateSpecializationType *SpecParam
1422  = cast<TemplateSpecializationType>(Param);
1423 
1424  // Try to deduce template arguments from the template-id.
1426  = DeduceTemplateArguments(S, TemplateParams, SpecParam, Arg,
1427  Info, Deduced);
1428 
1429  if (Result && (TDF & TDF_DerivedClass)) {
1430  // C++ [temp.deduct.call]p3b3:
1431  // If P is a class, and P has the form template-id, then A can be a
1432  // derived class of the deduced A. Likewise, if P is a pointer to a
1433  // class of the form template-id, A can be a pointer to a derived
1434  // class pointed to by the deduced A.
1435  //
1436  // More importantly:
1437  // These alternatives are considered only if type deduction would
1438  // otherwise fail.
1439  if (const RecordType *RecordT = Arg->getAs<RecordType>()) {
1440  // We cannot inspect base classes as part of deduction when the type
1441  // is incomplete, so either instantiate any templates necessary to
1442  // complete the type, or skip over it if it cannot be completed.
1443  if (!S.isCompleteType(Info.getLocation(), Arg))
1444  return Result;
1445 
1446  // Use data recursion to crawl through the list of base classes.
1447  // Visited contains the set of nodes we have already visited, while
1448  // ToVisit is our stack of records that we still need to visit.
1449  llvm::SmallPtrSet<const RecordType *, 8> Visited;
1451  ToVisit.push_back(RecordT);
1452  bool Successful = false;
1453  SmallVector<DeducedTemplateArgument, 8> DeducedOrig(Deduced.begin(),
1454  Deduced.end());
1455  while (!ToVisit.empty()) {
1456  // Retrieve the next class in the inheritance hierarchy.
1457  const RecordType *NextT = ToVisit.pop_back_val();
1458 
1459  // If we have already seen this type, skip it.
1460  if (!Visited.insert(NextT).second)
1461  continue;
1462 
1463  // If this is a base class, try to perform template argument
1464  // deduction from it.
1465  if (NextT != RecordT) {
1466  TemplateDeductionInfo BaseInfo(Info.getLocation());
1468  = DeduceTemplateArguments(S, TemplateParams, SpecParam,
1469  QualType(NextT, 0), BaseInfo,
1470  Deduced);
1471 
1472  // If template argument deduction for this base was successful,
1473  // note that we had some success. Otherwise, ignore any deductions
1474  // from this base class.
1475  if (BaseResult == Sema::TDK_Success) {
1476  Successful = true;
1477  DeducedOrig.clear();
1478  DeducedOrig.append(Deduced.begin(), Deduced.end());
1479  Info.Param = BaseInfo.Param;
1480  Info.FirstArg = BaseInfo.FirstArg;
1481  Info.SecondArg = BaseInfo.SecondArg;
1482  }
1483  else
1484  Deduced = DeducedOrig;
1485  }
1486 
1487  // Visit base classes
1488  CXXRecordDecl *Next = cast<CXXRecordDecl>(NextT->getDecl());
1489  for (const auto &Base : Next->bases()) {
1490  assert(Base.getType()->isRecordType() &&
1491  "Base class that isn't a record?");
1492  ToVisit.push_back(Base.getType()->getAs<RecordType>());
1493  }
1494  }
1495 
1496  if (Successful)
1497  return Sema::TDK_Success;
1498  }
1499 
1500  }
1501 
1502  return Result;
1503  }
1504 
1505  // T type::*
1506  // T T::*
1507  // T (type::*)()
1508  // type (T::*)()
1509  // type (type::*)(T)
1510  // type (T::*)(T)
1511  // T (type::*)(T)
1512  // T (T::*)()
1513  // T (T::*)(T)
1514  case Type::MemberPointer: {
1515  const MemberPointerType *MemPtrParam = cast<MemberPointerType>(Param);
1516  const MemberPointerType *MemPtrArg = dyn_cast<MemberPointerType>(Arg);
1517  if (!MemPtrArg)
1519 
1520  QualType ParamPointeeType = MemPtrParam->getPointeeType();
1521  if (ParamPointeeType->isFunctionType())
1522  S.adjustMemberFunctionCC(ParamPointeeType, /*IsStatic=*/true,
1523  /*IsCtorOrDtor=*/false, Info.getLocation());
1524  QualType ArgPointeeType = MemPtrArg->getPointeeType();
1525  if (ArgPointeeType->isFunctionType())
1526  S.adjustMemberFunctionCC(ArgPointeeType, /*IsStatic=*/true,
1527  /*IsCtorOrDtor=*/false, Info.getLocation());
1528 
1530  = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1531  ParamPointeeType,
1532  ArgPointeeType,
1533  Info, Deduced,
1534  TDF & TDF_IgnoreQualifiers))
1535  return Result;
1536 
1537  return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1538  QualType(MemPtrParam->getClass(), 0),
1539  QualType(MemPtrArg->getClass(), 0),
1540  Info, Deduced,
1541  TDF & TDF_IgnoreQualifiers);
1542  }
1543 
1544  // (clang extension)
1545  //
1546  // type(^)(T)
1547  // T(^)()
1548  // T(^)(T)
1549  case Type::BlockPointer: {
1550  const BlockPointerType *BlockPtrParam = cast<BlockPointerType>(Param);
1551  const BlockPointerType *BlockPtrArg = dyn_cast<BlockPointerType>(Arg);
1552 
1553  if (!BlockPtrArg)
1555 
1556  return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1557  BlockPtrParam->getPointeeType(),
1558  BlockPtrArg->getPointeeType(),
1559  Info, Deduced, 0);
1560  }
1561 
1562  // (clang extension)
1563  //
1564  // T __attribute__(((ext_vector_type(<integral constant>))))
1565  case Type::ExtVector: {
1566  const ExtVectorType *VectorParam = cast<ExtVectorType>(Param);
1567  if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1568  // Make sure that the vectors have the same number of elements.
1569  if (VectorParam->getNumElements() != VectorArg->getNumElements())
1570  return Sema::TDK_NonDeducedMismatch;
1571 
1572  // Perform deduction on the element types.
1573  return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1574  VectorParam->getElementType(),
1575  VectorArg->getElementType(),
1576  Info, Deduced, TDF);
1577  }
1578 
1579  if (const DependentSizedExtVectorType *VectorArg
1580  = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1581  // We can't check the number of elements, since the argument has a
1582  // dependent number of elements. This can only occur during partial
1583  // ordering.
1584 
1585  // Perform deduction on the element types.
1586  return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1587  VectorParam->getElementType(),
1588  VectorArg->getElementType(),
1589  Info, Deduced, TDF);
1590  }
1591 
1593  }
1594 
1595  // (clang extension)
1596  //
1597  // T __attribute__(((ext_vector_type(N))))
1598  case Type::DependentSizedExtVector: {
1599  const DependentSizedExtVectorType *VectorParam
1600  = cast<DependentSizedExtVectorType>(Param);
1601 
1602  if (const ExtVectorType *VectorArg = dyn_cast<ExtVectorType>(Arg)) {
1603  // Perform deduction on the element types.
1605  = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1606  VectorParam->getElementType(),
1607  VectorArg->getElementType(),
1608  Info, Deduced, TDF))
1609  return Result;
1610 
1611  // Perform deduction on the vector size, if we can.
1613  = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1614  if (!NTTP)
1615  return Sema::TDK_Success;
1616 
1617  llvm::APSInt ArgSize(S.Context.getTypeSize(S.Context.IntTy), false);
1618  ArgSize = VectorArg->getNumElements();
1619  return DeduceNonTypeTemplateArgument(S, NTTP, ArgSize, S.Context.IntTy,
1620  false, Info, Deduced);
1621  }
1622 
1623  if (const DependentSizedExtVectorType *VectorArg
1624  = dyn_cast<DependentSizedExtVectorType>(Arg)) {
1625  // Perform deduction on the element types.
1627  = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1628  VectorParam->getElementType(),
1629  VectorArg->getElementType(),
1630  Info, Deduced, TDF))
1631  return Result;
1632 
1633  // Perform deduction on the vector size, if we can.
1635  = getDeducedParameterFromExpr(VectorParam->getSizeExpr());
1636  if (!NTTP)
1637  return Sema::TDK_Success;
1638 
1639  return DeduceNonTypeTemplateArgument(S, NTTP, VectorArg->getSizeExpr(),
1640  Info, Deduced);
1641  }
1642 
1644  }
1645 
1646  case Type::TypeOfExpr:
1647  case Type::TypeOf:
1648  case Type::DependentName:
1649  case Type::UnresolvedUsing:
1650  case Type::Decltype:
1651  case Type::UnaryTransform:
1652  case Type::Auto:
1653  case Type::DependentTemplateSpecialization:
1654  case Type::PackExpansion:
1655  case Type::Pipe:
1656  // No template argument deduction for these types
1657  return Sema::TDK_Success;
1658  }
1659 
1660  llvm_unreachable("Invalid Type Class!");
1661 }
1662 
1665  TemplateParameterList *TemplateParams,
1666  const TemplateArgument &Param,
1667  TemplateArgument Arg,
1668  TemplateDeductionInfo &Info,
1669  SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
1670  // If the template argument is a pack expansion, perform template argument
1671  // deduction against the pattern of that expansion. This only occurs during
1672  // partial ordering.
1673  if (Arg.isPackExpansion())
1674  Arg = Arg.getPackExpansionPattern();
1675 
1676  switch (Param.getKind()) {
1678  llvm_unreachable("Null template argument in parameter list");
1679 
1681  if (Arg.getKind() == TemplateArgument::Type)
1682  return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
1683  Param.getAsType(),
1684  Arg.getAsType(),
1685  Info, Deduced, 0);
1686  Info.FirstArg = Param;
1687  Info.SecondArg = Arg;
1689 
1691  if (Arg.getKind() == TemplateArgument::Template)
1692  return DeduceTemplateArguments(S, TemplateParams,
1693  Param.getAsTemplate(),
1694  Arg.getAsTemplate(), Info, Deduced);
1695  Info.FirstArg = Param;
1696  Info.SecondArg = Arg;
1698 
1700  llvm_unreachable("caller should handle pack expansions");
1701 
1703  if (Arg.getKind() == TemplateArgument::Declaration &&
1704  isSameDeclaration(Param.getAsDecl(), Arg.getAsDecl()))
1705  return Sema::TDK_Success;
1706 
1707  Info.FirstArg = Param;
1708  Info.SecondArg = Arg;
1710 
1712  if (Arg.getKind() == TemplateArgument::NullPtr &&
1714  return Sema::TDK_Success;
1715 
1716  Info.FirstArg = Param;
1717  Info.SecondArg = Arg;
1719 
1721  if (Arg.getKind() == TemplateArgument::Integral) {
1722  if (hasSameExtendedValue(Param.getAsIntegral(), Arg.getAsIntegral()))
1723  return Sema::TDK_Success;
1724 
1725  Info.FirstArg = Param;
1726  Info.SecondArg = Arg;
1728  }
1729 
1730  if (Arg.getKind() == TemplateArgument::Expression) {
1731  Info.FirstArg = Param;
1732  Info.SecondArg = Arg;
1734  }
1735 
1736  Info.FirstArg = Param;
1737  Info.SecondArg = Arg;
1739 
1741  if (NonTypeTemplateParmDecl *NTTP
1743  if (Arg.getKind() == TemplateArgument::Integral)
1744  return DeduceNonTypeTemplateArgument(S, NTTP,
1745  Arg.getAsIntegral(),
1746  Arg.getIntegralType(),
1747  /*ArrayBound=*/false,
1748  Info, Deduced);
1750  return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsExpr(),
1751  Info, Deduced);
1753  return DeduceNonTypeTemplateArgument(S, NTTP, Arg.getAsDecl(),
1754  Info, Deduced);
1755 
1756  Info.FirstArg = Param;
1757  Info.SecondArg = Arg;
1759  }
1760 
1761  // Can't deduce anything, but that's okay.
1762  return Sema::TDK_Success;
1763  }
1765  llvm_unreachable("Argument packs should be expanded by the caller!");
1766  }
1767 
1768  llvm_unreachable("Invalid TemplateArgument Kind!");
1769 }
1770 
1771 /// \brief Determine whether there is a template argument to be used for
1772 /// deduction.
1773 ///
1774 /// This routine "expands" argument packs in-place, overriding its input
1775 /// parameters so that \c Args[ArgIdx] will be the available template argument.
1776 ///
1777 /// \returns true if there is another template argument (which will be at
1778 /// \c Args[ArgIdx]), false otherwise.
1780  unsigned &ArgIdx,
1781  unsigned &NumArgs) {
1782  if (ArgIdx == NumArgs)
1783  return false;
1784 
1785  const TemplateArgument &Arg = Args[ArgIdx];
1786  if (Arg.getKind() != TemplateArgument::Pack)
1787  return true;
1788 
1789  assert(ArgIdx == NumArgs - 1 && "Pack not at the end of argument list?");
1790  Args = Arg.pack_begin();
1791  NumArgs = Arg.pack_size();
1792  ArgIdx = 0;
1793  return ArgIdx < NumArgs;
1794 }
1795 
1796 /// \brief Determine whether the given set of template arguments has a pack
1797 /// expansion that is not the last template argument.
1799  unsigned NumArgs) {
1800  unsigned ArgIdx = 0;
1801  while (ArgIdx < NumArgs) {
1802  const TemplateArgument &Arg = Args[ArgIdx];
1803 
1804  // Unwrap argument packs.
1805  if (Args[ArgIdx].getKind() == TemplateArgument::Pack) {
1806  Args = Arg.pack_begin();
1807  NumArgs = Arg.pack_size();
1808  ArgIdx = 0;
1809  continue;
1810  }
1811 
1812  ++ArgIdx;
1813  if (ArgIdx == NumArgs)
1814  return false;
1815 
1816  if (Arg.isPackExpansion())
1817  return true;
1818  }
1819 
1820  return false;
1821 }
1822 
1825  TemplateParameterList *TemplateParams,
1826  const TemplateArgument *Params, unsigned NumParams,
1827  const TemplateArgument *Args, unsigned NumArgs,
1828  TemplateDeductionInfo &Info,
1829  SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
1830  // C++0x [temp.deduct.type]p9:
1831  // If the template argument list of P contains a pack expansion that is not
1832  // the last template argument, the entire template argument list is a
1833  // non-deduced context.
1834  if (hasPackExpansionBeforeEnd(Params, NumParams))
1835  return Sema::TDK_Success;
1836 
1837  // C++0x [temp.deduct.type]p9:
1838  // If P has a form that contains <T> or <i>, then each argument Pi of the
1839  // respective template argument list P is compared with the corresponding
1840  // argument Ai of the corresponding template argument list of A.
1841  unsigned ArgIdx = 0, ParamIdx = 0;
1842  for (; hasTemplateArgumentForDeduction(Params, ParamIdx, NumParams);
1843  ++ParamIdx) {
1844  if (!Params[ParamIdx].isPackExpansion()) {
1845  // The simple case: deduce template arguments by matching Pi and Ai.
1846 
1847  // Check whether we have enough arguments.
1848  if (!hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs))
1849  return Sema::TDK_Success;
1850 
1851  if (Args[ArgIdx].isPackExpansion()) {
1852  // FIXME: We follow the logic of C++0x [temp.deduct.type]p22 here,
1853  // but applied to pack expansions that are template arguments.
1855  }
1856 
1857  // Perform deduction for this Pi/Ai pair.
1859  = DeduceTemplateArguments(S, TemplateParams,
1860  Params[ParamIdx], Args[ArgIdx],
1861  Info, Deduced))
1862  return Result;
1863 
1864  // Move to the next argument.
1865  ++ArgIdx;
1866  continue;
1867  }
1868 
1869  // The parameter is a pack expansion.
1870 
1871  // C++0x [temp.deduct.type]p9:
1872  // If Pi is a pack expansion, then the pattern of Pi is compared with
1873  // each remaining argument in the template argument list of A. Each
1874  // comparison deduces template arguments for subsequent positions in the
1875  // template parameter packs expanded by Pi.
1876  TemplateArgument Pattern = Params[ParamIdx].getPackExpansionPattern();
1877 
1878  // FIXME: If there are no remaining arguments, we can bail out early
1879  // and set any deduced parameter packs to an empty argument pack.
1880  // The latter part of this is a (minor) correctness issue.
1881 
1882  // Prepare to deduce the packs within the pattern.
1883  PackDeductionScope PackScope(S, TemplateParams, Deduced, Info, Pattern);
1884 
1885  // Keep track of the deduced template arguments for each parameter pack
1886  // expanded by this pack expansion (the outer index) and for each
1887  // template argument (the inner SmallVectors).
1888  bool HasAnyArguments = false;
1889  for (; hasTemplateArgumentForDeduction(Args, ArgIdx, NumArgs); ++ArgIdx) {
1890  HasAnyArguments = true;
1891 
1892  // Deduce template arguments from the pattern.
1894  = DeduceTemplateArguments(S, TemplateParams, Pattern, Args[ArgIdx],
1895  Info, Deduced))
1896  return Result;
1897 
1898  PackScope.nextPackElement();
1899  }
1900 
1901  // Build argument packs for each of the parameter packs expanded by this
1902  // pack expansion.
1903  if (auto Result = PackScope.finish(HasAnyArguments))
1904  return Result;
1905  }
1906 
1907  return Sema::TDK_Success;
1908 }
1909 
1912  TemplateParameterList *TemplateParams,
1913  const TemplateArgumentList &ParamList,
1914  const TemplateArgumentList &ArgList,
1915  TemplateDeductionInfo &Info,
1916  SmallVectorImpl<DeducedTemplateArgument> &Deduced) {
1917  return DeduceTemplateArguments(S, TemplateParams,
1918  ParamList.data(), ParamList.size(),
1919  ArgList.data(), ArgList.size(),
1920  Info, Deduced);
1921 }
1922 
1923 /// \brief Determine whether two template arguments are the same.
1925  const TemplateArgument &X,
1926  const TemplateArgument &Y) {
1927  if (X.getKind() != Y.getKind())
1928  return false;
1929 
1930  switch (X.getKind()) {
1932  llvm_unreachable("Comparing NULL template argument");
1933 
1935  return Context.getCanonicalType(X.getAsType()) ==
1936  Context.getCanonicalType(Y.getAsType());
1937 
1939  return isSameDeclaration(X.getAsDecl(), Y.getAsDecl());
1940 
1942  return Context.hasSameType(X.getNullPtrType(), Y.getNullPtrType());
1943 
1946  return Context.getCanonicalTemplateName(
1947  X.getAsTemplateOrTemplatePattern()).getAsVoidPointer() ==
1948  Context.getCanonicalTemplateName(
1949  Y.getAsTemplateOrTemplatePattern()).getAsVoidPointer();
1950 
1952  return X.getAsIntegral() == Y.getAsIntegral();
1953 
1955  llvm::FoldingSetNodeID XID, YID;
1956  X.getAsExpr()->Profile(XID, Context, true);
1957  Y.getAsExpr()->Profile(YID, Context, true);
1958  return XID == YID;
1959  }
1960 
1962  if (X.pack_size() != Y.pack_size())
1963  return false;
1964 
1966  XPEnd = X.pack_end(),
1967  YP = Y.pack_begin();
1968  XP != XPEnd; ++XP, ++YP)
1969  if (!isSameTemplateArg(Context, *XP, *YP))
1970  return false;
1971 
1972  return true;
1973  }
1974 
1975  llvm_unreachable("Invalid TemplateArgument Kind!");
1976 }
1977 
1978 /// \brief Allocate a TemplateArgumentLoc where all locations have
1979 /// been initialized to the given location.
1980 ///
1981 /// \param S The semantic analysis object.
1982 ///
1983 /// \param Arg The template argument we are producing template argument
1984 /// location information for.
1985 ///
1986 /// \param NTTPType For a declaration template argument, the type of
1987 /// the non-type template parameter that corresponds to this template
1988 /// argument.
1989 ///
1990 /// \param Loc The source location to use for the resulting template
1991 /// argument.
1992 static TemplateArgumentLoc
1994  const TemplateArgument &Arg,
1995  QualType NTTPType,
1996  SourceLocation Loc) {
1997  switch (Arg.getKind()) {
1999  llvm_unreachable("Can't get a NULL template argument here");
2000 
2002  return TemplateArgumentLoc(Arg,
2004 
2006  Expr *E
2007  = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2008  .getAs<Expr>();
2009  return TemplateArgumentLoc(TemplateArgument(E), E);
2010  }
2011 
2013  Expr *E
2014  = S.BuildExpressionFromDeclTemplateArgument(Arg, NTTPType, Loc)
2015  .getAs<Expr>();
2016  return TemplateArgumentLoc(TemplateArgument(NTTPType, /*isNullPtr*/true),
2017  E);
2018  }
2019 
2021  Expr *E
2023  return TemplateArgumentLoc(TemplateArgument(E), E);
2024  }
2025 
2029  TemplateName Template = Arg.getAsTemplate();
2030  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
2031  Builder.MakeTrivial(S.Context, DTN->getQualifier(), Loc);
2032  else if (QualifiedTemplateName *QTN =
2033  Template.getAsQualifiedTemplateName())
2034  Builder.MakeTrivial(S.Context, QTN->getQualifier(), Loc);
2035 
2036  if (Arg.getKind() == TemplateArgument::Template)
2037  return TemplateArgumentLoc(Arg,
2038  Builder.getWithLocInContext(S.Context),
2039  Loc);
2040 
2041 
2042  return TemplateArgumentLoc(Arg, Builder.getWithLocInContext(S.Context),
2043  Loc, Loc);
2044  }
2045 
2047  return TemplateArgumentLoc(Arg, Arg.getAsExpr());
2048 
2051  }
2052 
2053  llvm_unreachable("Invalid TemplateArgument Kind!");
2054 }
2055 
2056 
2057 /// \brief Convert the given deduced template argument and add it to the set of
2058 /// fully-converted template arguments.
2059 static bool
2062  NamedDecl *Template,
2063  QualType NTTPType,
2064  unsigned ArgumentPackIndex,
2065  TemplateDeductionInfo &Info,
2066  bool InFunctionTemplate,
2067  SmallVectorImpl<TemplateArgument> &Output) {
2068  if (Arg.getKind() == TemplateArgument::Pack) {
2069  // This is a template argument pack, so check each of its arguments against
2070  // the template parameter.
2071  SmallVector<TemplateArgument, 2> PackedArgsBuilder;
2072  for (const auto &P : Arg.pack_elements()) {
2073  // When converting the deduced template argument, append it to the
2074  // general output list. We need to do this so that the template argument
2075  // checking logic has all of the prior template arguments available.
2076  DeducedTemplateArgument InnerArg(P);
2078  if (ConvertDeducedTemplateArgument(S, Param, InnerArg, Template,
2079  NTTPType, PackedArgsBuilder.size(),
2080  Info, InFunctionTemplate, Output))
2081  return true;
2082 
2083  // Move the converted template argument into our argument pack.
2084  PackedArgsBuilder.push_back(Output.pop_back_val());
2085  }
2086 
2087  // Create the resulting argument pack.
2088  Output.push_back(
2089  TemplateArgument::CreatePackCopy(S.Context, PackedArgsBuilder));
2090  return false;
2091  }
2092 
2093  // Convert the deduced template argument into a template
2094  // argument that we can check, almost as if the user had written
2095  // the template argument explicitly.
2096  TemplateArgumentLoc ArgLoc = getTrivialTemplateArgumentLoc(S, Arg, NTTPType,
2097  Info.getLocation());
2098 
2099  // Check the template argument, converting it as necessary.
2100  return S.CheckTemplateArgument(Param, ArgLoc,
2101  Template,
2102  Template->getLocation(),
2103  Template->getSourceRange().getEnd(),
2104  ArgumentPackIndex,
2105  Output,
2106  InFunctionTemplate
2107  ? (Arg.wasDeducedFromArrayBound()
2111 }
2112 
2113 /// Complete template argument deduction for a class template partial
2114 /// specialization.
2118  const TemplateArgumentList &TemplateArgs,
2119  SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2120  TemplateDeductionInfo &Info) {
2121  // Unevaluated SFINAE context.
2123  Sema::SFINAETrap Trap(S);
2124 
2125  Sema::ContextRAII SavedContext(S, Partial);
2126 
2127  // C++ [temp.deduct.type]p2:
2128  // [...] or if any template argument remains neither deduced nor
2129  // explicitly specified, template argument deduction fails.
2131  TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2132  for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
2133  NamedDecl *Param = PartialParams->getParam(I);
2134  if (Deduced[I].isNull()) {
2135  Info.Param = makeTemplateParameter(Param);
2136  return Sema::TDK_Incomplete;
2137  }
2138 
2139  // We have deduced this argument, so it still needs to be
2140  // checked and converted.
2141 
2142  // First, for a non-type template parameter type that is
2143  // initialized by a declaration, we need the type of the
2144  // corresponding non-type template parameter.
2145  QualType NTTPType;
2146  if (NonTypeTemplateParmDecl *NTTP
2147  = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2148  NTTPType = NTTP->getType();
2149  if (NTTPType->isDependentType()) {
2151  Builder.data(), Builder.size());
2152  NTTPType = S.SubstType(NTTPType,
2153  MultiLevelTemplateArgumentList(TemplateArgs),
2154  NTTP->getLocation(),
2155  NTTP->getDeclName());
2156  if (NTTPType.isNull()) {
2157  Info.Param = makeTemplateParameter(Param);
2158  // FIXME: These template arguments are temporary. Free them!
2160  Builder.data(),
2161  Builder.size()));
2163  }
2164  }
2165  }
2166 
2167  if (ConvertDeducedTemplateArgument(S, Param, Deduced[I],
2168  Partial, NTTPType, 0, Info, false,
2169  Builder)) {
2170  Info.Param = makeTemplateParameter(Param);
2171  // FIXME: These template arguments are temporary. Free them!
2172  Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2173  Builder.size()));
2175  }
2176  }
2177 
2178  // Form the template argument list from the deduced template arguments.
2179  TemplateArgumentList *DeducedArgumentList
2180  = TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2181  Builder.size());
2182 
2183  Info.reset(DeducedArgumentList);
2184 
2185  // Substitute the deduced template arguments into the template
2186  // arguments of the class template partial specialization, and
2187  // verify that the instantiated template arguments are both valid
2188  // and are equivalent to the template arguments originally provided
2189  // to the class template.
2190  LocalInstantiationScope InstScope(S);
2191  ClassTemplateDecl *ClassTemplate = Partial->getSpecializedTemplate();
2192  const ASTTemplateArgumentListInfo *PartialTemplArgInfo
2193  = Partial->getTemplateArgsAsWritten();
2194  const TemplateArgumentLoc *PartialTemplateArgs
2195  = PartialTemplArgInfo->getTemplateArgs();
2196 
2197  TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2198  PartialTemplArgInfo->RAngleLoc);
2199 
2200  if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
2201  InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2202  unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2203  if (ParamIdx >= Partial->getTemplateParameters()->size())
2204  ParamIdx = Partial->getTemplateParameters()->size() - 1;
2205 
2206  Decl *Param
2207  = const_cast<NamedDecl *>(
2208  Partial->getTemplateParameters()->getParam(ParamIdx));
2209  Info.Param = makeTemplateParameter(Param);
2210  Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2212  }
2213 
2214  SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2215  if (S.CheckTemplateArgumentList(ClassTemplate, Partial->getLocation(),
2216  InstArgs, false, ConvertedInstArgs))
2218 
2219  TemplateParameterList *TemplateParams
2220  = ClassTemplate->getTemplateParameters();
2221  for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2222  TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2223  if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2224  Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2225  Info.FirstArg = TemplateArgs[I];
2226  Info.SecondArg = InstArg;
2228  }
2229  }
2230 
2231  if (Trap.hasErrorOccurred())
2233 
2234  return Sema::TDK_Success;
2235 }
2236 
2237 /// \brief Perform template argument deduction to determine whether
2238 /// the given template arguments match the given class template
2239 /// partial specialization per C++ [temp.class.spec.match].
2242  const TemplateArgumentList &TemplateArgs,
2243  TemplateDeductionInfo &Info) {
2244  if (Partial->isInvalidDecl())
2245  return TDK_Invalid;
2246 
2247  // C++ [temp.class.spec.match]p2:
2248  // A partial specialization matches a given actual template
2249  // argument list if the template arguments of the partial
2250  // specialization can be deduced from the actual template argument
2251  // list (14.8.2).
2252 
2253  // Unevaluated SFINAE context.
2255  SFINAETrap Trap(*this);
2256 
2258  Deduced.resize(Partial->getTemplateParameters()->size());
2260  = ::DeduceTemplateArguments(*this,
2261  Partial->getTemplateParameters(),
2262  Partial->getTemplateArgs(),
2263  TemplateArgs, Info, Deduced))
2264  return Result;
2265 
2266  SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2267  InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2268  Info);
2269  if (Inst.isInvalid())
2270  return TDK_InstantiationDepth;
2271 
2272  if (Trap.hasErrorOccurred())
2274 
2275  return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
2276  Deduced, Info);
2277 }
2278 
2279 /// Complete template argument deduction for a variable template partial
2280 /// specialization.
2281 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2282 /// May require unifying ClassTemplate(Partial)SpecializationDecl and
2283 /// VarTemplate(Partial)SpecializationDecl with a new data
2284 /// structure Template(Partial)SpecializationDecl, and
2285 /// using Template(Partial)SpecializationDecl as input type.
2288  const TemplateArgumentList &TemplateArgs,
2289  SmallVectorImpl<DeducedTemplateArgument> &Deduced,
2290  TemplateDeductionInfo &Info) {
2291  // Unevaluated SFINAE context.
2293  Sema::SFINAETrap Trap(S);
2294 
2295  // C++ [temp.deduct.type]p2:
2296  // [...] or if any template argument remains neither deduced nor
2297  // explicitly specified, template argument deduction fails.
2299  TemplateParameterList *PartialParams = Partial->getTemplateParameters();
2300  for (unsigned I = 0, N = PartialParams->size(); I != N; ++I) {
2301  NamedDecl *Param = PartialParams->getParam(I);
2302  if (Deduced[I].isNull()) {
2303  Info.Param = makeTemplateParameter(Param);
2304  return Sema::TDK_Incomplete;
2305  }
2306 
2307  // We have deduced this argument, so it still needs to be
2308  // checked and converted.
2309 
2310  // First, for a non-type template parameter type that is
2311  // initialized by a declaration, we need the type of the
2312  // corresponding non-type template parameter.
2313  QualType NTTPType;
2314  if (NonTypeTemplateParmDecl *NTTP =
2315  dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2316  NTTPType = NTTP->getType();
2317  if (NTTPType->isDependentType()) {
2319  Builder.data(), Builder.size());
2320  NTTPType =
2321  S.SubstType(NTTPType, MultiLevelTemplateArgumentList(TemplateArgs),
2322  NTTP->getLocation(), NTTP->getDeclName());
2323  if (NTTPType.isNull()) {
2324  Info.Param = makeTemplateParameter(Param);
2325  // FIXME: These template arguments are temporary. Free them!
2326  Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2327  Builder.size()));
2329  }
2330  }
2331  }
2332 
2333  if (ConvertDeducedTemplateArgument(S, Param, Deduced[I], Partial, NTTPType,
2334  0, Info, false, Builder)) {
2335  Info.Param = makeTemplateParameter(Param);
2336  // FIXME: These template arguments are temporary. Free them!
2337  Info.reset(TemplateArgumentList::CreateCopy(S.Context, Builder.data(),
2338  Builder.size()));
2340  }
2341  }
2342 
2343  // Form the template argument list from the deduced template arguments.
2345  S.Context, Builder.data(), Builder.size());
2346 
2347  Info.reset(DeducedArgumentList);
2348 
2349  // Substitute the deduced template arguments into the template
2350  // arguments of the class template partial specialization, and
2351  // verify that the instantiated template arguments are both valid
2352  // and are equivalent to the template arguments originally provided
2353  // to the class template.
2354  LocalInstantiationScope InstScope(S);
2355  VarTemplateDecl *VarTemplate = Partial->getSpecializedTemplate();
2356  const ASTTemplateArgumentListInfo *PartialTemplArgInfo
2357  = Partial->getTemplateArgsAsWritten();
2358  const TemplateArgumentLoc *PartialTemplateArgs
2359  = PartialTemplArgInfo->getTemplateArgs();
2360 
2361  TemplateArgumentListInfo InstArgs(PartialTemplArgInfo->LAngleLoc,
2362  PartialTemplArgInfo->RAngleLoc);
2363 
2364  if (S.Subst(PartialTemplateArgs, PartialTemplArgInfo->NumTemplateArgs,
2365  InstArgs, MultiLevelTemplateArgumentList(*DeducedArgumentList))) {
2366  unsigned ArgIdx = InstArgs.size(), ParamIdx = ArgIdx;
2367  if (ParamIdx >= Partial->getTemplateParameters()->size())
2368  ParamIdx = Partial->getTemplateParameters()->size() - 1;
2369 
2370  Decl *Param = const_cast<NamedDecl *>(
2371  Partial->getTemplateParameters()->getParam(ParamIdx));
2372  Info.Param = makeTemplateParameter(Param);
2373  Info.FirstArg = PartialTemplateArgs[ArgIdx].getArgument();
2375  }
2376  SmallVector<TemplateArgument, 4> ConvertedInstArgs;
2377  if (S.CheckTemplateArgumentList(VarTemplate, Partial->getLocation(), InstArgs,
2378  false, ConvertedInstArgs))
2380 
2381  TemplateParameterList *TemplateParams = VarTemplate->getTemplateParameters();
2382  for (unsigned I = 0, E = TemplateParams->size(); I != E; ++I) {
2383  TemplateArgument InstArg = ConvertedInstArgs.data()[I];
2384  if (!isSameTemplateArg(S.Context, TemplateArgs[I], InstArg)) {
2385  Info.Param = makeTemplateParameter(TemplateParams->getParam(I));
2386  Info.FirstArg = TemplateArgs[I];
2387  Info.SecondArg = InstArg;
2389  }
2390  }
2391 
2392  if (Trap.hasErrorOccurred())
2394 
2395  return Sema::TDK_Success;
2396 }
2397 
2398 /// \brief Perform template argument deduction to determine whether
2399 /// the given template arguments match the given variable template
2400 /// partial specialization per C++ [temp.class.spec.match].
2401 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2402 /// May require unifying ClassTemplate(Partial)SpecializationDecl and
2403 /// VarTemplate(Partial)SpecializationDecl with a new data
2404 /// structure Template(Partial)SpecializationDecl, and
2405 /// using Template(Partial)SpecializationDecl as input type.
2408  const TemplateArgumentList &TemplateArgs,
2409  TemplateDeductionInfo &Info) {
2410  if (Partial->isInvalidDecl())
2411  return TDK_Invalid;
2412 
2413  // C++ [temp.class.spec.match]p2:
2414  // A partial specialization matches a given actual template
2415  // argument list if the template arguments of the partial
2416  // specialization can be deduced from the actual template argument
2417  // list (14.8.2).
2418 
2419  // Unevaluated SFINAE context.
2421  SFINAETrap Trap(*this);
2422 
2424  Deduced.resize(Partial->getTemplateParameters()->size());
2426  *this, Partial->getTemplateParameters(), Partial->getTemplateArgs(),
2427  TemplateArgs, Info, Deduced))
2428  return Result;
2429 
2430  SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2431  InstantiatingTemplate Inst(*this, Info.getLocation(), Partial, DeducedArgs,
2432  Info);
2433  if (Inst.isInvalid())
2434  return TDK_InstantiationDepth;
2435 
2436  if (Trap.hasErrorOccurred())
2438 
2439  return ::FinishTemplateArgumentDeduction(*this, Partial, TemplateArgs,
2440  Deduced, Info);
2441 }
2442 
2443 /// \brief Determine whether the given type T is a simple-template-id type.
2445  if (const TemplateSpecializationType *Spec
2447  return Spec->getTemplateName().getAsTemplateDecl() != nullptr;
2448 
2449  return false;
2450 }
2451 
2452 /// \brief Substitute the explicitly-provided template arguments into the
2453 /// given function template according to C++ [temp.arg.explicit].
2454 ///
2455 /// \param FunctionTemplate the function template into which the explicit
2456 /// template arguments will be substituted.
2457 ///
2458 /// \param ExplicitTemplateArgs the explicitly-specified template
2459 /// arguments.
2460 ///
2461 /// \param Deduced the deduced template arguments, which will be populated
2462 /// with the converted and checked explicit template arguments.
2463 ///
2464 /// \param ParamTypes will be populated with the instantiated function
2465 /// parameters.
2466 ///
2467 /// \param FunctionType if non-NULL, the result type of the function template
2468 /// will also be instantiated and the pointed-to value will be updated with
2469 /// the instantiated function type.
2470 ///
2471 /// \param Info if substitution fails for any reason, this object will be
2472 /// populated with more information about the failure.
2473 ///
2474 /// \returns TDK_Success if substitution was successful, or some failure
2475 /// condition.
2478  FunctionTemplateDecl *FunctionTemplate,
2479  TemplateArgumentListInfo &ExplicitTemplateArgs,
2481  SmallVectorImpl<QualType> &ParamTypes,
2483  TemplateDeductionInfo &Info) {
2484  FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
2485  TemplateParameterList *TemplateParams
2486  = FunctionTemplate->getTemplateParameters();
2487 
2488  if (ExplicitTemplateArgs.size() == 0) {
2489  // No arguments to substitute; just copy over the parameter types and
2490  // fill in the function type.
2491  for (auto P : Function->params())
2492  ParamTypes.push_back(P->getType());
2493 
2494  if (FunctionType)
2495  *FunctionType = Function->getType();
2496  return TDK_Success;
2497  }
2498 
2499  // Unevaluated SFINAE context.
2501  SFINAETrap Trap(*this);
2502 
2503  // C++ [temp.arg.explicit]p3:
2504  // Template arguments that are present shall be specified in the
2505  // declaration order of their corresponding template-parameters. The
2506  // template argument list shall not specify more template-arguments than
2507  // there are corresponding template-parameters.
2509 
2510  // Enter a new template instantiation context where we check the
2511  // explicitly-specified template arguments against this function template,
2512  // and then substitute them into the function parameter types.
2513  SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2514  InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2515  DeducedArgs,
2517  Info);
2518  if (Inst.isInvalid())
2519  return TDK_InstantiationDepth;
2520 
2521  if (CheckTemplateArgumentList(FunctionTemplate,
2522  SourceLocation(),
2523  ExplicitTemplateArgs,
2524  true,
2525  Builder) || Trap.hasErrorOccurred()) {
2526  unsigned Index = Builder.size();
2527  if (Index >= TemplateParams->size())
2528  Index = TemplateParams->size() - 1;
2529  Info.Param = makeTemplateParameter(TemplateParams->getParam(Index));
2531  }
2532 
2533  // Form the template argument list from the explicitly-specified
2534  // template arguments.
2535  TemplateArgumentList *ExplicitArgumentList
2536  = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
2537  Info.reset(ExplicitArgumentList);
2538 
2539  // Template argument deduction and the final substitution should be
2540  // done in the context of the templated declaration. Explicit
2541  // argument substitution, on the other hand, needs to happen in the
2542  // calling context.
2543  ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2544 
2545  // If we deduced template arguments for a template parameter pack,
2546  // note that the template argument pack is partially substituted and record
2547  // the explicit template arguments. They'll be used as part of deduction
2548  // for this template parameter pack.
2549  for (unsigned I = 0, N = Builder.size(); I != N; ++I) {
2550  const TemplateArgument &Arg = Builder[I];
2551  if (Arg.getKind() == TemplateArgument::Pack) {
2553  TemplateParams->getParam(I),
2554  Arg.pack_begin(),
2555  Arg.pack_size());
2556  break;
2557  }
2558  }
2559 
2560  const FunctionProtoType *Proto
2561  = Function->getType()->getAs<FunctionProtoType>();
2562  assert(Proto && "Function template does not have a prototype?");
2563 
2564  // Isolate our substituted parameters from our caller.
2565  LocalInstantiationScope InstScope(*this, /*MergeWithOuterScope*/true);
2566 
2567  // Instantiate the types of each of the function parameters given the
2568  // explicitly-specified template arguments. If the function has a trailing
2569  // return type, substitute it after the arguments to ensure we substitute
2570  // in lexical order.
2571  if (Proto->hasTrailingReturn()) {
2572  if (SubstParmTypes(Function->getLocation(),
2573  Function->param_begin(), Function->getNumParams(),
2574  MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2575  ParamTypes))
2576  return TDK_SubstitutionFailure;
2577  }
2578 
2579  // Instantiate the return type.
2580  QualType ResultType;
2581  {
2582  // C++11 [expr.prim.general]p3:
2583  // If a declaration declares a member function or member function
2584  // template of a class X, the expression this is a prvalue of type
2585  // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2586  // and the end of the function-definition, member-declarator, or
2587  // declarator.
2588  unsigned ThisTypeQuals = 0;
2589  CXXRecordDecl *ThisContext = nullptr;
2590  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2591  ThisContext = Method->getParent();
2592  ThisTypeQuals = Method->getTypeQualifiers();
2593  }
2594 
2595  CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals,
2597 
2598  ResultType =
2599  SubstType(Proto->getReturnType(),
2600  MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2601  Function->getTypeSpecStartLoc(), Function->getDeclName());
2602  if (ResultType.isNull() || Trap.hasErrorOccurred())
2603  return TDK_SubstitutionFailure;
2604  }
2605 
2606  // Instantiate the types of each of the function parameters given the
2607  // explicitly-specified template arguments if we didn't do so earlier.
2608  if (!Proto->hasTrailingReturn() &&
2609  SubstParmTypes(Function->getLocation(),
2610  Function->param_begin(), Function->getNumParams(),
2611  MultiLevelTemplateArgumentList(*ExplicitArgumentList),
2612  ParamTypes))
2613  return TDK_SubstitutionFailure;
2614 
2615  if (FunctionType) {
2616  *FunctionType = BuildFunctionType(ResultType, ParamTypes,
2617  Function->getLocation(),
2618  Function->getDeclName(),
2619  Proto->getExtProtoInfo());
2620  if (FunctionType->isNull() || Trap.hasErrorOccurred())
2621  return TDK_SubstitutionFailure;
2622  }
2623 
2624  // C++ [temp.arg.explicit]p2:
2625  // Trailing template arguments that can be deduced (14.8.2) may be
2626  // omitted from the list of explicit template-arguments. If all of the
2627  // template arguments can be deduced, they may all be omitted; in this
2628  // case, the empty template argument list <> itself may also be omitted.
2629  //
2630  // Take all of the explicitly-specified arguments and put them into
2631  // the set of deduced template arguments. Explicitly-specified
2632  // parameter packs, however, will be set to NULL since the deduction
2633  // mechanisms handle explicitly-specified argument packs directly.
2634  Deduced.reserve(TemplateParams->size());
2635  for (unsigned I = 0, N = ExplicitArgumentList->size(); I != N; ++I) {
2636  const TemplateArgument &Arg = ExplicitArgumentList->get(I);
2637  if (Arg.getKind() == TemplateArgument::Pack)
2638  Deduced.push_back(DeducedTemplateArgument());
2639  else
2640  Deduced.push_back(Arg);
2641  }
2642 
2643  return TDK_Success;
2644 }
2645 
2646 /// \brief Check whether the deduced argument type for a call to a function
2647 /// template matches the actual argument type per C++ [temp.deduct.call]p4.
2648 static bool
2650  QualType DeducedA) {
2651  ASTContext &Context = S.Context;
2652 
2653  QualType A = OriginalArg.OriginalArgType;
2654  QualType OriginalParamType = OriginalArg.OriginalParamType;
2655 
2656  // Check for type equality (top-level cv-qualifiers are ignored).
2657  if (Context.hasSameUnqualifiedType(A, DeducedA))
2658  return false;
2659 
2660  // Strip off references on the argument types; they aren't needed for
2661  // the following checks.
2662  if (const ReferenceType *DeducedARef = DeducedA->getAs<ReferenceType>())
2663  DeducedA = DeducedARef->getPointeeType();
2664  if (const ReferenceType *ARef = A->getAs<ReferenceType>())
2665  A = ARef->getPointeeType();
2666 
2667  // C++ [temp.deduct.call]p4:
2668  // [...] However, there are three cases that allow a difference:
2669  // - If the original P is a reference type, the deduced A (i.e., the
2670  // type referred to by the reference) can be more cv-qualified than
2671  // the transformed A.
2672  if (const ReferenceType *OriginalParamRef
2673  = OriginalParamType->getAs<ReferenceType>()) {
2674  // We don't want to keep the reference around any more.
2675  OriginalParamType = OriginalParamRef->getPointeeType();
2676 
2677  Qualifiers AQuals = A.getQualifiers();
2678  Qualifiers DeducedAQuals = DeducedA.getQualifiers();
2679 
2680  // Under Objective-C++ ARC, the deduced type may have implicitly
2681  // been given strong or (when dealing with a const reference)
2682  // unsafe_unretained lifetime. If so, update the original
2683  // qualifiers to include this lifetime.
2684  if (S.getLangOpts().ObjCAutoRefCount &&
2685  ((DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_Strong &&
2686  AQuals.getObjCLifetime() == Qualifiers::OCL_None) ||
2687  (DeducedAQuals.hasConst() &&
2688  DeducedAQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone))) {
2689  AQuals.setObjCLifetime(DeducedAQuals.getObjCLifetime());
2690  }
2691 
2692  if (AQuals == DeducedAQuals) {
2693  // Qualifiers match; there's nothing to do.
2694  } else if (!DeducedAQuals.compatiblyIncludes(AQuals)) {
2695  return true;
2696  } else {
2697  // Qualifiers are compatible, so have the argument type adopt the
2698  // deduced argument type's qualifiers as if we had performed the
2699  // qualification conversion.
2700  A = Context.getQualifiedType(A.getUnqualifiedType(), DeducedAQuals);
2701  }
2702  }
2703 
2704  // - The transformed A can be another pointer or pointer to member
2705  // type that can be converted to the deduced A via a qualification
2706  // conversion.
2707  //
2708  // Also allow conversions which merely strip [[noreturn]] from function types
2709  // (recursively) as an extension.
2710  // FIXME: Currently, this doesn't play nicely with qualification conversions.
2711  bool ObjCLifetimeConversion = false;
2712  QualType ResultTy;
2713  if ((A->isAnyPointerType() || A->isMemberPointerType()) &&
2714  (S.IsQualificationConversion(A, DeducedA, false,
2715  ObjCLifetimeConversion) ||
2716  S.IsNoReturnConversion(A, DeducedA, ResultTy)))
2717  return false;
2718 
2719 
2720  // - If P is a class and P has the form simple-template-id, then the
2721  // transformed A can be a derived class of the deduced A. [...]
2722  // [...] Likewise, if P is a pointer to a class of the form
2723  // simple-template-id, the transformed A can be a pointer to a
2724  // derived class pointed to by the deduced A.
2725  if (const PointerType *OriginalParamPtr
2726  = OriginalParamType->getAs<PointerType>()) {
2727  if (const PointerType *DeducedAPtr = DeducedA->getAs<PointerType>()) {
2728  if (const PointerType *APtr = A->getAs<PointerType>()) {
2729  if (A->getPointeeType()->isRecordType()) {
2730  OriginalParamType = OriginalParamPtr->getPointeeType();
2731  DeducedA = DeducedAPtr->getPointeeType();
2732  A = APtr->getPointeeType();
2733  }
2734  }
2735  }
2736  }
2737 
2738  if (Context.hasSameUnqualifiedType(A, DeducedA))
2739  return false;
2740 
2741  if (A->isRecordType() && isSimpleTemplateIdType(OriginalParamType) &&
2742  S.IsDerivedFrom(SourceLocation(), A, DeducedA))
2743  return false;
2744 
2745  return true;
2746 }
2747 
2748 /// \brief Finish template argument deduction for a function template,
2749 /// checking the deduced template arguments for completeness and forming
2750 /// the function template specialization.
2751 ///
2752 /// \param OriginalCallArgs If non-NULL, the original call arguments against
2753 /// which the deduced argument types should be compared.
2757  unsigned NumExplicitlySpecified,
2758  FunctionDecl *&Specialization,
2759  TemplateDeductionInfo &Info,
2760  SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs,
2761  bool PartialOverloading) {
2762  TemplateParameterList *TemplateParams
2763  = FunctionTemplate->getTemplateParameters();
2764 
2765  // Unevaluated SFINAE context.
2767  SFINAETrap Trap(*this);
2768 
2769  // Enter a new template instantiation context while we instantiate the
2770  // actual function declaration.
2771  SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(), Deduced.end());
2772  InstantiatingTemplate Inst(*this, Info.getLocation(), FunctionTemplate,
2773  DeducedArgs,
2775  Info);
2776  if (Inst.isInvalid())
2777  return TDK_InstantiationDepth;
2778 
2779  ContextRAII SavedContext(*this, FunctionTemplate->getTemplatedDecl());
2780 
2781  // C++ [temp.deduct.type]p2:
2782  // [...] or if any template argument remains neither deduced nor
2783  // explicitly specified, template argument deduction fails.
2785  for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
2786  NamedDecl *Param = TemplateParams->getParam(I);
2787 
2788  if (!Deduced[I].isNull()) {
2789  if (I < NumExplicitlySpecified) {
2790  // We have already fully type-checked and converted this
2791  // argument, because it was explicitly-specified. Just record the
2792  // presence of this argument.
2793  Builder.push_back(Deduced[I]);
2794  // We may have had explicitly-specified template arguments for a
2795  // template parameter pack (that may or may not have been extended
2796  // via additional deduced arguments).
2797  if (Param->isParameterPack() && CurrentInstantiationScope) {
2799  Param) {
2800  // Forget the partially-substituted pack; its substitution is now
2801  // complete.
2803  }
2804  }
2805  continue;
2806  }
2807  // We have deduced this argument, so it still needs to be
2808  // checked and converted.
2809 
2810  // First, for a non-type template parameter type that is
2811  // initialized by a declaration, we need the type of the
2812  // corresponding non-type template parameter.
2813  QualType NTTPType;
2814  if (NonTypeTemplateParmDecl *NTTP
2815  = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2816  NTTPType = NTTP->getType();
2817  if (NTTPType->isDependentType()) {
2819  Builder.data(), Builder.size());
2820  NTTPType = SubstType(NTTPType,
2821  MultiLevelTemplateArgumentList(TemplateArgs),
2822  NTTP->getLocation(),
2823  NTTP->getDeclName());
2824  if (NTTPType.isNull()) {
2825  Info.Param = makeTemplateParameter(Param);
2826  // FIXME: These template arguments are temporary. Free them!
2828  Builder.data(),
2829  Builder.size()));
2830  return TDK_SubstitutionFailure;
2831  }
2832  }
2833  }
2834 
2835  if (ConvertDeducedTemplateArgument(*this, Param, Deduced[I],
2836  FunctionTemplate, NTTPType, 0, Info,
2837  true, Builder)) {
2838  Info.Param = makeTemplateParameter(Param);
2839  // FIXME: These template arguments are temporary. Free them!
2840  Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2841  Builder.size()));
2842  return TDK_SubstitutionFailure;
2843  }
2844 
2845  continue;
2846  }
2847 
2848  // C++0x [temp.arg.explicit]p3:
2849  // A trailing template parameter pack (14.5.3) not otherwise deduced will
2850  // be deduced to an empty sequence of template arguments.
2851  // FIXME: Where did the word "trailing" come from?
2852  if (Param->isTemplateParameterPack()) {
2853  // We may have had explicitly-specified template arguments for this
2854  // template parameter pack. If so, our empty deduction extends the
2855  // explicitly-specified set (C++0x [temp.arg.explicit]p9).
2856  const TemplateArgument *ExplicitArgs;
2857  unsigned NumExplicitArgs;
2860  &NumExplicitArgs)
2861  == Param) {
2862  Builder.push_back(TemplateArgument(
2863  llvm::makeArrayRef(ExplicitArgs, NumExplicitArgs)));
2864 
2865  // Forget the partially-substituted pack; it's substitution is now
2866  // complete.
2868  } else {
2869  Builder.push_back(TemplateArgument::getEmptyPack());
2870  }
2871  continue;
2872  }
2873 
2874  // Substitute into the default template argument, if available.
2875  bool HasDefaultArg = false;
2876  TemplateArgumentLoc DefArg
2877  = SubstDefaultTemplateArgumentIfAvailable(FunctionTemplate,
2878  FunctionTemplate->getLocation(),
2879  FunctionTemplate->getSourceRange().getEnd(),
2880  Param,
2881  Builder, HasDefaultArg);
2882 
2883  // If there was no default argument, deduction is incomplete.
2884  if (DefArg.getArgument().isNull()) {
2886  const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2887  Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2888  Builder.size()));
2889  if (PartialOverloading) break;
2890 
2891  return HasDefaultArg ? TDK_SubstitutionFailure : TDK_Incomplete;
2892  }
2893 
2894  // Check whether we can actually use the default argument.
2895  if (CheckTemplateArgument(Param, DefArg,
2896  FunctionTemplate,
2897  FunctionTemplate->getLocation(),
2898  FunctionTemplate->getSourceRange().getEnd(),
2899  0, Builder,
2900  CTAK_Specified)) {
2902  const_cast<NamedDecl *>(TemplateParams->getParam(I)));
2903  // FIXME: These template arguments are temporary. Free them!
2904  Info.reset(TemplateArgumentList::CreateCopy(Context, Builder.data(),
2905  Builder.size()));
2906  return TDK_SubstitutionFailure;
2907  }
2908 
2909  // If we get here, we successfully used the default template argument.
2910  }
2911 
2912  // Form the template argument list from the deduced template arguments.
2913  TemplateArgumentList *DeducedArgumentList
2914  = TemplateArgumentList::CreateCopy(Context, Builder.data(), Builder.size());
2915  Info.reset(DeducedArgumentList);
2916 
2917  // Substitute the deduced template arguments into the function template
2918  // declaration to produce the function template specialization.
2919  DeclContext *Owner = FunctionTemplate->getDeclContext();
2920  if (FunctionTemplate->getFriendObjectKind())
2921  Owner = FunctionTemplate->getLexicalDeclContext();
2922  Specialization = cast_or_null<FunctionDecl>(
2923  SubstDecl(FunctionTemplate->getTemplatedDecl(), Owner,
2924  MultiLevelTemplateArgumentList(*DeducedArgumentList)));
2925  if (!Specialization || Specialization->isInvalidDecl())
2926  return TDK_SubstitutionFailure;
2927 
2928  assert(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
2929  FunctionTemplate->getCanonicalDecl());
2930 
2931  // If the template argument list is owned by the function template
2932  // specialization, release it.
2933  if (Specialization->getTemplateSpecializationArgs() == DeducedArgumentList &&
2934  !Trap.hasErrorOccurred())
2935  Info.take();
2936 
2937  // There may have been an error that did not prevent us from constructing a
2938  // declaration. Mark the declaration invalid and return with a substitution
2939  // failure.
2940  if (Trap.hasErrorOccurred()) {
2941  Specialization->setInvalidDecl(true);
2942  return TDK_SubstitutionFailure;
2943  }
2944 
2945  if (OriginalCallArgs) {
2946  // C++ [temp.deduct.call]p4:
2947  // In general, the deduction process attempts to find template argument
2948  // values that will make the deduced A identical to A (after the type A
2949  // is transformed as described above). [...]
2950  for (unsigned I = 0, N = OriginalCallArgs->size(); I != N; ++I) {
2951  OriginalCallArg OriginalArg = (*OriginalCallArgs)[I];
2952  unsigned ParamIdx = OriginalArg.ArgIdx;
2953 
2954  if (ParamIdx >= Specialization->getNumParams())
2955  continue;
2956 
2957  QualType DeducedA = Specialization->getParamDecl(ParamIdx)->getType();
2958  if (CheckOriginalCallArgDeduction(*this, OriginalArg, DeducedA)) {
2959  Info.FirstArg = TemplateArgument(DeducedA);
2960  Info.SecondArg = TemplateArgument(OriginalArg.OriginalArgType);
2961  Info.CallArgIndex = OriginalArg.ArgIdx;
2962  return TDK_DeducedMismatch;
2963  }
2964  }
2965  }
2966 
2967  // If we suppressed any diagnostics while performing template argument
2968  // deduction, and if we haven't already instantiated this declaration,
2969  // keep track of these diagnostics. They'll be emitted if this specialization
2970  // is actually used.
2971  if (Info.diag_begin() != Info.diag_end()) {
2973  Pos = SuppressedDiagnostics.find(Specialization->getCanonicalDecl());
2974  if (Pos == SuppressedDiagnostics.end())
2975  SuppressedDiagnostics[Specialization->getCanonicalDecl()]
2976  .append(Info.diag_begin(), Info.diag_end());
2977  }
2978 
2979  return TDK_Success;
2980 }
2981 
2982 /// Gets the type of a function for template-argument-deducton
2983 /// purposes when it's considered as part of an overload set.
2985  FunctionDecl *Fn) {
2986  // We may need to deduce the return type of the function now.
2987  if (S.getLangOpts().CPlusPlus14 && Fn->getReturnType()->isUndeducedType() &&
2988  S.DeduceReturnType(Fn, R.Expression->getExprLoc(), /*Diagnose*/ false))
2989  return QualType();
2990 
2991  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
2992  if (Method->isInstance()) {
2993  // An instance method that's referenced in a form that doesn't
2994  // look like a member pointer is just invalid.
2995  if (!R.HasFormOfMemberPointer) return QualType();
2996 
2997  return S.Context.getMemberPointerType(Fn->getType(),
2998  S.Context.getTypeDeclType(Method->getParent()).getTypePtr());
2999  }
3000 
3001  if (!R.IsAddressOfOperand) return Fn->getType();
3002  return S.Context.getPointerType(Fn->getType());
3003 }
3004 
3005 /// Apply the deduction rules for overload sets.
3006 ///
3007 /// \return the null type if this argument should be treated as an
3008 /// undeduced context
3009 static QualType
3011  Expr *Arg, QualType ParamType,
3012  bool ParamWasReference) {
3013 
3015 
3016  OverloadExpr *Ovl = R.Expression;
3017 
3018  // C++0x [temp.deduct.call]p4
3019  unsigned TDF = 0;
3020  if (ParamWasReference)
3022  if (R.IsAddressOfOperand)
3023  TDF |= TDF_IgnoreQualifiers;
3024 
3025  // C++0x [temp.deduct.call]p6:
3026  // When P is a function type, pointer to function type, or pointer
3027  // to member function type:
3028 
3029  if (!ParamType->isFunctionType() &&
3030  !ParamType->isFunctionPointerType() &&
3031  !ParamType->isMemberFunctionPointerType()) {
3032  if (Ovl->hasExplicitTemplateArgs()) {
3033  // But we can still look for an explicit specialization.
3034  if (FunctionDecl *ExplicitSpec
3036  return GetTypeOfFunction(S, R, ExplicitSpec);
3037  }
3038 
3039  return QualType();
3040  }
3041 
3042  // Gather the explicit template arguments, if any.
3043  TemplateArgumentListInfo ExplicitTemplateArgs;
3044  if (Ovl->hasExplicitTemplateArgs())
3045  Ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
3046  QualType Match;
3047  for (UnresolvedSetIterator I = Ovl->decls_begin(),
3048  E = Ovl->decls_end(); I != E; ++I) {
3049  NamedDecl *D = (*I)->getUnderlyingDecl();
3050 
3051  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
3052  // - If the argument is an overload set containing one or more
3053  // function templates, the parameter is treated as a
3054  // non-deduced context.
3055  if (!Ovl->hasExplicitTemplateArgs())
3056  return QualType();
3057 
3058  // Otherwise, see if we can resolve a function type
3059  FunctionDecl *Specialization = nullptr;
3060  TemplateDeductionInfo Info(Ovl->getNameLoc());
3061  if (S.DeduceTemplateArguments(FunTmpl, &ExplicitTemplateArgs,
3062  Specialization, Info))
3063  continue;
3064 
3065  D = Specialization;
3066  }
3067 
3068  FunctionDecl *Fn = cast<FunctionDecl>(D);
3069  QualType ArgType = GetTypeOfFunction(S, R, Fn);
3070  if (ArgType.isNull()) continue;
3071 
3072  // Function-to-pointer conversion.
3073  if (!ParamWasReference && ParamType->isPointerType() &&
3074  ArgType->isFunctionType())
3075  ArgType = S.Context.getPointerType(ArgType);
3076 
3077  // - If the argument is an overload set (not containing function
3078  // templates), trial argument deduction is attempted using each
3079  // of the members of the set. If deduction succeeds for only one
3080  // of the overload set members, that member is used as the
3081  // argument value for the deduction. If deduction succeeds for
3082  // more than one member of the overload set the parameter is
3083  // treated as a non-deduced context.
3084 
3085  // We do all of this in a fresh context per C++0x [temp.deduct.type]p2:
3086  // Type deduction is done independently for each P/A pair, and
3087  // the deduced template argument values are then combined.
3088  // So we do not reject deductions which were made elsewhere.
3090  Deduced(TemplateParams->size());
3091  TemplateDeductionInfo Info(Ovl->getNameLoc());
3093  = DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3094  ArgType, Info, Deduced, TDF);
3095  if (Result) continue;
3096  if (!Match.isNull()) return QualType();
3097  Match = ArgType;
3098  }
3099 
3100  return Match;
3101 }
3102 
3103 /// \brief Perform the adjustments to the parameter and argument types
3104 /// described in C++ [temp.deduct.call].
3105 ///
3106 /// \returns true if the caller should not attempt to perform any template
3107 /// argument deduction based on this P/A pair because the argument is an
3108 /// overloaded function set that could not be resolved.
3110  TemplateParameterList *TemplateParams,
3111  QualType &ParamType,
3112  QualType &ArgType,
3113  Expr *Arg,
3114  unsigned &TDF) {
3115  // C++0x [temp.deduct.call]p3:
3116  // If P is a cv-qualified type, the top level cv-qualifiers of P's type
3117  // are ignored for type deduction.
3118  if (ParamType.hasQualifiers())
3119  ParamType = ParamType.getUnqualifiedType();
3120 
3121  // [...] If P is a reference type, the type referred to by P is
3122  // used for type deduction.
3123  const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>();
3124  if (ParamRefType)
3125  ParamType = ParamRefType->getPointeeType();
3126 
3127  // Overload sets usually make this parameter an undeduced context,
3128  // but there are sometimes special circumstances. Typically
3129  // involving a template-id-expr.
3130  if (ArgType == S.Context.OverloadTy) {
3131  ArgType = ResolveOverloadForDeduction(S, TemplateParams,
3132  Arg, ParamType,
3133  ParamRefType != nullptr);
3134  if (ArgType.isNull())
3135  return true;
3136  }
3137 
3138  if (ParamRefType) {
3139  // If the argument has incomplete array type, try to complete its type.
3140  if (ArgType->isIncompleteArrayType()) {
3141  S.completeExprArrayBound(Arg);
3142  ArgType = Arg->getType();
3143  }
3144 
3145  // C++0x [temp.deduct.call]p3:
3146  // If P is an rvalue reference to a cv-unqualified template
3147  // parameter and the argument is an lvalue, the type "lvalue
3148  // reference to A" is used in place of A for type deduction.
3149  if (ParamRefType->isRValueReferenceType() &&
3150  !ParamType.getQualifiers() &&
3151  isa<TemplateTypeParmType>(ParamType) &&
3152  Arg->isLValue())
3153  ArgType = S.Context.getLValueReferenceType(ArgType);
3154  } else {
3155  // C++ [temp.deduct.call]p2:
3156  // If P is not a reference type:
3157  // - If A is an array type, the pointer type produced by the
3158  // array-to-pointer standard conversion (4.2) is used in place of
3159  // A for type deduction; otherwise,
3160  if (ArgType->isArrayType())
3161  ArgType = S.Context.getArrayDecayedType(ArgType);
3162  // - If A is a function type, the pointer type produced by the
3163  // function-to-pointer standard conversion (4.3) is used in place
3164  // of A for type deduction; otherwise,
3165  else if (ArgType->isFunctionType())
3166  ArgType = S.Context.getPointerType(ArgType);
3167  else {
3168  // - If A is a cv-qualified type, the top level cv-qualifiers of A's
3169  // type are ignored for type deduction.
3170  ArgType = ArgType.getUnqualifiedType();
3171  }
3172  }
3173 
3174  // C++0x [temp.deduct.call]p4:
3175  // In general, the deduction process attempts to find template argument
3176  // values that will make the deduced A identical to A (after the type A
3177  // is transformed as described above). [...]
3178  TDF = TDF_SkipNonDependent;
3179 
3180  // - If the original P is a reference type, the deduced A (i.e., the
3181  // type referred to by the reference) can be more cv-qualified than
3182  // the transformed A.
3183  if (ParamRefType)
3185  // - The transformed A can be another pointer or pointer to member
3186  // type that can be converted to the deduced A via a qualification
3187  // conversion (4.4).
3188  if (ArgType->isPointerType() || ArgType->isMemberPointerType() ||
3189  ArgType->isObjCObjectPointerType())
3190  TDF |= TDF_IgnoreQualifiers;
3191  // - If P is a class and P has the form simple-template-id, then the
3192  // transformed A can be a derived class of the deduced A. Likewise,
3193  // if P is a pointer to a class of the form simple-template-id, the
3194  // transformed A can be a pointer to a derived class pointed to by
3195  // the deduced A.
3196  if (isSimpleTemplateIdType(ParamType) ||
3197  (isa<PointerType>(ParamType) &&
3199  ParamType->getAs<PointerType>()->getPointeeType())))
3200  TDF |= TDF_DerivedClass;
3201 
3202  return false;
3203 }
3204 
3205 static bool
3207  QualType T);
3208 
3210  Sema &S, TemplateParameterList *TemplateParams, QualType ParamType,
3211  Expr *Arg, TemplateDeductionInfo &Info,
3212  SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned TDF);
3213 
3214 /// \brief Attempt template argument deduction from an initializer list
3215 /// deemed to be an argument in a function call.
3216 static bool
3218  QualType AdjustedParamType, InitListExpr *ILE,
3219  TemplateDeductionInfo &Info,
3220  SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3221  unsigned TDF, Sema::TemplateDeductionResult &Result) {
3222 
3223  // [temp.deduct.call] p1 (post CWG-1591)
3224  // If removing references and cv-qualifiers from P gives
3225  // std::initializer_list<P0> or P0[N] for some P0 and N and the argument is a
3226  // non-empty initializer list (8.5.4), then deduction is performed instead for
3227  // each element of the initializer list, taking P0 as a function template
3228  // parameter type and the initializer element as its argument, and in the
3229  // P0[N] case, if N is a non-type template parameter, N is deduced from the
3230  // length of the initializer list. Otherwise, an initializer list argument
3231  // causes the parameter to be considered a non-deduced context
3232 
3233  const bool IsConstSizedArray = AdjustedParamType->isConstantArrayType();
3234 
3235  const bool IsDependentSizedArray =
3236  !IsConstSizedArray && AdjustedParamType->isDependentSizedArrayType();
3237 
3238  QualType ElTy; // The element type of the std::initializer_list or the array.
3239 
3240  const bool IsSTDList = !IsConstSizedArray && !IsDependentSizedArray &&
3241  S.isStdInitializerList(AdjustedParamType, &ElTy);
3242 
3243  if (!IsConstSizedArray && !IsDependentSizedArray && !IsSTDList)
3244  return false;
3245 
3246  Result = Sema::TDK_Success;
3247  // If we are not deducing against the 'T' in a std::initializer_list<T> then
3248  // deduce against the 'T' in T[N].
3249  if (ElTy.isNull()) {
3250  assert(!IsSTDList);
3251  ElTy = S.Context.getAsArrayType(AdjustedParamType)->getElementType();
3252  }
3253  // Deduction only needs to be done for dependent types.
3254  if (ElTy->isDependentType()) {
3255  for (Expr *E : ILE->inits()) {
3256  if ((Result = DeduceTemplateArgumentByListElement(S, TemplateParams, ElTy,
3257  E, Info, Deduced, TDF)))
3258  return true;
3259  }
3260  }
3261  if (IsDependentSizedArray) {
3262  const DependentSizedArrayType *ArrTy =
3263  S.Context.getAsDependentSizedArrayType(AdjustedParamType);
3264  // Determine the array bound is something we can deduce.
3265  if (NonTypeTemplateParmDecl *NTTP =
3267  // We can perform template argument deduction for the given non-type
3268  // template parameter.
3269  assert(NTTP->getDepth() == 0 &&
3270  "Cannot deduce non-type template argument at depth > 0");
3271  llvm::APInt Size(S.Context.getIntWidth(NTTP->getType()),
3272  ILE->getNumInits());
3273 
3275  S, NTTP, llvm::APSInt(Size), NTTP->getType(),
3276  /*ArrayBound=*/true, Info, Deduced);
3277  }
3278  }
3279  return true;
3280 }
3281 
3282 /// \brief Perform template argument deduction by matching a parameter type
3283 /// against a single expression, where the expression is an element of
3284 /// an initializer list that was originally matched against a parameter
3285 /// of type \c initializer_list<ParamType>.
3288  TemplateParameterList *TemplateParams,
3289  QualType ParamType, Expr *Arg,
3290  TemplateDeductionInfo &Info,
3291  SmallVectorImpl<DeducedTemplateArgument> &Deduced,
3292  unsigned TDF) {
3293  // Handle the case where an init list contains another init list as the
3294  // element.
3295  if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3297  if (!DeduceFromInitializerList(S, TemplateParams,
3298  ParamType.getNonReferenceType(), ILE, Info,
3299  Deduced, TDF, Result))
3300  return Sema::TDK_Success; // Just ignore this expression.
3301 
3302  return Result;
3303  }
3304 
3305  // For all other cases, just match by type.
3306  QualType ArgType = Arg->getType();
3307  if (AdjustFunctionParmAndArgTypesForDeduction(S, TemplateParams, ParamType,
3308  ArgType, Arg, TDF)) {
3309  Info.Expression = Arg;
3311  }
3312  return DeduceTemplateArgumentsByTypeMatch(S, TemplateParams, ParamType,
3313  ArgType, Info, Deduced, TDF);
3314 }
3315 
3316 /// \brief Perform template argument deduction from a function call
3317 /// (C++ [temp.deduct.call]).
3318 ///
3319 /// \param FunctionTemplate the function template for which we are performing
3320 /// template argument deduction.
3321 ///
3322 /// \param ExplicitTemplateArgs the explicit template arguments provided
3323 /// for this call.
3324 ///
3325 /// \param Args the function call arguments
3326 ///
3327 /// \param Specialization if template argument deduction was successful,
3328 /// this will be set to the function template specialization produced by
3329 /// template argument deduction.
3330 ///
3331 /// \param Info the argument will be updated to provide additional information
3332 /// about template argument deduction.
3333 ///
3334 /// \returns the result of template argument deduction.
3336  FunctionTemplateDecl *FunctionTemplate,
3337  TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3338  FunctionDecl *&Specialization, TemplateDeductionInfo &Info,
3339  bool PartialOverloading) {
3340  if (FunctionTemplate->isInvalidDecl())
3341  return TDK_Invalid;
3342 
3343  FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3344  unsigned NumParams = Function->getNumParams();
3345 
3346  // C++ [temp.deduct.call]p1:
3347  // Template argument deduction is done by comparing each function template
3348  // parameter type (call it P) with the type of the corresponding argument
3349  // of the call (call it A) as described below.
3350  unsigned CheckArgs = Args.size();
3351  if (Args.size() < Function->getMinRequiredArguments() && !PartialOverloading)
3352  return TDK_TooFewArguments;
3353  else if (TooManyArguments(NumParams, Args.size(), PartialOverloading)) {
3354  const FunctionProtoType *Proto
3355  = Function->getType()->getAs<FunctionProtoType>();
3356  if (Proto->isTemplateVariadic())
3357  /* Do nothing */;
3358  else if (Proto->isVariadic())
3359  CheckArgs = NumParams;
3360  else
3361  return TDK_TooManyArguments;
3362  }
3363 
3364  // The types of the parameters from which we will perform template argument
3365  // deduction.
3366  LocalInstantiationScope InstScope(*this);
3367  TemplateParameterList *TemplateParams
3368  = FunctionTemplate->getTemplateParameters();
3370  SmallVector<QualType, 4> ParamTypes;
3371  unsigned NumExplicitlySpecified = 0;
3372  if (ExplicitTemplateArgs) {
3374  SubstituteExplicitTemplateArguments(FunctionTemplate,
3375  *ExplicitTemplateArgs,
3376  Deduced,
3377  ParamTypes,
3378  nullptr,
3379  Info);
3380  if (Result)
3381  return Result;
3382 
3383  NumExplicitlySpecified = Deduced.size();
3384  } else {
3385  // Just fill in the parameter types from the function declaration.
3386  for (unsigned I = 0; I != NumParams; ++I)
3387  ParamTypes.push_back(Function->getParamDecl(I)->getType());
3388  }
3389 
3390  // Deduce template arguments from the function parameters.
3391  Deduced.resize(TemplateParams->size());
3392  unsigned ArgIdx = 0;
3393  SmallVector<OriginalCallArg, 4> OriginalCallArgs;
3394  for (unsigned ParamIdx = 0, NumParamTypes = ParamTypes.size();
3395  ParamIdx != NumParamTypes; ++ParamIdx) {
3396  QualType OrigParamType = ParamTypes[ParamIdx];
3397  QualType ParamType = OrigParamType;
3398 
3399  const PackExpansionType *ParamExpansion
3400  = dyn_cast<PackExpansionType>(ParamType);
3401  if (!ParamExpansion) {
3402  // Simple case: matching a function parameter to a function argument.
3403  if (ArgIdx >= CheckArgs)
3404  break;
3405 
3406  Expr *Arg = Args[ArgIdx++];
3407  QualType ArgType = Arg->getType();
3408 
3409  unsigned TDF = 0;
3410  if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3411  ParamType, ArgType, Arg,
3412  TDF))
3413  continue;
3414 
3415  // If we have nothing to deduce, we're done.
3416  if (!hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3417  continue;
3418 
3419  // If the argument is an initializer list ...
3420  if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3422  // Removing references was already done.
3423  if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3424  Info, Deduced, TDF, Result))
3425  continue;
3426 
3427  if (Result)
3428  return Result;
3429  // Don't track the argument type, since an initializer list has none.
3430  continue;
3431  }
3432 
3433  // Keep track of the argument type and corresponding parameter index,
3434  // so we can check for compatibility between the deduced A and A.
3435  OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx-1,
3436  ArgType));
3437 
3439  = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3440  ParamType, ArgType,
3441  Info, Deduced, TDF))
3442  return Result;
3443 
3444  continue;
3445  }
3446 
3447  // C++0x [temp.deduct.call]p1:
3448  // For a function parameter pack that occurs at the end of the
3449  // parameter-declaration-list, the type A of each remaining argument of
3450  // the call is compared with the type P of the declarator-id of the
3451  // function parameter pack. Each comparison deduces template arguments
3452  // for subsequent positions in the template parameter packs expanded by
3453  // the function parameter pack. For a function parameter pack that does
3454  // not occur at the end of the parameter-declaration-list, the type of
3455  // the parameter pack is a non-deduced context.
3456  if (ParamIdx + 1 < NumParamTypes)
3457  break;
3458 
3459  QualType ParamPattern = ParamExpansion->getPattern();
3460  PackDeductionScope PackScope(*this, TemplateParams, Deduced, Info,
3461  ParamPattern);
3462 
3463  bool HasAnyArguments = false;
3464  for (; ArgIdx < Args.size(); ++ArgIdx) {
3465  HasAnyArguments = true;
3466 
3467  QualType OrigParamType = ParamPattern;
3468  ParamType = OrigParamType;
3469  Expr *Arg = Args[ArgIdx];
3470  QualType ArgType = Arg->getType();
3471 
3472  unsigned TDF = 0;
3473  if (AdjustFunctionParmAndArgTypesForDeduction(*this, TemplateParams,
3474  ParamType, ArgType, Arg,
3475  TDF)) {
3476  // We can't actually perform any deduction for this argument, so stop
3477  // deduction at this point.
3478  ++ArgIdx;
3479  break;
3480  }
3481 
3482  // As above, initializer lists need special handling.
3483  if (InitListExpr *ILE = dyn_cast<InitListExpr>(Arg)) {
3485  if (!DeduceFromInitializerList(*this, TemplateParams, ParamType, ILE,
3486  Info, Deduced, TDF, Result)) {
3487  ++ArgIdx;
3488  break;
3489  }
3490 
3491  if (Result)
3492  return Result;
3493  } else {
3494 
3495  // Keep track of the argument type and corresponding argument index,
3496  // so we can check for compatibility between the deduced A and A.
3497  if (hasDeducibleTemplateParameters(*this, FunctionTemplate, ParamType))
3498  OriginalCallArgs.push_back(OriginalCallArg(OrigParamType, ArgIdx,
3499  ArgType));
3500 
3502  = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3503  ParamType, ArgType, Info,
3504  Deduced, TDF))
3505  return Result;
3506  }
3507 
3508  PackScope.nextPackElement();
3509  }
3510 
3511  // Build argument packs for each of the parameter packs expanded by this
3512  // pack expansion.
3513  if (auto Result = PackScope.finish(HasAnyArguments))
3514  return Result;
3515 
3516  // After we've matching against a parameter pack, we're done.
3517  break;
3518  }
3519 
3520  return FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3521  NumExplicitlySpecified, Specialization,
3522  Info, &OriginalCallArgs,
3523  PartialOverloading);
3524 }
3525 
3528  if (ArgFunctionType.isNull())
3529  return ArgFunctionType;
3530 
3531  const FunctionProtoType *FunctionTypeP =
3532  FunctionType->castAs<FunctionProtoType>();
3533  CallingConv CC = FunctionTypeP->getCallConv();
3534  bool NoReturn = FunctionTypeP->getNoReturnAttr();
3535  const FunctionProtoType *ArgFunctionTypeP =
3536  ArgFunctionType->getAs<FunctionProtoType>();
3537  if (ArgFunctionTypeP->getCallConv() == CC &&
3538  ArgFunctionTypeP->getNoReturnAttr() == NoReturn)
3539  return ArgFunctionType;
3540 
3541  FunctionType::ExtInfo EI = ArgFunctionTypeP->getExtInfo().withCallingConv(CC);
3542  EI = EI.withNoReturn(NoReturn);
3543  ArgFunctionTypeP =
3544  cast<FunctionProtoType>(Context.adjustFunctionType(ArgFunctionTypeP, EI));
3545  return QualType(ArgFunctionTypeP, 0);
3546 }
3547 
3548 /// \brief Deduce template arguments when taking the address of a function
3549 /// template (C++ [temp.deduct.funcaddr]) or matching a specialization to
3550 /// a template.
3551 ///
3552 /// \param FunctionTemplate the function template for which we are performing
3553 /// template argument deduction.
3554 ///
3555 /// \param ExplicitTemplateArgs the explicitly-specified template
3556 /// arguments.
3557 ///
3558 /// \param ArgFunctionType the function type that will be used as the
3559 /// "argument" type (A) when performing template argument deduction from the
3560 /// function template's function type. This type may be NULL, if there is no
3561 /// argument type to compare against, in C++0x [temp.arg.explicit]p3.
3562 ///
3563 /// \param Specialization if template argument deduction was successful,
3564 /// this will be set to the function template specialization produced by
3565 /// template argument deduction.
3566 ///
3567 /// \param Info the argument will be updated to provide additional information
3568 /// about template argument deduction.
3569 ///
3570 /// \returns the result of template argument deduction.
3573  TemplateArgumentListInfo *ExplicitTemplateArgs,
3574  QualType ArgFunctionType,
3575  FunctionDecl *&Specialization,
3576  TemplateDeductionInfo &Info,
3577  bool InOverloadResolution) {
3578  if (FunctionTemplate->isInvalidDecl())
3579  return TDK_Invalid;
3580 
3581  FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
3582  TemplateParameterList *TemplateParams
3583  = FunctionTemplate->getTemplateParameters();
3584  QualType FunctionType = Function->getType();
3585  if (!InOverloadResolution)
3586  ArgFunctionType = adjustCCAndNoReturn(ArgFunctionType, FunctionType);
3587 
3588  // Substitute any explicit template arguments.
3589  LocalInstantiationScope InstScope(*this);
3591  unsigned NumExplicitlySpecified = 0;
3592  SmallVector<QualType, 4> ParamTypes;
3593  if (ExplicitTemplateArgs) {
3595  = SubstituteExplicitTemplateArguments(FunctionTemplate,
3596  *ExplicitTemplateArgs,
3597  Deduced, ParamTypes,
3598  &FunctionType, Info))
3599  return Result;
3600 
3601  NumExplicitlySpecified = Deduced.size();
3602  }
3603 
3604  // Unevaluated SFINAE context.
3606  SFINAETrap Trap(*this);
3607 
3608  Deduced.resize(TemplateParams->size());
3609 
3610  // If the function has a deduced return type, substitute it for a dependent
3611  // type so that we treat it as a non-deduced context in what follows.
3612  bool HasDeducedReturnType = false;
3613  if (getLangOpts().CPlusPlus14 && InOverloadResolution &&
3614  Function->getReturnType()->getContainedAutoType()) {
3615  FunctionType = SubstAutoType(FunctionType, Context.DependentTy);
3616  HasDeducedReturnType = true;
3617  }
3618 
3619  if (!ArgFunctionType.isNull()) {
3620  unsigned TDF = TDF_TopLevelParameterTypeList;
3621  if (InOverloadResolution) TDF |= TDF_InOverloadResolution;
3622  // Deduce template arguments from the function type.
3624  = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3625  FunctionType, ArgFunctionType,
3626  Info, Deduced, TDF))
3627  return Result;
3628  }
3629 
3631  = FinishTemplateArgumentDeduction(FunctionTemplate, Deduced,
3632  NumExplicitlySpecified,
3633  Specialization, Info))
3634  return Result;
3635 
3636  // If the function has a deduced return type, deduce it now, so we can check
3637  // that the deduced function type matches the requested type.
3638  if (HasDeducedReturnType &&
3639  Specialization->getReturnType()->isUndeducedType() &&
3640  DeduceReturnType(Specialization, Info.getLocation(), false))
3642 
3643  // If the requested function type does not match the actual type of the
3644  // specialization with respect to arguments of compatible pointer to function
3645  // types, template argument deduction fails.
3646  if (!ArgFunctionType.isNull()) {
3647  if (InOverloadResolution && !isSameOrCompatibleFunctionType(
3648  Context.getCanonicalType(Specialization->getType()),
3649  Context.getCanonicalType(ArgFunctionType)))
3651  else if(!InOverloadResolution &&
3652  !Context.hasSameType(Specialization->getType(), ArgFunctionType))
3654  }
3655 
3656  return TDK_Success;
3657 }
3658 
3659 /// \brief Given a function declaration (e.g. a generic lambda conversion
3660 /// function) that contains an 'auto' in its result type, substitute it
3661 /// with TypeToReplaceAutoWith. Be careful to pass in the type you want
3662 /// to replace 'auto' with and not the actual result type you want
3663 /// to set the function to.
3664 static inline void
3666  QualType TypeToReplaceAutoWith, Sema &S) {
3667  assert(!TypeToReplaceAutoWith->getContainedAutoType());
3668  QualType AutoResultType = F->getReturnType();
3669  assert(AutoResultType->getContainedAutoType());
3670  QualType DeducedResultType = S.SubstAutoType(AutoResultType,
3671  TypeToReplaceAutoWith);
3672  S.Context.adjustDeducedFunctionResultType(F, DeducedResultType);
3673 }
3674 
3675 /// \brief Given a specialized conversion operator of a generic lambda
3676 /// create the corresponding specializations of the call operator and
3677 /// the static-invoker. If the return type of the call operator is auto,
3678 /// deduce its return type and check if that matches the
3679 /// return type of the destination function ptr.
3680 
3681 static inline Sema::TemplateDeductionResult
3683  CXXConversionDecl *ConversionSpecialized,
3684  SmallVectorImpl<DeducedTemplateArgument> &DeducedArguments,
3685  QualType ReturnTypeOfDestFunctionPtr,
3686  TemplateDeductionInfo &TDInfo,
3687  Sema &S) {
3688 
3689  CXXRecordDecl *LambdaClass = ConversionSpecialized->getParent();
3690  assert(LambdaClass && LambdaClass->isGenericLambda());
3691 
3692  CXXMethodDecl *CallOpGeneric = LambdaClass->getLambdaCallOperator();
3693  QualType CallOpResultType = CallOpGeneric->getReturnType();
3694  const bool GenericLambdaCallOperatorHasDeducedReturnType =
3695  CallOpResultType->getContainedAutoType();
3696 
3697  FunctionTemplateDecl *CallOpTemplate =
3698  CallOpGeneric->getDescribedFunctionTemplate();
3699 
3700  FunctionDecl *CallOpSpecialized = nullptr;
3701  // Use the deduced arguments of the conversion function, to specialize our
3702  // generic lambda's call operator.
3704  = S.FinishTemplateArgumentDeduction(CallOpTemplate,
3705  DeducedArguments,
3706  0, CallOpSpecialized, TDInfo))
3707  return Result;
3708 
3709  // If we need to deduce the return type, do so (instantiates the callop).
3710  if (GenericLambdaCallOperatorHasDeducedReturnType &&
3711  CallOpSpecialized->getReturnType()->isUndeducedType())
3712  S.DeduceReturnType(CallOpSpecialized,
3713  CallOpSpecialized->getPointOfInstantiation(),
3714  /*Diagnose*/ true);
3715 
3716  // Check to see if the return type of the destination ptr-to-function
3717  // matches the return type of the call operator.
3718  if (!S.Context.hasSameType(CallOpSpecialized->getReturnType(),
3719  ReturnTypeOfDestFunctionPtr))
3721  // Since we have succeeded in matching the source and destination
3722  // ptr-to-functions (now including return type), and have successfully
3723  // specialized our corresponding call operator, we are ready to
3724  // specialize the static invoker with the deduced arguments of our
3725  // ptr-to-function.
3726  FunctionDecl *InvokerSpecialized = nullptr;
3727  FunctionTemplateDecl *InvokerTemplate = LambdaClass->
3728  getLambdaStaticInvoker()->getDescribedFunctionTemplate();
3729 
3730 #ifndef NDEBUG
3731  Sema::TemplateDeductionResult LLVM_ATTRIBUTE_UNUSED Result =
3732 #endif
3733  S.FinishTemplateArgumentDeduction(InvokerTemplate, DeducedArguments, 0,
3734  InvokerSpecialized, TDInfo);
3735  assert(Result == Sema::TDK_Success &&
3736  "If the call operator succeeded so should the invoker!");
3737  // Set the result type to match the corresponding call operator
3738  // specialization's result type.
3739  if (GenericLambdaCallOperatorHasDeducedReturnType &&
3740  InvokerSpecialized->getReturnType()->isUndeducedType()) {
3741  // Be sure to get the type to replace 'auto' with and not
3742  // the full result type of the call op specialization
3743  // to substitute into the 'auto' of the invoker and conversion
3744  // function.
3745  // For e.g.
3746  // int* (*fp)(int*) = [](auto* a) -> auto* { return a; };
3747  // We don't want to subst 'int*' into 'auto' to get int**.
3748 
3749  QualType TypeToReplaceAutoWith = CallOpSpecialized->getReturnType()
3751  ->getDeducedType();
3752  SubstAutoWithinFunctionReturnType(InvokerSpecialized,
3753  TypeToReplaceAutoWith, S);
3754  SubstAutoWithinFunctionReturnType(ConversionSpecialized,
3755  TypeToReplaceAutoWith, S);
3756  }
3757 
3758  // Ensure that static invoker doesn't have a const qualifier.
3759  // FIXME: When creating the InvokerTemplate in SemaLambda.cpp
3760  // do not use the CallOperator's TypeSourceInfo which allows
3761  // the const qualifier to leak through.
3762  const FunctionProtoType *InvokerFPT = InvokerSpecialized->
3763  getType().getTypePtr()->castAs<FunctionProtoType>();
3765  EPI.TypeQuals = 0;
3766  InvokerSpecialized->setType(S.Context.getFunctionType(
3767  InvokerFPT->getReturnType(), InvokerFPT->getParamTypes(), EPI));
3768  return Sema::TDK_Success;
3769 }
3770 /// \brief Deduce template arguments for a templated conversion
3771 /// function (C++ [temp.deduct.conv]) and, if successful, produce a
3772 /// conversion function template specialization.
3775  QualType ToType,
3776  CXXConversionDecl *&Specialization,
3777  TemplateDeductionInfo &Info) {
3778  if (ConversionTemplate->isInvalidDecl())
3779  return TDK_Invalid;
3780 
3781  CXXConversionDecl *ConversionGeneric
3782  = cast<CXXConversionDecl>(ConversionTemplate->getTemplatedDecl());
3783 
3784  QualType FromType = ConversionGeneric->getConversionType();
3785 
3786  // Canonicalize the types for deduction.
3787  QualType P = Context.getCanonicalType(FromType);
3788  QualType A = Context.getCanonicalType(ToType);
3789 
3790  // C++0x [temp.deduct.conv]p2:
3791  // If P is a reference type, the type referred to by P is used for
3792  // type deduction.
3793  if (const ReferenceType *PRef = P->getAs<ReferenceType>())
3794  P = PRef->getPointeeType();
3795 
3796  // C++0x [temp.deduct.conv]p4:
3797  // [...] If A is a reference type, the type referred to by A is used
3798  // for type deduction.
3799  if (const ReferenceType *ARef = A->getAs<ReferenceType>())
3800  A = ARef->getPointeeType().getUnqualifiedType();
3801  // C++ [temp.deduct.conv]p3:
3802  //
3803  // If A is not a reference type:
3804  else {
3805  assert(!A->isReferenceType() && "Reference types were handled above");
3806 
3807  // - If P is an array type, the pointer type produced by the
3808  // array-to-pointer standard conversion (4.2) is used in place
3809  // of P for type deduction; otherwise,
3810  if (P->isArrayType())
3812  // - If P is a function type, the pointer type produced by the
3813  // function-to-pointer standard conversion (4.3) is used in
3814  // place of P for type deduction; otherwise,
3815  else if (P->isFunctionType())
3816  P = Context.getPointerType(P);
3817  // - If P is a cv-qualified type, the top level cv-qualifiers of
3818  // P's type are ignored for type deduction.
3819  else
3820  P = P.getUnqualifiedType();
3821 
3822  // C++0x [temp.deduct.conv]p4:
3823  // If A is a cv-qualified type, the top level cv-qualifiers of A's
3824  // type are ignored for type deduction. If A is a reference type, the type
3825  // referred to by A is used for type deduction.
3826  A = A.getUnqualifiedType();
3827  }
3828 
3829  // Unevaluated SFINAE context.
3831  SFINAETrap Trap(*this);
3832 
3833  // C++ [temp.deduct.conv]p1:
3834  // Template argument deduction is done by comparing the return
3835  // type of the template conversion function (call it P) with the
3836  // type that is required as the result of the conversion (call it
3837  // A) as described in 14.8.2.4.
3838  TemplateParameterList *TemplateParams
3839  = ConversionTemplate->getTemplateParameters();
3841  Deduced.resize(TemplateParams->size());
3842 
3843  // C++0x [temp.deduct.conv]p4:
3844  // In general, the deduction process attempts to find template
3845  // argument values that will make the deduced A identical to
3846  // A. However, there are two cases that allow a difference:
3847  unsigned TDF = 0;
3848  // - If the original A is a reference type, A can be more
3849  // cv-qualified than the deduced A (i.e., the type referred to
3850  // by the reference)
3851  if (ToType->isReferenceType())
3853  // - The deduced A can be another pointer or pointer to member
3854  // type that can be converted to A via a qualification
3855  // conversion.
3856  //
3857  // (C++0x [temp.deduct.conv]p6 clarifies that this only happens when
3858  // both P and A are pointers or member pointers. In this case, we
3859  // just ignore cv-qualifiers completely).
3860  if ((P->isPointerType() && A->isPointerType()) ||
3862  TDF |= TDF_IgnoreQualifiers;
3864  = DeduceTemplateArgumentsByTypeMatch(*this, TemplateParams,
3865  P, A, Info, Deduced, TDF))
3866  return Result;
3867 
3868  // Create an Instantiation Scope for finalizing the operator.
3869  LocalInstantiationScope InstScope(*this);
3870  // Finish template argument deduction.
3871  FunctionDecl *ConversionSpecialized = nullptr;
3873  = FinishTemplateArgumentDeduction(ConversionTemplate, Deduced, 0,
3874  ConversionSpecialized, Info);
3875  Specialization = cast_or_null<CXXConversionDecl>(ConversionSpecialized);
3876 
3877  // If the conversion operator is being invoked on a lambda closure to convert
3878  // to a ptr-to-function, use the deduced arguments from the conversion
3879  // function to specialize the corresponding call operator.
3880  // e.g., int (*fp)(int) = [](auto a) { return a; };
3881  if (Result == TDK_Success && isLambdaConversionOperator(ConversionGeneric)) {
3882 
3883  // Get the return type of the destination ptr-to-function we are converting
3884  // to. This is necessary for matching the lambda call operator's return
3885  // type to that of the destination ptr-to-function's return type.
3886  assert(A->isPointerType() &&
3887  "Can only convert from lambda to ptr-to-function");
3888  const FunctionType *ToFunType =
3890  const QualType DestFunctionPtrReturnType = ToFunType->getReturnType();
3891 
3892  // Create the corresponding specializations of the call operator and
3893  // the static-invoker; and if the return type is auto,
3894  // deduce the return type and check if it matches the
3895  // DestFunctionPtrReturnType.
3896  // For instance:
3897  // auto L = [](auto a) { return f(a); };
3898  // int (*fp)(int) = L;
3899  // char (*fp2)(int) = L; <-- Not OK.
3900 
3902  Specialization, Deduced, DestFunctionPtrReturnType,
3903  Info, *this);
3904  }
3905  return Result;
3906 }
3907 
3908 /// \brief Deduce template arguments for a function template when there is
3909 /// nothing to deduce against (C++0x [temp.arg.explicit]p3).
3910 ///
3911 /// \param FunctionTemplate the function template for which we are performing
3912 /// template argument deduction.
3913 ///
3914 /// \param ExplicitTemplateArgs the explicitly-specified template
3915 /// arguments.
3916 ///
3917 /// \param Specialization if template argument deduction was successful,
3918 /// this will be set to the function template specialization produced by
3919 /// template argument deduction.
3920 ///
3921 /// \param Info the argument will be updated to provide additional information
3922 /// about template argument deduction.
3923 ///
3924 /// \returns the result of template argument deduction.
3927  TemplateArgumentListInfo *ExplicitTemplateArgs,
3928  FunctionDecl *&Specialization,
3929  TemplateDeductionInfo &Info,
3930  bool InOverloadResolution) {
3931  return DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
3932  QualType(), Specialization, Info,
3933  InOverloadResolution);
3934 }
3935 
3936 namespace {
3937  /// Substitute the 'auto' type specifier within a type for a given replacement
3938  /// type.
3939  class SubstituteAutoTransform :
3940  public TreeTransform<SubstituteAutoTransform> {
3941  QualType Replacement;
3942  public:
3943  SubstituteAutoTransform(Sema &SemaRef, QualType Replacement)
3944  : TreeTransform<SubstituteAutoTransform>(SemaRef),
3945  Replacement(Replacement) {}
3946 
3947  QualType TransformAutoType(TypeLocBuilder &TLB, AutoTypeLoc TL) {
3948  // If we're building the type pattern to deduce against, don't wrap the
3949  // substituted type in an AutoType. Certain template deduction rules
3950  // apply only when a template type parameter appears directly (and not if
3951  // the parameter is found through desugaring). For instance:
3952  // auto &&lref = lvalue;
3953  // must transform into "rvalue reference to T" not "rvalue reference to
3954  // auto type deduced as T" in order for [temp.deduct.call]p3 to apply.
3955  if (!Replacement.isNull() && isa<TemplateTypeParmType>(Replacement)) {
3956  QualType Result = Replacement;
3957  TemplateTypeParmTypeLoc NewTL =
3959  NewTL.setNameLoc(TL.getNameLoc());
3960  return Result;
3961  } else {
3962  bool Dependent =
3963  !Replacement.isNull() && Replacement->isDependentType();
3964  QualType Result =
3965  SemaRef.Context.getAutoType(Dependent ? QualType() : Replacement,
3966  TL.getTypePtr()->getKeyword(),
3967  Dependent);
3968  AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
3969  NewTL.setNameLoc(TL.getNameLoc());
3970  return Result;
3971  }
3972  }
3973 
3974  ExprResult TransformLambdaExpr(LambdaExpr *E) {
3975  // Lambdas never need to be transformed.
3976  return E;
3977  }
3978 
3979  QualType Apply(TypeLoc TL) {
3980  // Create some scratch storage for the transformed type locations.
3981  // FIXME: We're just going to throw this information away. Don't build it.
3982  TypeLocBuilder TLB;
3983  TLB.reserve(TL.getFullDataSize());
3984  return TransformType(TLB, TL);
3985  }
3986  };
3987 }
3988 
3991  return DeduceAutoType(Type->getTypeLoc(), Init, Result);
3992 }
3993 
3994 /// \brief Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
3995 ///
3996 /// \param Type the type pattern using the auto type-specifier.
3997 /// \param Init the initializer for the variable whose type is to be deduced.
3998 /// \param Result if type deduction was successful, this will be set to the
3999 /// deduced type.
4002  if (Init->getType()->isNonOverloadPlaceholderType()) {
4003  ExprResult NonPlaceholder = CheckPlaceholderExpr(Init);
4004  if (NonPlaceholder.isInvalid())
4006  Init = NonPlaceholder.get();
4007  }
4008 
4009  if (Init->isTypeDependent() || Type.getType()->isDependentType()) {
4010  Result = SubstituteAutoTransform(*this, Context.DependentTy).Apply(Type);
4011  assert(!Result.isNull() && "substituting DependentTy can't fail");
4012  return DAR_Succeeded;
4013  }
4014 
4015  // If this is a 'decltype(auto)' specifier, do the decltype dance.
4016  // Since 'decltype(auto)' can only occur at the top of the type, we
4017  // don't need to go digging for it.
4018  if (const AutoType *AT = Type.getType()->getAs<AutoType>()) {
4019  if (AT->isDecltypeAuto()) {
4020  if (isa<InitListExpr>(Init)) {
4021  Diag(Init->getLocStart(), diag::err_decltype_auto_initializer_list);
4023  }
4024 
4025  QualType Deduced = BuildDecltypeType(Init, Init->getLocStart(), false);
4026  if (Deduced.isNull())
4028  // FIXME: Support a non-canonical deduced type for 'auto'.
4029  Deduced = Context.getCanonicalType(Deduced);
4030  Result = SubstituteAutoTransform(*this, Deduced).Apply(Type);
4031  if (Result.isNull())
4033  return DAR_Succeeded;
4034  } else if (!getLangOpts().CPlusPlus) {
4035  if (isa<InitListExpr>(Init)) {
4036  Diag(Init->getLocStart(), diag::err_auto_init_list_from_c);
4038  }
4039  }
4040  }
4041 
4042  SourceLocation Loc = Init->getExprLoc();
4043 
4044  LocalInstantiationScope InstScope(*this);
4045 
4046  // Build template<class TemplParam> void Func(FuncParam);
4047  TemplateTypeParmDecl *TemplParam =
4048  TemplateTypeParmDecl::Create(Context, nullptr, SourceLocation(), Loc, 0, 0,
4049  nullptr, false, false);
4050  QualType TemplArg = QualType(TemplParam->getTypeForDecl(), 0);
4051  NamedDecl *TemplParamPtr = TemplParam;
4053  Loc, Loc, TemplParamPtr, Loc);
4054 
4055  QualType FuncParam = SubstituteAutoTransform(*this, TemplArg).Apply(Type);
4056  assert(!FuncParam.isNull() &&
4057  "substituting template parameter for 'auto' failed");
4058 
4059  // Deduce type of TemplParam in Func(Init)
4061  Deduced.resize(1);
4062  QualType InitType = Init->getType();
4063  unsigned TDF = 0;
4064 
4065  TemplateDeductionInfo Info(Loc);
4066 
4067  InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
4068  if (InitList) {
4069  for (unsigned i = 0, e = InitList->getNumInits(); i < e; ++i) {
4070  if (DeduceTemplateArgumentByListElement(*this, TemplateParamsSt.get(),
4071  TemplArg, InitList->getInit(i),
4072  Info, Deduced, TDF))
4073  return DAR_Failed;
4074  }
4075  } else {
4076  if (!getLangOpts().CPlusPlus && Init->refersToBitField()) {
4077  Diag(Loc, diag::err_auto_bitfield);
4079  }
4080 
4082  *this, TemplateParamsSt.get(), FuncParam, InitType, Init, TDF))
4083  return DAR_Failed;
4084 
4085  if (DeduceTemplateArgumentsByTypeMatch(*this, TemplateParamsSt.get(),
4086  FuncParam, InitType, Info, Deduced,
4087  TDF))
4088  return DAR_Failed;
4089  }
4090 
4091  if (Deduced[0].getKind() != TemplateArgument::Type)
4092  return DAR_Failed;
4093 
4094  QualType DeducedType = Deduced[0].getAsType();
4095 
4096  if (InitList) {
4097  DeducedType = BuildStdInitializerList(DeducedType, Loc);
4098  if (DeducedType.isNull())
4100  }
4101 
4102  Result = SubstituteAutoTransform(*this, DeducedType).Apply(Type);
4103  if (Result.isNull())
4105 
4106  // Check that the deduced argument type is compatible with the original
4107  // argument type per C++ [temp.deduct.call]p4.
4108  if (!InitList && !Result.isNull() &&
4110  Sema::OriginalCallArg(FuncParam,0,InitType),
4111  Result)) {
4112  Result = QualType();
4113  return DAR_Failed;
4114  }
4115 
4116  return DAR_Succeeded;
4117 }
4118 
4120  QualType TypeToReplaceAuto) {
4121  return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4122  TransformType(TypeWithAuto);
4123 }
4124 
4126  QualType TypeToReplaceAuto) {
4127  return SubstituteAutoTransform(*this, TypeToReplaceAuto).
4128  TransformType(TypeWithAuto);
4129 }
4130 
4132  if (isa<InitListExpr>(Init))
4133  Diag(VDecl->getLocation(),
4134  VDecl->isInitCapture()
4135  ? diag::err_init_capture_deduction_failure_from_init_list
4136  : diag::err_auto_var_deduction_failure_from_init_list)
4137  << VDecl->getDeclName() << VDecl->getType() << Init->getSourceRange();
4138  else
4139  Diag(VDecl->getLocation(),
4140  VDecl->isInitCapture() ? diag::err_init_capture_deduction_failure
4141  : diag::err_auto_var_deduction_failure)
4142  << VDecl->getDeclName() << VDecl->getType() << Init->getType()
4143  << Init->getSourceRange();
4144 }
4145 
4147  bool Diagnose) {
4148  assert(FD->getReturnType()->isUndeducedType());
4149 
4152 
4153  bool StillUndeduced = FD->getReturnType()->isUndeducedType();
4154  if (StillUndeduced && Diagnose && !FD->isInvalidDecl()) {
4155  Diag(Loc, diag::err_auto_fn_used_before_defined) << FD;
4156  Diag(FD->getLocation(), diag::note_callee_decl) << FD;
4157  }
4158 
4159  return StillUndeduced;
4160 }
4161 
4162 static void
4164  bool OnlyDeduced,
4165  unsigned Level,
4166  llvm::SmallBitVector &Deduced);
4167 
4168 /// \brief If this is a non-static member function,
4169 static void
4171  CXXMethodDecl *Method,
4172  SmallVectorImpl<QualType> &ArgTypes) {
4173  // C++11 [temp.func.order]p3:
4174  // [...] The new parameter is of type "reference to cv A," where cv are
4175  // the cv-qualifiers of the function template (if any) and A is
4176  // the class of which the function template is a member.
4177  //
4178  // The standard doesn't say explicitly, but we pick the appropriate kind of
4179  // reference type based on [over.match.funcs]p4.
4180  QualType ArgTy = Context.getTypeDeclType(Method->getParent());
4181  ArgTy = Context.getQualifiedType(ArgTy,
4183  if (Method->getRefQualifier() == RQ_RValue)
4184  ArgTy = Context.getRValueReferenceType(ArgTy);
4185  else
4186  ArgTy = Context.getLValueReferenceType(ArgTy);
4187  ArgTypes.push_back(ArgTy);
4188 }
4189 
4190 /// \brief Determine whether the function template \p FT1 is at least as
4191 /// specialized as \p FT2.
4193  SourceLocation Loc,
4194  FunctionTemplateDecl *FT1,
4195  FunctionTemplateDecl *FT2,
4197  unsigned NumCallArguments1) {
4198  FunctionDecl *FD1 = FT1->getTemplatedDecl();
4199  FunctionDecl *FD2 = FT2->getTemplatedDecl();
4200  const FunctionProtoType *Proto1 = FD1->getType()->getAs<FunctionProtoType>();
4201  const FunctionProtoType *Proto2 = FD2->getType()->getAs<FunctionProtoType>();
4202 
4203  assert(Proto1 && Proto2 && "Function templates must have prototypes");
4204  TemplateParameterList *TemplateParams = FT2->getTemplateParameters();
4206  Deduced.resize(TemplateParams->size());
4207 
4208  // C++0x [temp.deduct.partial]p3:
4209  // The types used to determine the ordering depend on the context in which
4210  // the partial ordering is done:
4211  TemplateDeductionInfo Info(Loc);
4213  switch (TPOC) {
4214  case TPOC_Call: {
4215  // - In the context of a function call, the function parameter types are
4216  // used.
4217  CXXMethodDecl *Method1 = dyn_cast<CXXMethodDecl>(FD1);
4218  CXXMethodDecl *Method2 = dyn_cast<CXXMethodDecl>(FD2);
4219 
4220  // C++11 [temp.func.order]p3:
4221  // [...] If only one of the function templates is a non-static
4222  // member, that function template is considered to have a new
4223  // first parameter inserted in its function parameter list. The
4224  // new parameter is of type "reference to cv A," where cv are
4225  // the cv-qualifiers of the function template (if any) and A is
4226  // the class of which the function template is a member.
4227  //
4228  // Note that we interpret this to mean "if one of the function
4229  // templates is a non-static member and the other is a non-member";
4230  // otherwise, the ordering rules for static functions against non-static
4231  // functions don't make any sense.
4232  //
4233  // C++98/03 doesn't have this provision but we've extended DR532 to cover
4234  // it as wording was broken prior to it.
4236 
4237  unsigned NumComparedArguments = NumCallArguments1;
4238 
4239  if (!Method2 && Method1 && !Method1->isStatic()) {
4240  // Compare 'this' from Method1 against first parameter from Method2.
4241  AddImplicitObjectParameterType(S.Context, Method1, Args1);
4242  ++NumComparedArguments;
4243  } else if (!Method1 && Method2 && !Method2->isStatic()) {
4244  // Compare 'this' from Method2 against first parameter from Method1.
4245  AddImplicitObjectParameterType(S.Context, Method2, Args2);
4246  }
4247 
4248  Args1.insert(Args1.end(), Proto1->param_type_begin(),
4249  Proto1->param_type_end());
4250  Args2.insert(Args2.end(), Proto2->param_type_begin(),
4251  Proto2->param_type_end());
4252 
4253  // C++ [temp.func.order]p5:
4254  // The presence of unused ellipsis and default arguments has no effect on
4255  // the partial ordering of function templates.
4256  if (Args1.size() > NumComparedArguments)
4257  Args1.resize(NumComparedArguments);
4258  if (Args2.size() > NumComparedArguments)
4259  Args2.resize(NumComparedArguments);
4260  if (DeduceTemplateArguments(S, TemplateParams, Args2.data(), Args2.size(),
4261  Args1.data(), Args1.size(), Info, Deduced,
4262  TDF_None, /*PartialOrdering=*/true))
4263  return false;
4264 
4265  break;
4266  }
4267 
4268  case TPOC_Conversion:
4269  // - In the context of a call to a conversion operator, the return types
4270  // of the conversion function templates are used.
4272  S, TemplateParams, Proto2->getReturnType(), Proto1->getReturnType(),
4273  Info, Deduced, TDF_None,
4274  /*PartialOrdering=*/true))
4275  return false;
4276  break;
4277 
4278  case TPOC_Other:
4279  // - In other contexts (14.6.6.2) the function template's function type
4280  // is used.
4281  if (DeduceTemplateArgumentsByTypeMatch(S, TemplateParams,
4282  FD2->getType(), FD1->getType(),
4283  Info, Deduced, TDF_None,
4284  /*PartialOrdering=*/true))
4285  return false;
4286  break;
4287  }
4288 
4289  // C++0x [temp.deduct.partial]p11:
4290  // In most cases, all template parameters must have values in order for
4291  // deduction to succeed, but for partial ordering purposes a template
4292  // parameter may remain without a value provided it is not used in the
4293  // types being used for partial ordering. [ Note: a template parameter used
4294  // in a non-deduced context is considered used. -end note]
4295  unsigned ArgIdx = 0, NumArgs = Deduced.size();
4296  for (; ArgIdx != NumArgs; ++ArgIdx)
4297  if (Deduced[ArgIdx].isNull())
4298  break;
4299 
4300  if (ArgIdx == NumArgs) {
4301  // All template arguments were deduced. FT1 is at least as specialized
4302  // as FT2.
4303  return true;
4304  }
4305 
4306  // Figure out which template parameters were used.
4307  llvm::SmallBitVector UsedParameters(TemplateParams->size());
4308  switch (TPOC) {
4309  case TPOC_Call:
4310  for (unsigned I = 0, N = Args2.size(); I != N; ++I)
4311  ::MarkUsedTemplateParameters(S.Context, Args2[I], false,
4312  TemplateParams->getDepth(),
4313  UsedParameters);
4314  break;
4315 
4316  case TPOC_Conversion:
4317  ::MarkUsedTemplateParameters(S.Context, Proto2->getReturnType(), false,
4318  TemplateParams->getDepth(), UsedParameters);
4319  break;
4320 
4321  case TPOC_Other:
4322  ::MarkUsedTemplateParameters(S.Context, FD2->getType(), false,
4323  TemplateParams->getDepth(),
4324  UsedParameters);
4325  break;
4326  }
4327 
4328  for (; ArgIdx != NumArgs; ++ArgIdx)
4329  // If this argument had no value deduced but was used in one of the types
4330  // used for partial ordering, then deduction fails.
4331  if (Deduced[ArgIdx].isNull() && UsedParameters[ArgIdx])
4332  return false;
4333 
4334  return true;
4335 }
4336 
4337 /// \brief Determine whether this a function template whose parameter-type-list
4338 /// ends with a function parameter pack.
4340  FunctionDecl *Function = FunTmpl->getTemplatedDecl();
4341  unsigned NumParams = Function->getNumParams();
4342  if (NumParams == 0)
4343  return false;
4344 
4345  ParmVarDecl *Last = Function->getParamDecl(NumParams - 1);
4346  if (!Last->isParameterPack())
4347  return false;
4348 
4349  // Make sure that no previous parameter is a parameter pack.
4350  while (--NumParams > 0) {
4351  if (Function->getParamDecl(NumParams - 1)->isParameterPack())
4352  return false;
4353  }
4354 
4355  return true;
4356 }
4357 
4358 /// \brief Returns the more specialized function template according
4359 /// to the rules of function template partial ordering (C++ [temp.func.order]).
4360 ///
4361 /// \param FT1 the first function template
4362 ///
4363 /// \param FT2 the second function template
4364 ///
4365 /// \param TPOC the context in which we are performing partial ordering of
4366 /// function templates.
4367 ///
4368 /// \param NumCallArguments1 The number of arguments in the call to FT1, used
4369 /// only when \c TPOC is \c TPOC_Call.
4370 ///
4371 /// \param NumCallArguments2 The number of arguments in the call to FT2, used
4372 /// only when \c TPOC is \c TPOC_Call.
4373 ///
4374 /// \returns the more specialized function template. If neither
4375 /// template is more specialized, returns NULL.
4378  FunctionTemplateDecl *FT2,
4379  SourceLocation Loc,
4381  unsigned NumCallArguments1,
4382  unsigned NumCallArguments2) {
4383  bool Better1 = isAtLeastAsSpecializedAs(*this, Loc, FT1, FT2, TPOC,
4384  NumCallArguments1);
4385  bool Better2 = isAtLeastAsSpecializedAs(*this, Loc, FT2, FT1, TPOC,
4386  NumCallArguments2);
4387 
4388  if (Better1 != Better2) // We have a clear winner
4389  return Better1 ? FT1 : FT2;
4390 
4391  if (!Better1 && !Better2) // Neither is better than the other
4392  return nullptr;
4393 
4394  // FIXME: This mimics what GCC implements, but doesn't match up with the
4395  // proposed resolution for core issue 692. This area needs to be sorted out,
4396  // but for now we attempt to maintain compatibility.
4397  bool Variadic1 = isVariadicFunctionTemplate(FT1);
4398  bool Variadic2 = isVariadicFunctionTemplate(FT2);
4399  if (Variadic1 != Variadic2)
4400  return Variadic1? FT2 : FT1;
4401 
4402  return nullptr;
4403 }
4404 
4405 /// \brief Determine if the two templates are equivalent.
4407  if (T1 == T2)
4408  return true;
4409 
4410  if (!T1 || !T2)
4411  return false;
4412 
4413  return T1->getCanonicalDecl() == T2->getCanonicalDecl();
4414 }
4415 
4416 /// \brief Retrieve the most specialized of the given function template
4417 /// specializations.
4418 ///
4419 /// \param SpecBegin the start iterator of the function template
4420 /// specializations that we will be comparing.
4421 ///
4422 /// \param SpecEnd the end iterator of the function template
4423 /// specializations, paired with \p SpecBegin.
4424 ///
4425 /// \param Loc the location where the ambiguity or no-specializations
4426 /// diagnostic should occur.
4427 ///
4428 /// \param NoneDiag partial diagnostic used to diagnose cases where there are
4429 /// no matching candidates.
4430 ///
4431 /// \param AmbigDiag partial diagnostic used to diagnose an ambiguity, if one
4432 /// occurs.
4433 ///
4434 /// \param CandidateDiag partial diagnostic used for each function template
4435 /// specialization that is a candidate in the ambiguous ordering. One parameter
4436 /// in this diagnostic should be unbound, which will correspond to the string
4437 /// describing the template arguments for the function template specialization.
4438 ///
4439 /// \returns the most specialized function template specialization, if
4440 /// found. Otherwise, returns SpecEnd.
4442  UnresolvedSetIterator SpecBegin, UnresolvedSetIterator SpecEnd,
4443  TemplateSpecCandidateSet &FailedCandidates,
4444  SourceLocation Loc, const PartialDiagnostic &NoneDiag,
4445  const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag,
4446  bool Complain, QualType TargetType) {
4447  if (SpecBegin == SpecEnd) {
4448  if (Complain) {
4449  Diag(Loc, NoneDiag);
4450  FailedCandidates.NoteCandidates(*this, Loc);
4451  }
4452  return SpecEnd;
4453  }
4454 
4455  if (SpecBegin + 1 == SpecEnd)
4456  return SpecBegin;
4457 
4458  // Find the function template that is better than all of the templates it
4459  // has been compared to.
4460  UnresolvedSetIterator Best = SpecBegin;
4461  FunctionTemplateDecl *BestTemplate
4462  = cast<FunctionDecl>(*Best)->getPrimaryTemplate();
4463  assert(BestTemplate && "Not a function template specialization?");
4464  for (UnresolvedSetIterator I = SpecBegin + 1; I != SpecEnd; ++I) {
4465  FunctionTemplateDecl *Challenger
4466  = cast<FunctionDecl>(*I)->getPrimaryTemplate();
4467  assert(Challenger && "Not a function template specialization?");
4468  if (isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
4469  Loc, TPOC_Other, 0, 0),
4470  Challenger)) {
4471  Best = I;
4472  BestTemplate = Challenger;
4473  }
4474  }
4475 
4476  // Make sure that the "best" function template is more specialized than all
4477  // of the others.
4478  bool Ambiguous = false;
4479  for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4480  FunctionTemplateDecl *Challenger
4481  = cast<FunctionDecl>(*I)->getPrimaryTemplate();
4482  if (I != Best &&
4483  !isSameTemplate(getMoreSpecializedTemplate(BestTemplate, Challenger,
4484  Loc, TPOC_Other, 0, 0),
4485  BestTemplate)) {
4486  Ambiguous = true;
4487  break;
4488  }
4489  }
4490 
4491  if (!Ambiguous) {
4492  // We found an answer. Return it.
4493  return Best;
4494  }
4495 
4496  // Diagnose the ambiguity.
4497  if (Complain) {
4498  Diag(Loc, AmbigDiag);
4499 
4500  // FIXME: Can we order the candidates in some sane way?
4501  for (UnresolvedSetIterator I = SpecBegin; I != SpecEnd; ++I) {
4502  PartialDiagnostic PD = CandidateDiag;
4504  cast<FunctionDecl>(*I)->getPrimaryTemplate()->getTemplateParameters(),
4505  *cast<FunctionDecl>(*I)->getTemplateSpecializationArgs());
4506  if (!TargetType.isNull())
4507  HandleFunctionTypeMismatch(PD, cast<FunctionDecl>(*I)->getType(),
4508  TargetType);
4509  Diag((*I)->getLocation(), PD);
4510  }
4511  }
4512 
4513  return SpecEnd;
4514 }
4515 
4516 /// \brief Returns the more specialized class template partial specialization
4517 /// according to the rules of partial ordering of class template partial
4518 /// specializations (C++ [temp.class.order]).
4519 ///
4520 /// \param PS1 the first class template partial specialization
4521 ///
4522 /// \param PS2 the second class template partial specialization
4523 ///
4524 /// \returns the more specialized class template partial specialization. If
4525 /// neither partial specialization is more specialized, returns NULL.
4530  SourceLocation Loc) {
4531  // C++ [temp.class.order]p1:
4532  // For two class template partial specializations, the first is at least as
4533  // specialized as the second if, given the following rewrite to two
4534  // function templates, the first function template is at least as
4535  // specialized as the second according to the ordering rules for function
4536  // templates (14.6.6.2):
4537  // - the first function template has the same template parameters as the
4538  // first partial specialization and has a single function parameter
4539  // whose type is a class template specialization with the template
4540  // arguments of the first partial specialization, and
4541  // - the second function template has the same template parameters as the
4542  // second partial specialization and has a single function parameter
4543  // whose type is a class template specialization with the template
4544  // arguments of the second partial specialization.
4545  //
4546  // Rather than synthesize function templates, we merely perform the
4547  // equivalent partial ordering by performing deduction directly on
4548  // the template arguments of the class template partial
4549  // specializations. This computation is slightly simpler than the
4550  // general problem of function template partial ordering, because
4551  // class template partial specializations are more constrained. We
4552  // know that every template parameter is deducible from the class
4553  // template partial specialization's template arguments, for
4554  // example.
4556  TemplateDeductionInfo Info(Loc);
4557 
4560 
4561  // Determine whether PS1 is at least as specialized as PS2
4562  Deduced.resize(PS2->getTemplateParameters()->size());
4563  bool Better1 = !DeduceTemplateArgumentsByTypeMatch(*this,
4564  PS2->getTemplateParameters(),
4565  PT2, PT1, Info, Deduced, TDF_None,
4566  /*PartialOrdering=*/true);
4567  if (Better1) {
4568  SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
4569  InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
4571  *this, PS2, PS1->getTemplateArgs(), Deduced, Info);
4572  }
4573 
4574  // Determine whether PS2 is at least as specialized as PS1
4575  Deduced.clear();
4576  Deduced.resize(PS1->getTemplateParameters()->size());
4577  bool Better2 = !DeduceTemplateArgumentsByTypeMatch(
4578  *this, PS1->getTemplateParameters(), PT1, PT2, Info, Deduced, TDF_None,
4579  /*PartialOrdering=*/true);
4580  if (Better2) {
4581  SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4582  Deduced.end());
4583  InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
4585  *this, PS1, PS2->getTemplateArgs(), Deduced, Info);
4586  }
4587 
4588  if (Better1 == Better2)
4589  return nullptr;
4590 
4591  return Better1 ? PS1 : PS2;
4592 }
4593 
4594 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
4595 /// May require unifying ClassTemplate(Partial)SpecializationDecl and
4596 /// VarTemplate(Partial)SpecializationDecl with a new data
4597 /// structure Template(Partial)SpecializationDecl, and
4598 /// using Template(Partial)SpecializationDecl as input type.
4604  TemplateDeductionInfo Info(Loc);
4605 
4606  assert(PS1->getSpecializedTemplate() == PS2->getSpecializedTemplate() &&
4607  "the partial specializations being compared should specialize"
4608  " the same template.");
4612  CanonTemplate, PS1->getTemplateArgs().data(),
4613  PS1->getTemplateArgs().size());
4615  CanonTemplate, PS2->getTemplateArgs().data(),
4616  PS2->getTemplateArgs().size());
4617 
4618  // Determine whether PS1 is at least as specialized as PS2
4619  Deduced.resize(PS2->getTemplateParameters()->size());
4620  bool Better1 = !DeduceTemplateArgumentsByTypeMatch(
4621  *this, PS2->getTemplateParameters(), PT2, PT1, Info, Deduced, TDF_None,
4622  /*PartialOrdering=*/true);
4623  if (Better1) {
4624  SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),
4625  Deduced.end());
4626  InstantiatingTemplate Inst(*this, Loc, PS2, DeducedArgs, Info);
4627  Better1 = !::FinishTemplateArgumentDeduction(*this, PS2,
4628  PS1->getTemplateArgs(),
4629  Deduced, Info);
4630  }
4631 
4632  // Determine whether PS2 is at least as specialized as PS1
4633  Deduced.clear();
4634  Deduced.resize(PS1->getTemplateParameters()->size());
4635  bool Better2 = !DeduceTemplateArgumentsByTypeMatch(*this,
4636  PS1->getTemplateParameters(),
4637  PT1, PT2, Info, Deduced, TDF_None,
4638  /*PartialOrdering=*/true);
4639  if (Better2) {
4640  SmallVector<TemplateArgument, 4> DeducedArgs(Deduced.begin(),Deduced.end());
4641  InstantiatingTemplate Inst(*this, Loc, PS1, DeducedArgs, Info);
4642  Better2 = !::FinishTemplateArgumentDeduction(*this, PS1,
4643  PS2->getTemplateArgs(),
4644  Deduced, Info);
4645  }
4646 
4647  if (Better1 == Better2)
4648  return nullptr;
4649 
4650  return Better1? PS1 : PS2;
4651 }
4652 
4653 static void
4655  const TemplateArgument &TemplateArg,
4656  bool OnlyDeduced,
4657  unsigned Depth,
4658  llvm::SmallBitVector &Used);
4659 
4660 /// \brief Mark the template parameters that are used by the given
4661 /// expression.
4662 static void
4664  const Expr *E,
4665  bool OnlyDeduced,
4666  unsigned Depth,
4667  llvm::SmallBitVector &Used) {
4668  // We can deduce from a pack expansion.
4669  if (const PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(E))
4670  E = Expansion->getPattern();
4671 
4672  // Skip through any implicit casts we added while type-checking, and any
4673  // substitutions performed by template alias expansion.
4674  while (1) {
4675  if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
4676  E = ICE->getSubExpr();
4677  else if (const SubstNonTypeTemplateParmExpr *Subst =
4678  dyn_cast<SubstNonTypeTemplateParmExpr>(E))
4679  E = Subst->getReplacement();
4680  else
4681  break;
4682  }
4683 
4684  // FIXME: if !OnlyDeduced, we have to walk the whole subexpression to
4685  // find other occurrences of template parameters.
4686  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
4687  if (!DRE)
4688  return;
4689 
4690  const NonTypeTemplateParmDecl *NTTP
4691  = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4692  if (!NTTP)
4693  return;
4694 
4695  if (NTTP->getDepth() == Depth)
4696  Used[NTTP->getIndex()] = true;
4697 }
4698 
4699 /// \brief Mark the template parameters that are used by the given
4700 /// nested name specifier.
4701 static void
4703  NestedNameSpecifier *NNS,
4704  bool OnlyDeduced,
4705  unsigned Depth,
4706  llvm::SmallBitVector &Used) {
4707  if (!NNS)
4708  return;
4709 
4710  MarkUsedTemplateParameters(Ctx, NNS->getPrefix(), OnlyDeduced, Depth,
4711  Used);
4713  OnlyDeduced, Depth, Used);
4714 }
4715 
4716 /// \brief Mark the template parameters that are used by the given
4717 /// template name.
4718 static void
4721  bool OnlyDeduced,
4722  unsigned Depth,
4723  llvm::SmallBitVector &Used) {
4724  if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4725  if (TemplateTemplateParmDecl *TTP
4726  = dyn_cast<TemplateTemplateParmDecl>(Template)) {
4727  if (TTP->getDepth() == Depth)
4728  Used[TTP->getIndex()] = true;
4729  }
4730  return;
4731  }
4732 
4734  MarkUsedTemplateParameters(Ctx, QTN->getQualifier(), OnlyDeduced,
4735  Depth, Used);
4737  MarkUsedTemplateParameters(Ctx, DTN->getQualifier(), OnlyDeduced,
4738  Depth, Used);
4739 }
4740 
4741 /// \brief Mark the template parameters that are used by the given
4742 /// type.
4743 static void
4745  bool OnlyDeduced,
4746  unsigned Depth,
4747  llvm::SmallBitVector &Used) {
4748  if (T.isNull())
4749  return;
4750 
4751  // Non-dependent types have nothing deducible
4752  if (!T->isDependentType())
4753  return;
4754 
4755  T = Ctx.getCanonicalType(T);
4756  switch (T->getTypeClass()) {
4757  case Type::Pointer:
4759  cast<PointerType>(T)->getPointeeType(),
4760  OnlyDeduced,
4761  Depth,
4762  Used);
4763  break;
4764 
4765  case Type::BlockPointer:
4767  cast<BlockPointerType>(T)->getPointeeType(),
4768  OnlyDeduced,
4769  Depth,
4770  Used);
4771  break;
4772 
4773  case Type::LValueReference:
4774  case Type::RValueReference:
4776  cast<ReferenceType>(T)->getPointeeType(),
4777  OnlyDeduced,
4778  Depth,
4779  Used);
4780  break;
4781 
4782  case Type::MemberPointer: {
4783  const MemberPointerType *MemPtr = cast<MemberPointerType>(T.getTypePtr());
4784  MarkUsedTemplateParameters(Ctx, MemPtr->getPointeeType(), OnlyDeduced,
4785  Depth, Used);
4786  MarkUsedTemplateParameters(Ctx, QualType(MemPtr->getClass(), 0),
4787  OnlyDeduced, Depth, Used);
4788  break;
4789  }
4790 
4791  case Type::DependentSizedArray:
4793  cast<DependentSizedArrayType>(T)->getSizeExpr(),
4794  OnlyDeduced, Depth, Used);
4795  // Fall through to check the element type
4796 
4797  case Type::ConstantArray:
4798  case Type::IncompleteArray:
4800  cast<ArrayType>(T)->getElementType(),
4801  OnlyDeduced, Depth, Used);
4802  break;
4803 
4804  case Type::Vector:
4805  case Type::ExtVector:
4807  cast<VectorType>(T)->getElementType(),
4808  OnlyDeduced, Depth, Used);
4809  break;
4810 
4811  case Type::DependentSizedExtVector: {
4812  const DependentSizedExtVectorType *VecType
4813  = cast<DependentSizedExtVectorType>(T);
4814  MarkUsedTemplateParameters(Ctx, VecType->getElementType(), OnlyDeduced,
4815  Depth, Used);
4816  MarkUsedTemplateParameters(Ctx, VecType->getSizeExpr(), OnlyDeduced,
4817  Depth, Used);
4818  break;
4819  }
4820 
4821  case Type::FunctionProto: {
4822  const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
4823  MarkUsedTemplateParameters(Ctx, Proto->getReturnType(), OnlyDeduced, Depth,
4824  Used);
4825  for (unsigned I = 0, N = Proto->getNumParams(); I != N; ++I)
4826  MarkUsedTemplateParameters(Ctx, Proto->getParamType(I), OnlyDeduced,
4827  Depth, Used);
4828  break;
4829  }
4830 
4831  case Type::TemplateTypeParm: {
4832  const TemplateTypeParmType *TTP = cast<TemplateTypeParmType>(T);
4833  if (TTP->getDepth() == Depth)
4834  Used[TTP->getIndex()] = true;
4835  break;
4836  }
4837 
4838  case Type::SubstTemplateTypeParmPack: {
4839  const SubstTemplateTypeParmPackType *Subst
4840  = cast<SubstTemplateTypeParmPackType>(T);
4842  QualType(Subst->getReplacedParameter(), 0),
4843  OnlyDeduced, Depth, Used);
4845  OnlyDeduced, Depth, Used);
4846  break;
4847  }
4848 
4849  case Type::InjectedClassName:
4850  T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
4851  // fall through
4852 
4853  case Type::TemplateSpecialization: {
4854  const TemplateSpecializationType *Spec
4855  = cast<TemplateSpecializationType>(T);
4856  MarkUsedTemplateParameters(Ctx, Spec->getTemplateName(), OnlyDeduced,
4857  Depth, Used);
4858 
4859  // C++0x [temp.deduct.type]p9:
4860  // If the template argument list of P contains a pack expansion that is
4861  // not the last template argument, the entire template argument list is a
4862  // non-deduced context.
4863  if (OnlyDeduced &&
4864  hasPackExpansionBeforeEnd(Spec->getArgs(), Spec->getNumArgs()))
4865  break;
4866 
4867  for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
4868  MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
4869  Used);
4870  break;
4871  }
4872 
4873  case Type::Complex:
4874  if (!OnlyDeduced)
4876  cast<ComplexType>(T)->getElementType(),
4877  OnlyDeduced, Depth, Used);
4878  break;
4879 
4880  case Type::Atomic:
4881  if (!OnlyDeduced)
4883  cast<AtomicType>(T)->getValueType(),
4884  OnlyDeduced, Depth, Used);
4885  break;
4886 
4887  case Type::DependentName:
4888  if (!OnlyDeduced)
4890  cast<DependentNameType>(T)->getQualifier(),
4891  OnlyDeduced, Depth, Used);
4892  break;
4893 
4894  case Type::DependentTemplateSpecialization: {
4895  // C++14 [temp.deduct.type]p5:
4896  // The non-deduced contexts are:
4897  // -- The nested-name-specifier of a type that was specified using a
4898  // qualified-id
4899  //
4900  // C++14 [temp.deduct.type]p6:
4901  // When a type name is specified in a way that includes a non-deduced
4902  // context, all of the types that comprise that type name are also
4903  // non-deduced.
4904  if (OnlyDeduced)
4905  break;
4906 
4908  = cast<DependentTemplateSpecializationType>(T);
4909 
4910  MarkUsedTemplateParameters(Ctx, Spec->getQualifier(),
4911  OnlyDeduced, Depth, Used);
4912 
4913  for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
4914  MarkUsedTemplateParameters(Ctx, Spec->getArg(I), OnlyDeduced, Depth,
4915  Used);
4916  break;
4917  }
4918 
4919  case Type::TypeOf:
4920  if (!OnlyDeduced)
4922  cast<TypeOfType>(T)->getUnderlyingType(),
4923  OnlyDeduced, Depth, Used);
4924  break;
4925 
4926  case Type::TypeOfExpr:
4927  if (!OnlyDeduced)
4929  cast<TypeOfExprType>(T)->getUnderlyingExpr(),
4930  OnlyDeduced, Depth, Used);
4931  break;
4932 
4933  case Type::Decltype:
4934  if (!OnlyDeduced)
4936  cast<DecltypeType>(T)->getUnderlyingExpr(),
4937  OnlyDeduced, Depth, Used);
4938  break;
4939 
4940  case Type::UnaryTransform:
4941  if (!OnlyDeduced)
4943  cast<UnaryTransformType>(T)->getUnderlyingType(),
4944  OnlyDeduced, Depth, Used);
4945  break;
4946 
4947  case Type::PackExpansion:
4949  cast<PackExpansionType>(T)->getPattern(),
4950  OnlyDeduced, Depth, Used);
4951  break;
4952 
4953  case Type::Auto:
4955  cast<AutoType>(T)->getDeducedType(),
4956  OnlyDeduced, Depth, Used);
4957 
4958  // None of these types have any template parameters in them.
4959  case Type::Builtin:
4960  case Type::VariableArray:
4961  case Type::FunctionNoProto:
4962  case Type::Record:
4963  case Type::Enum:
4964  case Type::ObjCInterface:
4965  case Type::ObjCObject:
4966  case Type::ObjCObjectPointer:
4967  case Type::UnresolvedUsing:
4968  case Type::Pipe:
4969 #define TYPE(Class, Base)
4970 #define ABSTRACT_TYPE(Class, Base)
4971 #define DEPENDENT_TYPE(Class, Base)
4972 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4973 #include "clang/AST/TypeNodes.def"
4974  break;
4975  }
4976 }
4977 
4978 /// \brief Mark the template parameters that are used by this
4979 /// template argument.
4980 static void
4982  const TemplateArgument &TemplateArg,
4983  bool OnlyDeduced,
4984  unsigned Depth,
4985  llvm::SmallBitVector &Used) {
4986  switch (TemplateArg.getKind()) {
4990  break;
4991 
4993  MarkUsedTemplateParameters(Ctx, TemplateArg.getNullPtrType(), OnlyDeduced,
4994  Depth, Used);
4995  break;
4996 
4998  MarkUsedTemplateParameters(Ctx, TemplateArg.getAsType(), OnlyDeduced,
4999  Depth, Used);
5000  break;
5001 
5005  TemplateArg.getAsTemplateOrTemplatePattern(),
5006  OnlyDeduced, Depth, Used);
5007  break;
5008 
5010  MarkUsedTemplateParameters(Ctx, TemplateArg.getAsExpr(), OnlyDeduced,
5011  Depth, Used);
5012  break;
5013 
5015  for (const auto &P : TemplateArg.pack_elements())
5016  MarkUsedTemplateParameters(Ctx, P, OnlyDeduced, Depth, Used);
5017  break;
5018  }
5019 }
5020 
5021 /// \brief Mark which template parameters can be deduced from a given
5022 /// template argument list.
5023 ///
5024 /// \param TemplateArgs the template argument list from which template
5025 /// parameters will be deduced.
5026 ///
5027 /// \param Used a bit vector whose elements will be set to \c true
5028 /// to indicate when the corresponding template parameter will be
5029 /// deduced.
5030 void
5032  bool OnlyDeduced, unsigned Depth,
5033  llvm::SmallBitVector &Used) {
5034  // C++0x [temp.deduct.type]p9:
5035  // If the template argument list of P contains a pack expansion that is not
5036  // the last template argument, the entire template argument list is a
5037  // non-deduced context.
5038  if (OnlyDeduced &&
5039  hasPackExpansionBeforeEnd(TemplateArgs.data(), TemplateArgs.size()))
5040  return;
5041 
5042  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
5043  ::MarkUsedTemplateParameters(Context, TemplateArgs[I], OnlyDeduced,
5044  Depth, Used);
5045 }
5046 
5047 /// \brief Marks all of the template parameters that will be deduced by a
5048 /// call to the given function template.
5050  ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate,
5051  llvm::SmallBitVector &Deduced) {
5052  TemplateParameterList *TemplateParams
5053  = FunctionTemplate->getTemplateParameters();
5054  Deduced.clear();
5055  Deduced.resize(TemplateParams->size());
5056 
5057  FunctionDecl *Function = FunctionTemplate->getTemplatedDecl();
5058  for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I)
5059  ::MarkUsedTemplateParameters(Ctx, Function->getParamDecl(I)->getType(),
5060  true, TemplateParams->getDepth(), Deduced);
5061 }
5062 
5064  FunctionTemplateDecl *FunctionTemplate,
5065  QualType T) {
5066  if (!T->isDependentType())
5067  return false;
5068 
5069  TemplateParameterList *TemplateParams
5070  = FunctionTemplate->getTemplateParameters();
5071  llvm::SmallBitVector Deduced(TemplateParams->size());
5072  ::MarkUsedTemplateParameters(S.Context, T, true, TemplateParams->getDepth(),
5073  Deduced);
5074 
5075  return Deduced.any();
5076 }
QualType BuildStdInitializerList(QualType Element, SourceLocation Loc)
Looks for the std::initializer_list template and instantiates it with Element, or emits an error if i...
unsigned getNumElements() const
Definition: Type.h:2749
bool hasObjCGCAttr() const
Definition: Type.h:268
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition: ExprCXX.h:2561
ExprResult BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
Construct a new expression that refers to the given integral template argument with the given source-...
Defines the clang::ASTContext interface.
unsigned getNumInits() const
Definition: Expr.h:3754
SourceLocation getEnd() const
Expr * getSizeExpr() const
Definition: Type.h:2699
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1483
bool isVariadic() const
Definition: Type.h:3255
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl * >, SourceLocation > UnexpandedParameterPack
Definition: Sema.h:212
static bool isSameTemplateArg(ASTContext &Context, const TemplateArgument &X, const TemplateArgument &Y)
Determine whether two template arguments are the same.
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
QualType getInjectedSpecializationType() const
Retrieves the injected specialization type for this partial specialization.
static DeducedTemplateArgument checkDeducedTemplateArguments(ASTContext &Context, const DeducedTemplateArgument &X, const DeducedTemplateArgument &Y)
Verify that the given, deduced template arguments are compatible.
unsigned getDepth() const
Definition: Type.h:3779
SuppressedDiagnosticsMap SuppressedDiagnostics
Definition: Sema.h:6674
QualType BuildFunctionType(QualType T, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI)
Build a function type.
Definition: SemaType.cpp:2250
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition: Type.h:5540
llvm::iterator_range< pack_iterator > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
Definition: TemplateBase.h:329
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2147
A (possibly-)qualified type.
Definition: Type.h:575
bool isConstantArrayType() const
Definition: Type.h:5347
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition: ExprCXX.h:2545
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:6287
base_class_range bases()
Definition: DeclCXX.h:713
bool isInvalid() const
Definition: Ownership.h:159
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
bool isLambdaConversionOperator(CXXConversionDecl *C)
Definition: ASTLambda.h:48
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
Definition: TemplateBase.h:282
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:2954
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2432
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:178
bool isMemberPointerType() const
Definition: Type.h:5329
Template argument deduction was successful.
Definition: Sema.h:6289
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:1673
const LangOptions & getLangOpts() const
Definition: Sema.h:1041
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:2847
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known...
Provides information about an attempted template argument deduction, whose success or failure was des...
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
unsigned getIntWidth(QualType T) const
void setObjCLifetime(ObjCLifetime type)
Definition: Type.h:293
The template argument is an expression, and we've not resolved it to one of the other forms yet...
Definition: TemplateBase.h:69
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments...
bool isRecordType() const
Definition: Type.h:5362
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1118
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:77
static bool IsPossiblyOpaquelyQualifiedType(QualType T)
Determines whether the given type is an opaque type that might be more qualified when instantiated...
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type...
Definition: Type.cpp:1589
Defines the C++ template declaration subclasses.
Represents a C++11 auto or C++14 decltype(auto) type.
Definition: Type.h:3918
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
Definition: TemplateBase.h:315
PtrTy get() const
Definition: Ownership.h:163
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type...
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:1832
TemplateSpecializationType(TemplateName T, const TemplateArgument *Args, unsigned NumArgs, QualType Canon, QualType Aliased)
Definition: Type.cpp:3118
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:6846
QualType getPointeeType() const
Definition: Type.h:2388
The base class of the type hierarchy.
Definition: Type.h:1249
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
Definition: ASTContext.h:2100
DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, unsigned NumArgs, const TemplateArgument *Args, QualType Canon)
Definition: Type.cpp:2454
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:5122
Declaration of a variable template.
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2424
The template argument is a declaration that was provided for a pointer, reference, or pointer to member non-type template parameter.
Definition: TemplateBase.h:51
Template argument deduction produced inconsistent deduced values for the given template parameter...
Definition: Sema.h:6300
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:100
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:427
A container of type source information.
Definition: Decl.h:61
unsigned getIndex() const
Definition: Type.h:3780
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:305
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
Definition: DeclTemplate.h:217
Partial ordering of function templates for a call to a conversion function.
Definition: Template.h:119
void SetPartiallySubstitutedPack(NamedDecl *Pack, const TemplateArgument *ExplicitArgs, unsigned NumExplicitArgs)
Note that the given parameter pack has been partially substituted via explicit specification of templ...
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Get the template arguments as written.
const llvm::APInt & getSize() const
Definition: Type.h:2495
This file provides some common utility functions for processing Lambda related AST Constructs...
VarTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
RAII object that enters a new expression evaluation context.
Definition: Sema.h:9238
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:699
void removeObjCLifetime()
Definition: Type.h:296
ObjCLifetime getObjCLifetime() const
Definition: Type.h:290
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:46
Extra information about a function prototype.
Definition: Type.h:3067
TemplateDeductionFlags
Various flags that control template argument deduction.
CallingConv getCallConv() const
Definition: Type.h:2985
bool isCanonical() const
Definition: Type.h:5133
AutoTypeKeyword getKeyword() const
Definition: Type.h:3936
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:1793
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:319
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:4583
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:566
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:48
TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, Decl *Param, SmallVectorImpl< TemplateArgument > &Converted, bool &HasDefaultArg)
If the given template parameter has a default template argument, substitute into that default templat...
static TemplateArgumentLoc getTrivialTemplateArgumentLoc(Sema &S, const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location...
Whether we are performing template argument deduction for parameters and arguments in a top-level tem...
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1299
Defines the clang::Expr interface and subclasses for C++ expressions.
TemplateParameter Param
The template parameter to which a template argument deduction failure refers.
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: DeclTemplate.h:368
The collection of all-type qualifiers we support.
Definition: Type.h:116
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
bool isTemplateVariadic() const
Determines whether this function prototype contains a parameter pack at the end.
Definition: Type.cpp:2808
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:40
unsigned getNumParams() const
Definition: Type.h:3160
A semantic tree transformation that allows one to transform one abstract syntax tree into another...
Definition: TreeTransform.h:95
QualType getElementType() const
Definition: Type.h:2700
Represents a class template specialization, which refers to a class template with a given set of temp...
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:6873
void setDeducedFromArrayBound(bool Deduced)
Specify whether the given non-type template argument was deduced from an array bound.
Definition: Template.h:167
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
static TemplateArgument getEmptyPack()
Definition: TemplateBase.h:208
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
Definition: Type.h:4381
bool wasDeducedFromArrayBound() const
For a non-type template argument, determine whether the template argument was deduced from an array b...
Definition: Template.h:163
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:3184
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:91
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:411
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:3165
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:57
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isReferenceType() const
Definition: Type.h:5314
QualType getReturnType() const
Definition: Decl.h:1956
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Definition: DeclTemplate.h:891
bool isAnyPointerType() const
Definition: Type.h:5308
static bool isVariadicFunctionTemplate(FunctionTemplateDecl *FunTmpl)
Determine whether this a function template whose parameter-type-list ends with a function parameter p...
The arguments included an overloaded function name that could not be resolved to a suitable function...
Definition: Sema.h:6326
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType)
unsigned getCVRQualifiers() const
Definition: Type.h:251
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:232
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:28
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:1962
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:374
Represents the result of substituting a set of types for a template type parameter pack...
Definition: Type.h:3872
unsigned size() const
Definition: DeclTemplate.h:91
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1191
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:1987
Within template argument deduction from a function call, we are matching with a parameter type for wh...
Describes an C or C++ initializer list.
Definition: Expr.h:3724
void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, SourceLocation Loc)
Adjust the calling convention of a method to be the ABI default if it wasn't specified explicitly...
Definition: SemaType.cpp:5977
FunctionTemplateDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this template.
Definition: DeclTemplate.h:906
TemplateArgument getArgumentPack() const
Definition: Type.cpp:3078
bool isCompleteType(SourceLocation Loc, QualType T)
Definition: Sema.h:1416
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2351
static TemplateArgumentList * CreateCopy(ASTContext &Context, const TemplateArgument *Args, unsigned NumArgs)
Create a new template argument list that copies the given set of template arguments.
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:496
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
A convenient class for passing around template argument information.
Definition: TemplateBase.h:517
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Get the template arguments as written.
CanProxy< U > getAs() const
Retrieve a canonical type pointer with a different static type, upcasting or downcasting as needed...
QualType getReturnType() const
Definition: Type.h:2977
unsigned getMinRequiredArguments() const
getMinRequiredArguments - Returns the minimum number of arguments needed to call this function...
Definition: Decl.cpp:2786
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:1801
static bool hasPackExpansionBeforeEnd(const TemplateArgument *Args, unsigned NumArgs)
Determine whether the given set of template arguments has a pack expansion that is not the last templ...
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:6509
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:3723
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack)
Substitution of the deduced template argument values resulted in an error.
Definition: Sema.h:6308
SourceLocation RAngleLoc
The source location of the right angle bracket ('>').
Definition: TemplateBase.h:579
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:146
QualifiedTemplateName * getAsQualifiedTemplateName() const
Retrieve the underlying qualified template name structure, if any.
RecordDecl * getDecl() const
Definition: Type.h:3553
FunctionDecl * getTemplateInstantiationPattern() const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition: Decl.cpp:3123
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition: Sema.h:6294
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition: Sema.h:6461
static bool ConvertDeducedTemplateArgument(Sema &S, NamedDecl *Param, DeducedTemplateArgument Arg, NamedDecl *Template, QualType NTTPType, unsigned ArgumentPackIndex, TemplateDeductionInfo &Info, bool InFunctionTemplate, SmallVectorImpl< TemplateArgument > &Output)
Convert the given deduced template argument and add it to the set of fully-converted template argumen...
We are substituting explicit template arguments provided for a function template. ...
Definition: Sema.h:6502
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
TypeClass getTypeClass() const
Definition: Type.h:1501
bool hasConst() const
Definition: Type.h:229
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC)...
Definition: DeclBase.h:708
SmallVector< DeducedTemplateArgument, 4 > New
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context...
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1422
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl< TemplateArgument > &Converted)
Check that the given template arguments can be be provided to the given template, converting the argu...
detail::InMemoryDirectory::const_iterator I
static bool AdjustFunctionParmAndArgTypesForDeduction(Sema &S, TemplateParameterList *TemplateParams, QualType &ParamType, QualType &ArgType, Expr *Arg, unsigned &TDF)
Perform the adjustments to the parameter and argument types described in C++ [temp.deduct.call].
const DependentSizedArrayType * getAsDependentSizedArrayType(QualType T) const
Definition: ASTContext.h:2103
QualType getType() const
Definition: Decl.h:530
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:753
static Sema::TemplateDeductionResult DeduceTemplateArgumentByListElement(Sema &S, TemplateParameterList *TemplateParams, QualType ParamType, Expr *Arg, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, unsigned TDF)
Perform template argument deduction by matching a parameter type against a single expression...
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:2686
This object can be modified without requiring retains or releases.
Definition: Type.h:137
const TemplateTypeParmType * getReplacedParameter() const
Gets the template parameter that was substituted for.
Definition: Type.h:3893
param_iterator param_begin()
Definition: Decl.h:1906
static bool hasTemplateArgumentForDeduction(const TemplateArgument *&Args, unsigned &ArgIdx, unsigned &NumArgs)
Determine whether there is a template argument to be used for deduction.
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
Class that aids in the construction of nested-name-specifiers along with source-location information ...
QualType getTemplateSpecializationType(TemplateName T, const TemplateArgument *Args, unsigned NumArgs, QualType Canon=QualType()) const
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:6820
AnnotatingParser & P
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack...
Definition: DeclBase.cpp:168
bool isStatic() const
Definition: DeclCXX.cpp:1408
static Sema::TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, const TemplateArgument &Param, TemplateArgument Arg, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced)
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType)
Change the result type of a function type once it is deduced.
diag_iterator diag_end() const
Returns an iterator at the end of the sequence of suppressed diagnostics.
const TemplateArgumentLoc * getTemplateArgs() const
Retrieve the template arguments.
Definition: TemplateBase.h:585
ExtInfo getExtInfo() const
Definition: Type.h:2986
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:259
static bool isAtLeastAsSpecializedAs(Sema &S, SourceLocation Loc, FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1)
Determine whether the function template FT1 is at least as specialized as FT2.
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl< TemplateArgument > &Converted, CheckTemplateArgumentKind CTAK=CTAK_Specified)
Check that the given template argument corresponds to the given template parameter.
QualType getParamType(unsigned i) const
Definition: Type.h:3161
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3041
void reset(TemplateArgumentList *NewDeduced)
Provide a new template argument list that contains the results of template argument deduction...
bool isParameterPack() const
Determine whether this parameter is actually a function parameter pack.
Definition: Decl.cpp:2428
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL...
param_type_iterator param_type_begin() const
Definition: Type.h:3281
static bool hasDeducibleTemplateParameters(Sema &S, FunctionTemplateDecl *FunctionTemplate, QualType T)
Template argument deduction did not deduce a value for every template parameter.
Definition: Sema.h:6297
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition: DeclCXX.cpp:979
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1643
ASTContext * Context
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:415
bool isFunctionPointerType() const
Definition: Type.h:5323
static bool isSimpleTemplateIdType(QualType T)
Determine whether the given type T is a simple-template-id type.
static std::pair< unsigned, unsigned > getDepthAndIndex(NamedDecl *ND)
Retrieve the depth and index of a template parameter.
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:2627
int * Depth
const Type * getTypeForDecl() const
Definition: Decl.h:2507
unsigned getTypeQualifiers() const
Definition: DeclCXX.h:1817
QualType getPointeeType() const
Definition: Type.h:2268
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Definition: Decl.h:521
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:5615
Expr - This represents one expression.
Definition: Expr.h:104
TemplateDeductionResult FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate, SmallVectorImpl< DeducedTemplateArgument > &Deduced, unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, SmallVectorImpl< OriginalCallArg > const *OriginalCallArgs=nullptr, bool PartialOverloading=false)
Finish template argument deduction for a function template, checking the deduced template arguments f...
When performing template argument deduction for a function template, there were too many call argumen...
Definition: Sema.h:6317
decls_iterator decls_end() const
Definition: ExprCXX.h:2492
Declaration of a template type parameter.
SourceLocation getNameLoc() const
Gets the location of the name.
Definition: ExprCXX.h:2509
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:2464
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
Definition: TemplateBase.h:582
This file defines the classes used to store parsed information about declaration-specifiers and decla...
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:54
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:111
diag_iterator diag_begin() const
Returns an iterator at the beginning of the sequence of suppressed diagnostics.
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:1927
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:216
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3169
void completeExprArrayBound(Expr *E)
Definition: SemaType.cpp:6420
DeclContext * getDeclContext()
Definition: DeclBase.h:393
When performing template argument deduction for a function template, there were too few call argument...
Definition: Sema.h:6320
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:14543
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents a C++ template name within the type system.
Definition: TemplateName.h:175
ArrayRef< Expr * > inits()
Definition: Expr.h:3759
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg)
Compare types for equality with respect to possibly compatible function types (noreturn adjustment...
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:107
TemplateDeductionResult SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo &ExplicitTemplateArgs, SmallVectorImpl< DeducedTemplateArgument > &Deduced, SmallVectorImpl< QualType > &ParamTypes, QualType *FunctionType, sema::TemplateDeductionInfo &Info)
Substitute the explicitly-provided template arguments into the given function template according to C...
static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading=false)
To be used for checking whether the arguments being passed to function exceeds the number of paramete...
Definition: Sema.h:9224
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:1751
bool hasTrailingReturn() const
Definition: Type.h:3265
Within template argument deduction from overload resolution per C++ [over.over] allow matching functi...
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1200
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion, return the pattern as a template name.
Definition: TemplateBase.h:269
const TemplateArgument * data() const
Retrieve a pointer to the template argument list.
Definition: DeclTemplate.h:235
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:42
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:984
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2334
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
Definition: Decl.h:190
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:3669
class LLVM_ALIGNAS(8) TemplateSpecializationType unsigned NumArgs
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:3988
ValueDecl * getDecl()
Definition: Expr.h:1007
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition: Sema.h:6311
QualType getElementType() const
Definition: Type.h:2748
bool isStrictSupersetOf(Qualifiers Other) const
Determine whether this set of qualifiers is a strict superset of another set of qualifiers, not considering qualifier compatibility.
Definition: Type.cpp:32
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2392
The result type of a method or function.
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:256
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:228
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:473
Captures a template argument whose value has been deduced via c++ template argument deduction...
Definition: Template.h:139
bool hasObjCLifetime() const
Definition: Type.h:289
static bool hasInconsistentOrSupersetQualifiersOf(QualType ParamType, QualType ArgType)
Determine whether the parameter has qualifiers that are either inconsistent with or a superset of the...
decls_iterator decls_begin() const
Definition: ExprCXX.h:2491
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:2984
bool isDependentSizedArrayType() const
Definition: Type.h:5356
static void MarkUsedTemplateParameters(ASTContext &Ctx, QualType T, bool OnlyDeduced, unsigned Level, llvm::SmallBitVector &Deduced)
Mark the template parameters that are used by the given type.
SmallVector< DeducedPack *, 8 > PendingDeducedPacks
Information on packs that we're currently expanding.
void ResetPartiallySubstitutedPack()
Reset the partially-substituted pack when it is no longer of interest.
Definition: Template.h:356
CanQualType OverloadTy
Definition: ASTContext.h:896
There is no lifetime qualification on this type.
Definition: Type.h:133
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:215
Assigning into this object requires the old value to be released and the new value to be retained...
Definition: Type.h:144
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr...
Definition: ExprCXX.h:2402
NamedDecl * getPartiallySubstitutedPack(const TemplateArgument **ExplicitArgs=nullptr, unsigned *NumExplicitArgs=nullptr) const
Retrieve the partially-substitued template parameter pack.
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:145
A stack object to be created when performing template instantiation.
Definition: Sema.h:6687
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:144
SmallVectorImpl< AnnotatedLine * >::const_iterator Next
static Sema::TemplateDeductionResult DeduceTemplateArgumentsByTypeMatch(Sema &S, TemplateParameterList *TemplateParams, QualType Param, QualType Arg, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, unsigned TDF, bool PartialOrdering=false)
Deduce the template arguments by comparing the parameter type and the argument type (C++ [temp...
bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, TemplateArgumentListInfo &Result, const MultiLevelTemplateArgumentList &TemplateArgs)
The template argument was deduced from an array bound via template argument deduction.
Definition: Sema.h:5773
DeduceAutoResult
Result type of DeduceAutoType.
Definition: Sema.h:6407
Encodes a location in the source.
static TemplateParameter makeTemplateParameter(Decl *D)
Helper function to build a TemplateParameter when we don't know its type statically.
unsigned getNumParams() const
getNumParams - Return the number of parameters this function must have based on its FunctionType...
Definition: Decl.cpp:2743
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:5089
bool hasSameTemplateName(TemplateName X, TemplateName Y)
Determine whether the given template names refer to the same template.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:262
const TemplateArgument * iterator
Definition: Type.h:4070
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this function type.
Definition: Type.h:3271
bool IsNoReturnConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noreturn"...
static Sema::TemplateDeductionResult FinishTemplateArgumentDeduction(Sema &S, ClassTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, SmallVectorImpl< DeducedTemplateArgument > &Deduced, TemplateDeductionInfo &Info)
Complete template argument deduction for a class template partial specialization. ...
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition: Sema.h:6305
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location, which defaults to the empty location.
static bool isSameTemplate(TemplateDecl *T1, TemplateDecl *T2)
Determine if the two templates are equivalent.
static QualType getUnderlyingType(const SubRegion *R)
Within template argument deduction from a function call, we are matching in a case where we ignore cv...
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1701
SourceLocation getNameLoc() const
Definition: TypeLoc.h:493
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:2934
The declaration was invalid; do nothing.
Definition: Sema.h:6291
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2094
void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init)
void reserve(size_t Requested)
Ensures that this buffer has at least as much capacity as described.
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info)
Perform template argument deduction to determine whether the given template arguments match the given...
TypeSourceInfo * SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement)
Substitute Replacement for auto in TypeWithAuto.
Within template argument deduction from a function call, we are matching in a case where we can perfo...
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:2712
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:5706
bool isTypeDependent() const
isTypeDependent - Determines whether this expression is type-dependent (C++ [temp.dep.expr]), which means that its type could change from one template instantiation to the next.
Definition: Expr.h:164
static bool isSameDeclaration(Decl *X, Decl *Y)
Determine whether two declaration pointers refer to the same declaration.
static bool CheckOriginalCallArgDeduction(Sema &S, Sema::OriginalCallArg OriginalArg, QualType DeducedA)
Check whether the deduced argument type for a call to a function template matches the actual argument...
bool isMemberFunctionPointerType() const
Definition: Type.h:5332
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1210
void removeObjCGCAttr()
Definition: Type.h:273
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:432
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:245
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:193
QualType getPointeeType() const
Definition: Type.h:2161
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Represents a pack expansion of types.
Definition: Type.h:4471
FunctionTemplateDecl * getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, unsigned NumCallArguments2)
Returns the more specialized function template according to the rules of function template partial or...
static QualType GetTypeOfFunction(Sema &S, const OverloadExpr::FindResult &R, FunctionDecl *Fn)
Gets the type of a function for template-argument-deducton purposes when it's considered as part of a...
Expr * getSizeExpr() const
Definition: Type.h:2647
param_range params()
Definition: Decl.h:1910
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1207
QualType getType() const
Definition: Expr.h:125
Represents a template argument.
Definition: TemplateBase.h:40
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:238
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument. ...
Represents a template name that was expressed as a qualified name.
Definition: TemplateName.h:354
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:3164
llvm::PointerUnion3< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:40
static const Type * getElementType(const Expr *BaseExpr)
bool SubstParmTypes(SourceLocation Loc, ParmVarDecl **Params, unsigned NumParams, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< QualType > &ParamTypes, SmallVectorImpl< ParmVarDecl * > *OutParams=nullptr)
Substitute the given template arguments into the given set of parameters, producing the set of parame...
Qualifiers withoutObjCLifetime() const
Definition: Type.h:283
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1121
static QualType ResolveOverloadForDeduction(Sema &S, TemplateParameterList *TemplateParams, Expr *Arg, QualType ParamType, bool ParamWasReference)
Apply the deduction rules for overload sets.
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:331
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the variable template specialization.
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:63
static bool DeduceFromInitializerList(Sema &S, TemplateParameterList *TemplateParams, QualType AdjustedParamType, InitListExpr *ILE, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, unsigned TDF, Sema::TemplateDeductionResult &Result)
Attempt template argument deduction from an initializer list deemed to be an argument in a function c...
TemplateName getCanonicalTemplateName(TemplateName Name) const
Retrieves the "canonical" template name that refers to a given template.
bool isInvalidDecl() const
Definition: DeclBase.h:509
bool hasNonTrivialObjCLifetime() const
True if the lifetime is neither None or ExplicitNone.
Definition: Type.h:304
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types...
A non-depnedent component of the parameter did not match the corresponding component of the argument...
Definition: Sema.h:6314
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:3483
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language...
Definition: Expr.h:246
param_type_iterator param_type_end() const
Definition: Type.h:3284
bool isNull() const
Determine whether this template argument has no value.
Definition: TemplateBase.h:219
SourceLocation LAngleLoc
The source location of the left angle bracket ('<').
Definition: TemplateBase.h:576
detail::InMemoryDirectory::const_iterator E
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2369
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
void setCVRQualifiers(unsigned mask)
Definition: Type.h:252
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:1946
bool isLValueReferenceType() const
Definition: Type.h:5317
SourceLocation getPointOfInstantiation() const
Retrieve the (first) point of instantiation of a function template specialization or a member of a cl...
Definition: Decl.cpp:3306
No template argument deduction flags, which indicates the strictest results for template argument ded...
Allow non-dependent types to differ, e.g., when performing template argument deduction from a functio...
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false)
Instantiate the definition of the given function from its template.
unsigned getDepth() const
Get the nesting depth of the template parameter.
bool isRValueReferenceType() const
Definition: Type.h:5320
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:5255
Represents a pointer to an Objective C object.
Definition: Type.h:4821
Pointer to a block type.
Definition: Type.h:2254
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:3544
Complex values, per C99 6.2.5p11.
Definition: Type.h:2087
static Sema::TemplateDeductionResult DeduceNonTypeTemplateArgument(Sema &S, NonTypeTemplateParmDecl *NTTP, llvm::APSInt Value, QualType ValueType, bool DeducedFromArrayBound, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced)
Deduce the value of the given non-type template parameter from the given constant.
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:421
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition: Sema.h:5765
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:5675
unsigned getTypeQuals() const
Definition: Type.h:3267
TemplateArgumentList * take()
Take ownership of the deduced template argument list.
CanQualType DependentTy
Definition: ASTContext.h:896
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:294
bool isFunctionType() const
Definition: Type.h:5302
NestedNameSpecifier * getQualifier() const
Definition: Type.h:4412
ExtVectorType - Extended vector type.
Definition: Type.h:2784
QualType BuildDecltypeType(Expr *E, SourceLocation Loc, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
Definition: SemaType.cpp:7000
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2287
unsigned getAddressSpace() const
Definition: Type.h:316
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so...
Definition: DeclBase.h:978
The template argument is a type.
Definition: TemplateBase.h:48
Deduction failed; that's all we know.
Definition: Sema.h:6328
SourceLocation getLocation() const
Returns the location at which template argument is occurring.
The template argument is actually a parameter pack.
Definition: TemplateBase.h:72
GC getObjCGCAttr() const
Definition: Type.h:269
QualType getPointeeType() const
Definition: Type.h:2308
A template argument list.
Definition: DeclTemplate.h:172
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the class template specialization.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:11761
const Type * getClass() const
Definition: Type.h:2402
static void SubstAutoWithinFunctionReturnType(FunctionDecl *F, QualType TypeToReplaceAutoWith, Sema &S)
Given a function declaration (e.g.
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:256
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition: TypeLoc.h:139
bool hasAddressSpace() const
Definition: Type.h:315
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:335
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:5169
Represents a C++ struct/union/class.
Definition: DeclCXX.h:285
BoundNodesTreeBuilder *const Builder
bool isObjCObjectPointerType() const
Definition: Type.h:5377
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition: Type.h:5520
The template argument is a template name that was provided for a template template parameter...
Definition: TemplateBase.h:60
Represents a C array with an unspecified size.
Definition: Type.h:2530
static Sema::TemplateDeductionResult SpecializeCorrespondingLambdaCallOperatorAndInvoker(CXXConversionDecl *ConversionSpecialized, SmallVectorImpl< DeducedTemplateArgument > &DeducedArguments, QualType ReturnTypeOfDestFunctionPtr, TemplateDeductionInfo &TDInfo, Sema &S)
Given a specialized conversion operator of a generic lambda create the corresponding specializations ...
TPOC
The context in which partial ordering of function templates occurs.
Definition: Template.h:114
static NonTypeTemplateParmDecl * getDeducedParameterFromExpr(Expr *E)
If the given expression is of a form that permits the deduction of a non-type template parameter...
Location information for a TemplateArgument.
Definition: TemplateBase.h:362
TemplateArgument SecondArg
The second template argument to which the template argument deduction failure refers.
Declaration of a class template.
Partial ordering of function templates for a function call.
Definition: Template.h:116
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:355
pack_iterator pack_end() const
Iterator referencing one past the last argument of a template argument pack.
Definition: TemplateBase.h:322
A pack that we're currently deducing.
bool isArrayType() const
Definition: Type.h:5344
DeducedTemplateArgument Saved
QualType getPattern() const
Retrieve the pattern of this pack expansion, which is the type that will be repeatedly instantiated w...
Definition: Type.h:4498
Decl * SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs)
ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization(ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc)
Returns the more specialized class template partial specialization according to the rules of partial ...
static Qualifiers fromCVRMask(unsigned CVR)
Definition: Type.h:211
bool isIncompleteArrayType() const
Definition: Type.h:5350
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:772
CanQualType IntTy
Definition: ASTContext.h:889
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:922
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7)...
Definition: Sema.h:766
QualType getElementType() const
Definition: Type.h:2458
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:5164
unsigned CallArgIndex
The index of the function argument that caused a deduction failure.
const Expr * getInit(unsigned Init) const
Definition: Expr.h:3763
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
TemplateArgument FirstArg
The first template argument to which the template argument deduction failure refers.
DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result)
static bool hasSameExtendedValue(llvm::APSInt X, llvm::APSInt Y)
Compare two APSInts, extending and switching the sign as necessary to compare their values regardless...
Wrapper for template type parameters.
Definition: TypeLoc.h:688
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:180
SourceLocation getLocation() const
Definition: DeclBase.h:384
ASTContext & Context
Definition: Sema.h:295
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2682
NamedDecl - This represents a decl with a name.
Definition: Decl.h:145
Partial ordering of function templates in other contexts, e.g., taking the address of a function temp...
Definition: Template.h:123
void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark which template parameters can be deduced from a given template argument list.
static void AddImplicitObjectParameterType(ASTContext &Context, CXXMethodDecl *Method, SmallVectorImpl< QualType > &ArgTypes)
If this is a non-static member function,.
The template argument was deduced via template argument deduction.
Definition: Sema.h:5769
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:642
void setType(QualType newType)
Definition: Decl.h:531
void removeAddressSpace()
Definition: Type.h:322
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:464
brief A function argument from which we performed template argument
Definition: Sema.h:6350
The explicitly-specified template arguments were not valid template arguments for the given template...
Definition: Sema.h:6323
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2480
Declaration of a template function.
Definition: DeclTemplate.h:830
A class which abstracts out some details necessary for making a call.
Definition: Type.h:2872
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals)
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals...
DeducedTemplateArgument DeferredDeduction
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity)
Perform substitution on the type T with a given set of template arguments.
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:5116
bool isPointerType() const
Definition: Type.h:5305
A RAII object to temporarily push a declaration context.
Definition: Sema.h:601
QualType getDeducedType() const
Get the type deduced for this auto type, or null if it's either not been deduced or was deduced to a ...
Definition: Type.h:3945