[llvm-branch-commits] [clang] [clang] fix printing of canonical template template parameters take 2 (PR #93448)

2024-05-28 Thread Matheus Izvekov via llvm-branch-commits


@@ -292,6 +292,14 @@ void TemplateName::Profile(llvm::FoldingSetNodeID &ID) {
 
 void TemplateName::print(raw_ostream &OS, const PrintingPolicy &Policy,
  Qualified Qual) const {
+  auto handleCanonicalTTP = [](TemplateDecl *TD, raw_ostream &OS) {

mizvekov wrote:

Yeah, the primary use case is canonical TTPs, but it would be more accurate to 
say this handles any anonymous TTP, for whatever reason.

https://github.com/llvm/llvm-project/pull/93448
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [libcxx] [clang] Preserve Qualifiers and type sugar in TemplateNames (PR #93433)

2024-05-29 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/93433

>From 2f2aa69d1b1e421214097cb2595910da15a6c6f2 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Sat, 25 May 2024 13:57:39 -0300
Subject: [PATCH] [clang] Preserve Qualifiers and type sugar in TemplateNames

This patch improves the preservation of qualifiers
and loss of type sugar in TemplateNames.

This problem is analogous to https://reviews.llvm.org/D112374
and this patch takes a very similar approach to that patch,
except the impact here is much lesser.

When a TemplateName was written bare, without qualifications,
we wouldn't produce a QualifiedTemplate which could be used
to disambiguate it from a Canonical TemplateName. This had
effects in the TemplateName printer, which had workarounds
to deal with this, and wouldn't print the TemplateName
as-written in most situations.

There are also some related fixes to help preserve this type
sugar along the way into diagnostics, so that this patch can
be properly tested.

- Fix dropping the template keyword.
- Fix type deduction to preserve sugar in TST TemplateNames.
---
 clang/docs/ReleaseNotes.rst   |  2 +
 clang/include/clang/AST/TemplateName.h| 19 +++---
 clang/include/clang/Sema/Sema.h   |  3 +
 clang/lib/AST/ASTContext.cpp  | 16 ++---
 clang/lib/AST/DeclTemplate.cpp|  7 +-
 clang/lib/AST/ODRHash.cpp |  9 ++-
 clang/lib/AST/TemplateBase.cpp|  2 +-
 clang/lib/AST/TemplateName.cpp| 64 +--
 clang/lib/AST/TextNodeDumper.cpp  |  4 +-
 clang/lib/AST/Type.cpp|  3 +-
 clang/lib/AST/TypePrinter.cpp |  4 +-
 clang/lib/Sema/SemaDecl.cpp   | 15 ++---
 clang/lib/Sema/SemaDeclCXX.cpp| 12 ++--
 clang/lib/Sema/SemaExpr.cpp   |  4 +-
 clang/lib/Sema/SemaExprMember.cpp |  3 +-
 clang/lib/Sema/SemaTemplate.cpp   | 25 +---
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 62 +-
 clang/lib/Sema/SemaType.cpp   | 14 ++--
 clang/lib/Sema/TreeTransform.h|  8 +--
 clang/test/AST/ast-dump-ctad-alias.cpp|  6 +-
 clang/test/AST/ast-dump-decl.cpp  |  8 +--
 clang/test/AST/ast-dump-expr.cpp  |  2 +-
 clang/test/AST/ast-dump-template-decls.cpp|  6 +-
 clang/test/AST/ast-dump-template-name.cpp |  4 +-
 clang/test/AST/ast-dump-using-template.cpp|  6 +-
 clang/test/CXX/drs/cwg1xx.cpp |  4 +-
 .../over.match.oper/p3-2a.cpp |  4 +-
 .../temp.deduct/temp.deduct.type/p9-0x.cpp|  4 +-
 clang/test/Index/print-type.cpp   |  2 +-
 clang/test/OpenMP/declare_mapper_messages.cpp |  2 +-
 .../Parser/cxx-template-template-recovery.cpp |  4 +-
 .../cxx1y-variable-templates_in_class.cpp | 10 +--
 clang/test/SemaTemplate/cwg2398.cpp   |  2 +-
 .../instantiate-requires-expr.cpp |  4 +-
 .../nested-implicit-deduction-guides.cpp  |  2 +-
 clang/unittests/AST/TemplateNameTest.cpp  | 40 ++--
 .../map/map.cons/deduct.verify.cpp| 24 +++
 .../multimap/multimap.cons/deduct.verify.cpp  | 22 +++
 .../multiset/multiset.cons/deduct.verify.cpp  | 10 +--
 .../set/set.cons/deduct.verify.cpp| 10 +--
 .../priqueue.cons/deduct.verify.cpp   | 10 +--
 .../queue/queue.cons/deduct.verify.cpp|  6 +-
 .../stack/stack.cons/deduct.verify.cpp|  6 +-
 .../array/array.cons/deduct.verify.cpp|  2 +-
 .../deque/deque.cons/deduct.verify.cpp|  2 +-
 .../forwardlist.cons/deduct.verify.cpp|  2 +-
 .../list/list.cons/deduct.verify.cpp  |  2 +-
 .../vector/vector.cons/deduct.verify.cpp  |  2 +-
 .../unord.map.cnstr/deduct.verify.cpp | 16 ++---
 .../unord.multimap.cnstr/deduct.verify.cpp| 16 ++---
 .../unord.multiset.cnstr/deduct.verify.cpp| 16 ++---
 .../unord.set.cnstr/deduct.verify.cpp | 16 ++---
 .../range.adaptors/range.join/ctad.verify.cpp |  2 +-
 .../re.regex.construct/deduct.verify.cpp  |  4 +-
 .../optional.object.ctor/deduct.verify.cpp|  2 +-
 55 files changed, 316 insertions(+), 240 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index e1c6d55eeeacd..44035f48cb3f9 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -819,6 +819,8 @@ Bug Fixes to AST Handling
 - Clang now properly preserves ``FoundDecls`` within a ``ConceptReference``. 
(#GH82628)
 - The presence of the ``typename`` keyword is now stored in 
``TemplateTemplateParmDecl``.
 - Fixed malformed AST generated for anonymous union access in templates. 
(#GH90842)
+- Improved preservation of qualifiers and sugar in `TemplateNames`, including
+  template keyword.
 
 Miscellaneous Bug Fixes
 ^^^
diff --git a/clang/include/clang/AST/TemplateName.h 
b/c

[llvm-branch-commits] [clang] [clang] fix printing of canonical template template parameters take 2 (PR #93448)

2024-05-29 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/93448

>From 62eed81cb51c1e1a150bb4f5aad8628fa178b68c Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Mon, 27 May 2024 05:51:18 -0300
Subject: [PATCH] [clang] fix printing of canonical template template
 parameters take 2

Since they can also occur as the template name of
template specializations, handle them from TemplateName
printing instead of TemplateArgument.
---
 clang/lib/AST/TemplateBase.cpp  | 11 +--
 clang/lib/AST/TemplateName.cpp  | 14 ++
 clang/test/SemaTemplate/deduction-guide.cpp | 10 +-
 3 files changed, 20 insertions(+), 15 deletions(-)

diff --git a/clang/lib/AST/TemplateBase.cpp b/clang/lib/AST/TemplateBase.cpp
index 6d3c843cfd29e..46f7b79b272ef 100644
--- a/clang/lib/AST/TemplateBase.cpp
+++ b/clang/lib/AST/TemplateBase.cpp
@@ -544,16 +544,7 @@ void TemplateArgument::print(const PrintingPolicy &Policy, 
raw_ostream &Out,
 break;
 
   case Template: {
-TemplateName TN = getAsTemplate();
-if (const auto *TD = TN.getAsTemplateDecl();
-TD && TD->getDeclName().isEmpty()) {
-  assert(isa(TD) &&
- "Unexpected anonymous template");
-  const auto *TTP = cast(TD);
-  Out << "template-parameter-" << TTP->getDepth() << "-" << 
TTP->getIndex();
-} else {
-  TN.print(Out, Policy);
-}
+getAsTemplate().print(Out, Policy);
 break;
   }
 
diff --git a/clang/lib/AST/TemplateName.cpp b/clang/lib/AST/TemplateName.cpp
index 3aae998eceeb0..3dbdad92813f6 100644
--- a/clang/lib/AST/TemplateName.cpp
+++ b/clang/lib/AST/TemplateName.cpp
@@ -292,6 +292,14 @@ void TemplateName::Profile(llvm::FoldingSetNodeID &ID) {
 
 void TemplateName::print(raw_ostream &OS, const PrintingPolicy &Policy,
  Qualified Qual) const {
+  auto handleAnonymousTTP = [](TemplateDecl *TD, raw_ostream &OS) {
+if (TemplateTemplateParmDecl *TTP = dyn_cast(TD);
+TTP && TTP->getIdentifier() == nullptr) {
+  OS << "template-parameter-" << TTP->getDepth() << "-" << TTP->getIndex();
+  return true;
+}
+return false;
+  };
   if (NameKind Kind = getKind();
   Kind == TemplateName::Template || Kind == TemplateName::UsingTemplate) {
 // After `namespace ns { using std::vector }`, what is the fully-qualified
@@ -304,6 +312,8 @@ void TemplateName::print(raw_ostream &OS, const 
PrintingPolicy &Policy,
 // names more often than to export them, thus using the original name is
 // most useful in this case.
 TemplateDecl *Template = getAsTemplateDecl();
+if (handleAnonymousTTP(Template, OS))
+  return;
 if (Qual == Qualified::None)
   OS << *Template;
 else
@@ -320,6 +330,10 @@ void TemplateName::print(raw_ostream &OS, const 
PrintingPolicy &Policy,
Underlying.getKind() == TemplateName::UsingTemplate);
 
 TemplateDecl *UTD = Underlying.getAsTemplateDecl();
+
+if (handleAnonymousTTP(UTD, OS))
+  return;
+
 if (IdentifierInfo *II = UTD->getIdentifier();
 Policy.CleanUglifiedParameters && II &&
 isa(UTD))
diff --git a/clang/test/SemaTemplate/deduction-guide.cpp 
b/clang/test/SemaTemplate/deduction-guide.cpp
index 96b4cd9622a24..100b580fe9f02 100644
--- a/clang/test/SemaTemplate/deduction-guide.cpp
+++ b/clang/test/SemaTemplate/deduction-guide.cpp
@@ -315,19 +315,19 @@ namespace TTP {
 // CHECK-NEXT:  |-TemplateTypeParmDecl {{.+}} class depth 0 index 0 T{{$}}
 // CHECK-NEXT:  |-TemplateTemplateParmDecl {{.+}} depth 0 index 1 TT{{$}}
 // CHECK-NEXT:  | `-TemplateTypeParmDecl {{.+}} class depth 1 index 0{{$}}
-// CHECK-NEXT:  |-CXXDeductionGuideDecl {{.+}} 'auto () -> B'{{$}}
-// CHECK-NEXT:  | `-ParmVarDecl {{.+}} ''{{$}}
+// CHECK-NEXT:  |-CXXDeductionGuideDecl {{.+}} 'auto 
(template-parameter-0-1) -> B'{{$}}
+// CHECK-NEXT:  | `-ParmVarDecl {{.+}} 'template-parameter-0-1'{{$}}
 // CHECK-NEXT:  `-CXXDeductionGuideDecl {{.+}} 'auto (A) -> TTP::B'
 // CHECK-NEXT:|-TemplateArgument type 'int'
 // CHECK-NEXT:| `-BuiltinType {{.+}} 'int'{{$}}
 // CHECK-NEXT:|-TemplateArgument template 'TTP::A'{{$}}
 // CHECK-NEXT:| `-ClassTemplateDecl {{.+}} A{{$}}
 // CHECK-NEXT:`-ParmVarDecl {{.+}} 'A':'TTP::A'{{$}}
-// CHECK-NEXT:  FunctionProtoType {{.+}} 'auto () -> B' dependent 
trailing_return cdecl{{$}}
+// CHECK-NEXT:  FunctionProtoType {{.+}} 'auto (template-parameter-0-1) -> 
B' dependent trailing_return cdecl{{$}}
 // CHECK-NEXT:  |-InjectedClassNameType {{.+}} 'B' dependent{{$}}
 // CHECK-NEXT:  | `-CXXRecord {{.+}} 'B'{{$}}
-// CHECK-NEXT:  `-ElaboratedType {{.+}} '' sugar dependent{{$}}
-// CHECK-NEXT:`-TemplateSpecializationType {{.+}} '' dependent {{$}}
+// CHECK-NEXT:  `-ElaboratedType {{.+}} 'template-parameter-0-1' sugar 
dependent{{$}}
+// CHECK-NEXT:`-TemplateSpecializationType {{.+}} 
'template-parameter-0-1' dependent template-parameter-0-1{{$}}
 // CHECK-NEXT:  `-TemplateArgument type 'T':'type-p

[llvm-branch-commits] [clang] [clang] fix printing of canonical template template parameters take 2 (PR #93448)

2024-05-29 Thread Matheus Izvekov via llvm-branch-commits

mizvekov wrote:

Sorry, there were no libcxx or Sema.h changes, it was a GitHub issue, I just 
rebased a PR stacked below this one.

https://github.com/llvm/llvm-project/pull/93448
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] text ast-dumper: dump TemplateName for TST and DTST (PR #93766)

2024-05-29 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/93766

Implement AST text dumping of the TemplateName for TemplateSpecializationType 
and DeducedTemplateSpecializationType.

>From 4fe380db6671d38af26b80545d551c4930f1e6d5 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Thu, 30 May 2024 01:24:53 -0300
Subject: [PATCH] [clang] text ast-dumper: dump TemplateName for TST and DTST

Implement AST text dumping of the TemplateName for
TemplateSpecializationType and VisitDeducedTemplateSpecializationType.
---
 clang/include/clang/AST/TemplateName.h|  4 ++
 clang/include/clang/AST/TextNodeDumper.h  |  3 +-
 clang/lib/AST/TextNodeDumper.cpp  | 43 
 clang/test/AST/ast-dump-ctad-alias.cpp|  6 ++-
 clang/test/AST/ast-dump-template-decls.cpp| 14 --
 clang/test/AST/ast-dump-template-name.cpp |  6 +++
 clang/test/AST/ast-dump-using-template.cpp| 18 +--
 clang/test/Import/builtin-template/test.cpp   | 11 +---
 .../aggregate-deduction-candidate.cpp |  4 +-
 clang/test/SemaTemplate/deduction-guide.cpp   | 22 
 clang/test/SemaTemplate/make_integer_seq.cpp  | 50 +--
 clang/test/SemaTemplate/type_pack_element.cpp | 34 +
 12 files changed, 149 insertions(+), 66 deletions(-)

diff --git a/clang/include/clang/AST/TemplateName.h 
b/clang/include/clang/AST/TemplateName.h
index 876be463c71d0..7aedc086ab7d0 100644
--- a/clang/include/clang/AST/TemplateName.h
+++ b/clang/include/clang/AST/TemplateName.h
@@ -360,6 +360,10 @@ class TemplateName {
   static TemplateName getFromVoidPointer(void *Ptr) {
 return TemplateName(Ptr);
   }
+
+  /// Structural equality.
+  bool operator==(TemplateName Other) const { return Storage == Other.Storage; 
}
+  bool operator!=(TemplateName Other) const { return !operator==(Other); }
 };
 
 /// Insertion operator for diagnostics.  This allows sending TemplateName's
diff --git a/clang/include/clang/AST/TextNodeDumper.h 
b/clang/include/clang/AST/TextNodeDumper.h
index 63fa16c9ec47c..caa33abd99e47 100644
--- a/clang/include/clang/AST/TextNodeDumper.h
+++ b/clang/include/clang/AST/TextNodeDumper.h
@@ -214,7 +214,8 @@ class TextNodeDumper
   void dumpNestedNameSpecifier(const NestedNameSpecifier *NNS);
   void dumpConceptReference(const ConceptReference *R);
   void dumpTemplateArgument(const TemplateArgument &TA);
-  void dumpTemplateName(TemplateName TN);
+  void dumpBareTemplateName(TemplateName TN);
+  void dumpTemplateName(TemplateName TN, StringRef Label = {});
 
   void dumpDeclRef(const Decl *D, StringRef Label = {});
 
diff --git a/clang/lib/AST/TextNodeDumper.cpp b/clang/lib/AST/TextNodeDumper.cpp
index a0eedc71ea220..0e0e0a86f5cfc 100644
--- a/clang/lib/AST/TextNodeDumper.cpp
+++ b/clang/lib/AST/TextNodeDumper.cpp
@@ -1126,7 +1126,32 @@ void TextNodeDumper::VisitIntegralTemplateArgument(const 
TemplateArgument &TA) {
   dumpTemplateArgument(TA);
 }
 
-void TextNodeDumper::dumpTemplateName(TemplateName TN) {
+void TextNodeDumper::dumpTemplateName(TemplateName TN, StringRef Label) {
+  AddChild(Label, [=] {
+{
+  llvm::SmallString<128> Str;
+  {
+llvm::raw_svector_ostream SS(Str);
+TN.print(SS, PrintPolicy);
+  }
+  OS << " '" << Str << "'";
+
+  if (TemplateName CanonTN = Context->getCanonicalTemplateName(TN);
+  CanonTN != TN) {
+llvm::SmallString<128> CanonStr;
+{
+  llvm::raw_svector_ostream SS(CanonStr);
+  CanonTN.print(SS, PrintPolicy);
+}
+if (CanonStr != Str)
+  OS << ":'" << CanonStr << "'";
+  }
+}
+dumpBareTemplateName(TN);
+  });
+}
+
+void TextNodeDumper::dumpBareTemplateName(TemplateName TN) {
   switch (TN.getKind()) {
   case TemplateName::Template:
 AddChild([=] { Visit(TN.getAsTemplateDecl()); });
@@ -1143,7 +1168,7 @@ void TextNodeDumper::dumpTemplateName(TemplateName TN) {
 if (QTN->hasTemplateKeyword())
   OS << " keyword";
 dumpNestedNameSpecifier(QTN->getQualifier());
-dumpTemplateName(QTN->getUnderlyingTemplate());
+dumpBareTemplateName(QTN->getUnderlyingTemplate());
 return;
   }
   case TemplateName::DependentTemplate: {
@@ -1162,7 +1187,7 @@ void TextNodeDumper::dumpTemplateName(TemplateName TN) {
 if (const TemplateTemplateParmDecl *P = STS->getParameter())
   AddChild("parameter", [=] { Visit(P); });
 dumpDeclRef(STS->getAssociatedDecl(), "associated");
-AddChild("replacement", [=] { dumpTemplateName(STS->getReplacement()); });
+dumpTemplateName(STS->getReplacement(), "replacement");
 return;
   }
   // FIXME: Implement these.
@@ -1182,14 +1207,14 @@ void TextNodeDumper::dumpTemplateName(TemplateName TN) {
 void TextNodeDumper::VisitTemplateTemplateArgument(const TemplateArgument &TA) 
{
   OS << " template";
   dumpTemplateArgument(TA);
-  dumpTemplateName(TA.getAsTemplate());
+  dumpBareTemplateName(TA.getAsTemplate());
 }
 
 void TextNodeDumper::VisitTe

[llvm-branch-commits] [clang] [clang] text ast-dumper: dump TemplateName for TST and DTST (PR #93766)

2024-05-30 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/93766

>From 9193420d850ec65a5095d51e8281378febfb5206 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Thu, 30 May 2024 01:24:53 -0300
Subject: [PATCH] [clang] text ast-dumper: dump TemplateName for TST and DTST

Implement AST text dumping of the TemplateName for
TemplateSpecializationType and VisitDeducedTemplateSpecializationType.
---
 clang/include/clang/AST/TemplateName.h|  4 ++
 clang/include/clang/AST/TextNodeDumper.h  |  3 +-
 clang/lib/AST/TextNodeDumper.cpp  | 43 
 clang/test/AST/ast-dump-ctad-alias.cpp|  6 ++-
 clang/test/AST/ast-dump-template-decls.cpp| 14 --
 clang/test/AST/ast-dump-template-name.cpp |  6 +++
 clang/test/AST/ast-dump-using-template.cpp| 18 +--
 clang/test/Import/builtin-template/test.cpp   | 11 +---
 .../aggregate-deduction-candidate.cpp |  4 +-
 clang/test/SemaTemplate/deduction-guide.cpp   | 22 
 clang/test/SemaTemplate/make_integer_seq.cpp  | 50 +--
 clang/test/SemaTemplate/type_pack_element.cpp | 34 +
 12 files changed, 149 insertions(+), 66 deletions(-)

diff --git a/clang/include/clang/AST/TemplateName.h 
b/clang/include/clang/AST/TemplateName.h
index 876be463c71d0..7aedc086ab7d0 100644
--- a/clang/include/clang/AST/TemplateName.h
+++ b/clang/include/clang/AST/TemplateName.h
@@ -360,6 +360,10 @@ class TemplateName {
   static TemplateName getFromVoidPointer(void *Ptr) {
 return TemplateName(Ptr);
   }
+
+  /// Structural equality.
+  bool operator==(TemplateName Other) const { return Storage == Other.Storage; 
}
+  bool operator!=(TemplateName Other) const { return !operator==(Other); }
 };
 
 /// Insertion operator for diagnostics.  This allows sending TemplateName's
diff --git a/clang/include/clang/AST/TextNodeDumper.h 
b/clang/include/clang/AST/TextNodeDumper.h
index 63fa16c9ec47c..caa33abd99e47 100644
--- a/clang/include/clang/AST/TextNodeDumper.h
+++ b/clang/include/clang/AST/TextNodeDumper.h
@@ -214,7 +214,8 @@ class TextNodeDumper
   void dumpNestedNameSpecifier(const NestedNameSpecifier *NNS);
   void dumpConceptReference(const ConceptReference *R);
   void dumpTemplateArgument(const TemplateArgument &TA);
-  void dumpTemplateName(TemplateName TN);
+  void dumpBareTemplateName(TemplateName TN);
+  void dumpTemplateName(TemplateName TN, StringRef Label = {});
 
   void dumpDeclRef(const Decl *D, StringRef Label = {});
 
diff --git a/clang/lib/AST/TextNodeDumper.cpp b/clang/lib/AST/TextNodeDumper.cpp
index a0eedc71ea220..0e0e0a86f5cfc 100644
--- a/clang/lib/AST/TextNodeDumper.cpp
+++ b/clang/lib/AST/TextNodeDumper.cpp
@@ -1126,7 +1126,32 @@ void TextNodeDumper::VisitIntegralTemplateArgument(const 
TemplateArgument &TA) {
   dumpTemplateArgument(TA);
 }
 
-void TextNodeDumper::dumpTemplateName(TemplateName TN) {
+void TextNodeDumper::dumpTemplateName(TemplateName TN, StringRef Label) {
+  AddChild(Label, [=] {
+{
+  llvm::SmallString<128> Str;
+  {
+llvm::raw_svector_ostream SS(Str);
+TN.print(SS, PrintPolicy);
+  }
+  OS << " '" << Str << "'";
+
+  if (TemplateName CanonTN = Context->getCanonicalTemplateName(TN);
+  CanonTN != TN) {
+llvm::SmallString<128> CanonStr;
+{
+  llvm::raw_svector_ostream SS(CanonStr);
+  CanonTN.print(SS, PrintPolicy);
+}
+if (CanonStr != Str)
+  OS << ":'" << CanonStr << "'";
+  }
+}
+dumpBareTemplateName(TN);
+  });
+}
+
+void TextNodeDumper::dumpBareTemplateName(TemplateName TN) {
   switch (TN.getKind()) {
   case TemplateName::Template:
 AddChild([=] { Visit(TN.getAsTemplateDecl()); });
@@ -1143,7 +1168,7 @@ void TextNodeDumper::dumpTemplateName(TemplateName TN) {
 if (QTN->hasTemplateKeyword())
   OS << " keyword";
 dumpNestedNameSpecifier(QTN->getQualifier());
-dumpTemplateName(QTN->getUnderlyingTemplate());
+dumpBareTemplateName(QTN->getUnderlyingTemplate());
 return;
   }
   case TemplateName::DependentTemplate: {
@@ -1162,7 +1187,7 @@ void TextNodeDumper::dumpTemplateName(TemplateName TN) {
 if (const TemplateTemplateParmDecl *P = STS->getParameter())
   AddChild("parameter", [=] { Visit(P); });
 dumpDeclRef(STS->getAssociatedDecl(), "associated");
-AddChild("replacement", [=] { dumpTemplateName(STS->getReplacement()); });
+dumpTemplateName(STS->getReplacement(), "replacement");
 return;
   }
   // FIXME: Implement these.
@@ -1182,14 +1207,14 @@ void TextNodeDumper::dumpTemplateName(TemplateName TN) {
 void TextNodeDumper::VisitTemplateTemplateArgument(const TemplateArgument &TA) 
{
   OS << " template";
   dumpTemplateArgument(TA);
-  dumpTemplateName(TA.getAsTemplate());
+  dumpBareTemplateName(TA.getAsTemplate());
 }
 
 void TextNodeDumper::VisitTemplateExpansionTemplateArgument(
 const TemplateArgument &TA) {
   OS << " template expansion";
   dumpTemplateArgu

[llvm-branch-commits] [clang] [clang] Finish implementation of P0522 (PR #96023)

2024-06-18 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/96023

This finishes the clang implementation of P0522, getting rid of the fallback to 
the old, pre-P0522 rules.

Before this patch, when partial ordering template template parameters, we would 
perform, in order:
* If the old rules would match, we would accept it. Otherwise, don't generate 
diagnostics yet.
* If the new rules would match, just accept it. Otherwise, don't generate any 
diagnostics yet again.
* Apply the old rules again, this time with diagnostics.

This situation was far from ideal, as we would sometimes:
* Accept some things we shouldn't.
* Reject some things we shouldn't.
* Only diagnose rejection in terms of the old rules.

With this patch, we apply the P0522 rules throughout.

This needed to extend template argument deduction in order to accept the 
historial rule for TTP matching pack parameter to non-pack arguments.
This change also makes us accept some combinations of historical and P0522 
allowances we wouldn't before.

It also fixes a bunch of bugs that were documented in the test suite, which I 
am not sure there are issues already created for them.

This causes a lot of changes to the way these failures are diagnosed, with 
related test suite churn.

The problem here is that the old rules were very simple and non-recursive, 
making it easy to provide customized diagnostics, and to keep them consistent 
with each other.

The new rules are a lot more complex and rely on template argument deduction, 
substitutions, and they are recursive.

The approach taken here is to mostly rely on existing diagnostics, and create a 
new instantiation context that keeps track of things.

So for example when a substitution failure occurs, we use the error produced 
there unmodified, and just attach notes to it explaining that it occurred in 
the context of partial ordering this template argument against that template 
parameter.

This diverges from the old diagnostics, which would lead with an error pointing 
to the template argument, explain the problem in subsequent notes, and produce 
a final note pointing to the parameter.

>From 453df309b880468ded94fc8f2d670908e7bcb5c7 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Mon, 17 Jun 2024 21:39:08 -0300
Subject: [PATCH] [clang] Finish implementation of P0522

This finishes the clang implementation of P0522, getting rid
of the fallback to the old, pre-P0522 rules.

Before this patch, when partial ordering template template parameters,
we would perform, in order:
* If the old rules would match, we would accept it. Otherwise, don't
  generate diagnostics yet.
* If the new rules would match, just accept it. Otherwise, don't
  generate any diagnostics yet again.
* Apply the old rules again, this time with diagnostics.

This situation was far from ideal, as we would sometimes:
* Accept some things we shouldn't.
* Reject some things we shouldn't.
* Only diagnose rejection in terms of the old rules.

With this patch, we apply the P0522 rules throughout.

This needed to extend template argument deduction in order
to accept the historial rule for TTP matching pack parameter to non-pack
arguments.
This change also makes us accept some combinations of historical and P0522
allowances we wouldn't before.

It also fixes a bunch of bugs that were documented in the test suite,
which I am not sure there are issues already created for them.

This causes a lot of changes to the way these failures are diagnosed,
with related test suite churn.

The problem here is that the old rules were very simple and
non-recursive, making it easy to provide customized diagnostics,
and to keep them consistent with each other.

The new rules are a lot more complex and rely on template argument
deduction, substitutions, and they are recursive.

The approach taken here is to mostly rely on existing diagnostics,
and create a new instantiation context that keeps track of this context.

So for example when a substitution failure occurs, we use the error
produced there unmodified, and just attach notes to it explaining
that it occurred in the context of partial ordering this template
argument against that template parameter.

This diverges from the old diagnostics, which would lead with an
error pointing to the template argument, explain the problem
in subsequent notes, and produce a final note pointing to the parameter.
---
 clang/docs/ReleaseNotes.rst   |   9 +-
 .../clang/Basic/DiagnosticSemaKinds.td|   7 +
 clang/include/clang/Sema/Sema.h   |  14 +-
 clang/lib/Frontend/FrontendActions.cpp|   2 +
 clang/lib/Sema/SemaTemplate.cpp   |  95 ++---
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 341 +-
 clang/lib/Sema/SemaTemplateInstantiate.cpp|  15 +
 .../temp/temp.arg/temp.arg.template/p3-0x.cpp |  31 +-
 clang/test/CXX/temp/temp.param/p12.cpp|  21 +-
 clang/test/Modules/cxx-templates.cpp  |  15 +-
 clang/test/Sema

[llvm-branch-commits] [clang] [clang] Finish implementation of P0522 (PR #96023)

2024-06-18 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/96023

>From 03d5720d113ff3ce03694b27d376230d06d7693e Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Mon, 17 Jun 2024 21:39:08 -0300
Subject: [PATCH] [clang] Finish implementation of P0522

This finishes the clang implementation of P0522, getting rid
of the fallback to the old, pre-P0522 rules.

Before this patch, when partial ordering template template parameters,
we would perform, in order:
* If the old rules would match, we would accept it. Otherwise, don't
  generate diagnostics yet.
* If the new rules would match, just accept it. Otherwise, don't
  generate any diagnostics yet again.
* Apply the old rules again, this time with diagnostics.

This situation was far from ideal, as we would sometimes:
* Accept some things we shouldn't.
* Reject some things we shouldn't.
* Only diagnose rejection in terms of the old rules.

With this patch, we apply the P0522 rules throughout.

This needed to extend template argument deduction in order
to accept the historial rule for TTP matching pack parameter to non-pack
arguments.
This change also makes us accept some combinations of historical and P0522
allowances we wouldn't before.

It also fixes a bunch of bugs that were documented in the test suite,
which I am not sure there are issues already created for them.

This causes a lot of changes to the way these failures are diagnosed,
with related test suite churn.

The problem here is that the old rules were very simple and
non-recursive, making it easy to provide customized diagnostics,
and to keep them consistent with each other.

The new rules are a lot more complex and rely on template argument
deduction, substitutions, and they are recursive.

The approach taken here is to mostly rely on existing diagnostics,
and create a new instantiation context that keeps track of this context.

So for example when a substitution failure occurs, we use the error
produced there unmodified, and just attach notes to it explaining
that it occurred in the context of partial ordering this template
argument against that template parameter.

This diverges from the old diagnostics, which would lead with an
error pointing to the template argument, explain the problem
in subsequent notes, and produce a final note pointing to the parameter.
---
 clang/docs/ReleaseNotes.rst   |   9 +-
 .../clang/Basic/DiagnosticSemaKinds.td|   7 +
 clang/include/clang/Sema/Sema.h   |  14 +-
 clang/lib/Frontend/FrontendActions.cpp|   2 +
 clang/lib/Sema/SemaTemplate.cpp   |  94 ++---
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 341 +-
 clang/lib/Sema/SemaTemplateInstantiate.cpp|  15 +
 .../temp/temp.arg/temp.arg.template/p3-0x.cpp |  31 +-
 clang/test/CXX/temp/temp.param/p12.cpp|  21 +-
 clang/test/Modules/cxx-templates.cpp  |  15 +-
 clang/test/SemaCXX/make_integer_seq.cpp   |   5 +-
 clang/test/SemaTemplate/cwg2398.cpp   |  30 +-
 clang/test/SemaTemplate/temp_arg_nontype.cpp  |  45 +--
 clang/test/SemaTemplate/temp_arg_template.cpp |  38 +-
 .../SemaTemplate/temp_arg_template_p0522.cpp  |  70 ++--
 .../Templight/templight-empty-entries-fix.cpp |  12 +
 .../templight-prior-template-arg.cpp  |  33 +-
 17 files changed, 503 insertions(+), 279 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7112d1f889fef..abe535f55fb2a 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -176,6 +176,8 @@ C++17 Feature Support
   the values produced by GCC, so these macros should not be used from header
   files because they may not be stable across multiple TUs (the values may vary
   based on compiler version as well as CPU tuning). #GH60174
+- The implementation of the relaxed template template argument matching rules 
is
+  more complete and reliable, and should provide more accurate diagnostics.
 
 C++14 Feature Support
 ^
@@ -589,6 +591,10 @@ Improvements to Clang's diagnostics
 - Clang no longer emits a "declared here" note for a builtin function that has 
no declaration in source.
   Fixes #GH93369.
 
+- Clang now properly explains the reason a template template argument failed to
+  match a template template parameter, in terms of the C++17 relaxed matching 
rules
+  instead of the old ones.
+
 Improvements to Clang's time-trace
 --
 
@@ -887,7 +893,8 @@ Bug Fixes to C++ Support
   between the addresses of two labels (a GNU extension) to a pointer within a 
constant expression. (#GH95366).
 - Fix immediate escalation bugs in the presence of dependent call arguments. 
(#GH94935)
 - Clang now diagnoses explicit specializations with storage class specifiers 
in all contexts.
-
+- Fixes to several issues in partial ordering of template template parameters, 
which
+  were documented in the test suite.
 
 Bug Fixes to AST Handling
 

[llvm-branch-commits] [clang] [clang] Finish implementation of P0522 (PR #96023)

2024-06-19 Thread Matheus Izvekov via llvm-branch-commits


@@ -2513,49 +2545,76 @@ DeduceTemplateArguments(Sema &S, TemplateParameterList 
*TemplateParams,
 TemplateDeductionInfo &Info,
 SmallVectorImpl &Deduced,
 bool NumberOfArgumentsMustMatch, PackFold PackFold) {
-  if (PackFold == PackFold::ArgumentToParameter)
-std::swap(Ps, As);
+  bool FoldPackParameter = PackFold == PackFold::ParameterToArgument ||
+   PackFold == PackFold::Both,
+   FoldPackArgument = PackFold == PackFold::ArgumentToParameter ||
+  PackFold == PackFold::Both;
+
   // C++0x [temp.deduct.type]p9:
   //   If the template argument list of P contains a pack expansion that is not
   //   the last template argument, the entire template argument list is a
   //   non-deduced context.
-  if (hasPackExpansionBeforeEnd(Ps))
+  if (FoldPackParameter && hasPackExpansionBeforeEnd(Ps))
+return TemplateDeductionResult::Success;
+
+  if (FoldPackArgument && hasPackExpansionBeforeEnd(As))
 return TemplateDeductionResult::Success;
 
   // C++0x [temp.deduct.type]p9:
   //   If P has a form that contains  or , then each argument Pi of the
   //   respective template argument list P is compared with the corresponding
   //   argument Ai of the corresponding template argument list of A.
-  unsigned ArgIdx = 0, ParamIdx = 0;
-  for (; hasTemplateArgumentForDeduction(Ps, ParamIdx); ++ParamIdx) {
-const TemplateArgument &P = Ps[ParamIdx];
-if (!P.isPackExpansion()) {
+  for (unsigned ArgIdx = 0, ParamIdx = 0; /**/; /**/) {
+if (!hasTemplateArgumentForDeduction(Ps, ParamIdx))
+  return !FoldPackParameter && NumberOfArgumentsMustMatch &&
+ hasTemplateArgumentForDeduction(As, ArgIdx) &&
+ !As[ArgIdx].isPackExpansion()
+ ? TemplateDeductionResult::MiscellaneousDeductionFailure
+ : TemplateDeductionResult::Success;
+
+if (!Ps[ParamIdx].isPackExpansion()) {
   // The simple case: deduce template arguments by matching Pi and Ai.
 
   // Check whether we have enough arguments.
   if (!hasTemplateArgumentForDeduction(As, ArgIdx))
-return NumberOfArgumentsMustMatch
+return !FoldPackArgument && NumberOfArgumentsMustMatch
? TemplateDeductionResult::MiscellaneousDeductionFailure

mizvekov wrote:

The pre-existing error we have used for this is 
`MiscellaneousDeductionFailure`. `IncompletePack` means something else, it's 
used when we have an already expanded pack and we failed to deduce all elements 
of it.

This is a separate thing we have to fix, basically get rid of the 
`MiscellaneousDeductionFailure`, create new representations for all the 
separate things it was used for, and remove the generic `bad deduction` 
diagnostic.

But this would touch tests far outside of the scope of this patch, so I think 
it's best left for a separate PR.

https://github.com/llvm/llvm-project/pull/96023
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] Finish implementation of P0522 (PR #96023)

2024-06-19 Thread Matheus Izvekov via llvm-branch-commits


@@ -2513,49 +2545,76 @@ DeduceTemplateArguments(Sema &S, TemplateParameterList 
*TemplateParams,
 TemplateDeductionInfo &Info,
 SmallVectorImpl &Deduced,
 bool NumberOfArgumentsMustMatch, PackFold PackFold) {
-  if (PackFold == PackFold::ArgumentToParameter)
-std::swap(Ps, As);
+  bool FoldPackParameter = PackFold == PackFold::ParameterToArgument ||
+   PackFold == PackFold::Both,
+   FoldPackArgument = PackFold == PackFold::ArgumentToParameter ||
+  PackFold == PackFold::Both;
+
   // C++0x [temp.deduct.type]p9:
   //   If the template argument list of P contains a pack expansion that is not
   //   the last template argument, the entire template argument list is a
   //   non-deduced context.
-  if (hasPackExpansionBeforeEnd(Ps))
+  if (FoldPackParameter && hasPackExpansionBeforeEnd(Ps))
+return TemplateDeductionResult::Success;
+
+  if (FoldPackArgument && hasPackExpansionBeforeEnd(As))
 return TemplateDeductionResult::Success;
 
   // C++0x [temp.deduct.type]p9:
   //   If P has a form that contains  or , then each argument Pi of the
   //   respective template argument list P is compared with the corresponding
   //   argument Ai of the corresponding template argument list of A.
-  unsigned ArgIdx = 0, ParamIdx = 0;
-  for (; hasTemplateArgumentForDeduction(Ps, ParamIdx); ++ParamIdx) {
-const TemplateArgument &P = Ps[ParamIdx];
-if (!P.isPackExpansion()) {
+  for (unsigned ArgIdx = 0, ParamIdx = 0; /**/; /**/) {
+if (!hasTemplateArgumentForDeduction(Ps, ParamIdx))
+  return !FoldPackParameter && NumberOfArgumentsMustMatch &&
+ hasTemplateArgumentForDeduction(As, ArgIdx) &&
+ !As[ArgIdx].isPackExpansion()
+ ? TemplateDeductionResult::MiscellaneousDeductionFailure

mizvekov wrote:

As above

https://github.com/llvm/llvm-project/pull/96023
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] Finish implementation of P0522 (PR #96023)

2024-06-19 Thread Matheus Izvekov via llvm-branch-commits


@@ -3284,16 +3345,20 @@ DeduceTemplateArguments(Sema &S, T *Partial,
   if (Inst.isInvalid())
 return TemplateDeductionResult::InstantiationDepth;
 
-  if (Trap.hasErrorOccurred())
-return TemplateDeductionResult::SubstitutionFailure;
-
   TemplateDeductionResult Result;
   S.runWithSufficientStackSpace(Info.getLocation(), [&] {
 Result = ::FinishTemplateArgumentDeduction(S, Partial,
/*IsPartialOrdering=*/false,
TemplateArgs, Deduced, Info);
   });
-  return Result;
+
+  if (Result != TemplateDeductionResult::Success)
+return Result;
+
+  if (Trap.hasErrorOccurred())
+return TemplateDeductionResult::SubstitutionFailure;
+
+  return TemplateDeductionResult::Success;

mizvekov wrote:

It would change the priority we give to these errors, and I think there is a 
better chance the previous error would have had more context and been more 
helpful.

https://github.com/llvm/llvm-project/pull/96023
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] Finish implementation of P0522 (PR #96023)

2024-06-19 Thread Matheus Izvekov via llvm-branch-commits


@@ -6369,27 +6451,88 @@ bool 
Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
   //   be inverted between Ps and As. On non-deduced context, matching needs to
   //   happen both ways, according to [temp.arg.template]p3, but this is
   //   currently implemented as a special case elsewhere.
-  if (::DeduceTemplateArguments(*this, A, AArgs, PArgs, Info, Deduced,
-/*NumberOfArgumentsMustMatch=*/false,
-IsDeduced ? PackFold::ArgumentToParameter
-  : PackFold::ParameterToArgument) !=
-  TemplateDeductionResult::Success)
+  switch (TemplateDeductionResult Result = ::DeduceTemplateArguments(
+  *this, A, AArgs, PArgs, Info, Deduced,
+  /*NumberOfArgumentsMustMatch=*/false,
+  IsDeduced ? PackFold::ArgumentToParameter : PackFold::Both)) {
+  case clang::TemplateDeductionResult::Success:
+break;
+
+  case TemplateDeductionResult::MiscellaneousDeductionFailure:
+Diag(AArg->getLocation(), diag::err_template_param_list_different_arity)
+<< (A->size() > P->size()) << /*isTemplateTemplateParameter=*/true
+<< SourceRange(A->getTemplateLoc(), P->getRAngleLoc());
+return false;

mizvekov wrote:

The right thing would be to introduce a new enumerator, but I think this patch 
keeps the status quo while being large enough already.

https://github.com/llvm/llvm-project/pull/96023
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] Finish implementation of P0522 (PR #96023)

2024-06-19 Thread Matheus Izvekov via llvm-branch-commits


@@ -6369,27 +6451,88 @@ bool 
Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
   //   be inverted between Ps and As. On non-deduced context, matching needs to
   //   happen both ways, according to [temp.arg.template]p3, but this is
   //   currently implemented as a special case elsewhere.
-  if (::DeduceTemplateArguments(*this, A, AArgs, PArgs, Info, Deduced,
-/*NumberOfArgumentsMustMatch=*/false,
-IsDeduced ? PackFold::ArgumentToParameter
-  : PackFold::ParameterToArgument) !=
-  TemplateDeductionResult::Success)
+  switch (TemplateDeductionResult Result = ::DeduceTemplateArguments(
+  *this, A, AArgs, PArgs, Info, Deduced,
+  /*NumberOfArgumentsMustMatch=*/false,
+  IsDeduced ? PackFold::ArgumentToParameter : PackFold::Both)) {
+  case clang::TemplateDeductionResult::Success:
+break;
+
+  case TemplateDeductionResult::MiscellaneousDeductionFailure:
+Diag(AArg->getLocation(), diag::err_template_param_list_different_arity)
+<< (A->size() > P->size()) << /*isTemplateTemplateParameter=*/true
+<< SourceRange(A->getTemplateLoc(), P->getRAngleLoc());
+return false;
+  case TemplateDeductionResult::NonDeducedMismatch:
+Diag(AArg->getLocation(), diag::err_non_deduced_mismatch)
+<< Info.FirstArg << Info.SecondArg;
+return false;
+  case TemplateDeductionResult::Inconsistent:
+Diag(getAsNamedDecl(Info.Param)->getLocation(),
+ diag::err_inconsistent_deduction)
+<< Info.FirstArg << Info.SecondArg;
+return false;
+  case TemplateDeductionResult::AlreadyDiagnosed:
 return false;
 
+  // None of these should happen for a plain deduction.
+  case TemplateDeductionResult::Invalid:
+  case TemplateDeductionResult::InstantiationDepth:
+  case TemplateDeductionResult::Incomplete:
+  case TemplateDeductionResult::IncompletePack:
+  case TemplateDeductionResult::Underqualified:
+  case TemplateDeductionResult::SubstitutionFailure:
+  case TemplateDeductionResult::DeducedMismatch:
+  case TemplateDeductionResult::DeducedMismatchNested:
+  case TemplateDeductionResult::TooManyArguments:
+  case TemplateDeductionResult::TooFewArguments:
+  case TemplateDeductionResult::InvalidExplicitArguments:
+  case TemplateDeductionResult::NonDependentConversionFailure:
+  case TemplateDeductionResult::ConstraintsNotSatisfied:
+  case TemplateDeductionResult::CUDATargetMismatch:

mizvekov wrote:

Adding default would suppress the warning you get when one of the enumerators 
is missing a case. I think this is an immensely useful warning, it helps you 
not forget to look for and do something about each place the enumerator could 
be used.

https://github.com/llvm/llvm-project/pull/96023
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] Finish implementation of P0522 (PR #96023)

2024-06-19 Thread Matheus Izvekov via llvm-branch-commits


@@ -6369,27 +6451,88 @@ bool 
Sema::isTemplateTemplateParameterAtLeastAsSpecializedAs(
   //   be inverted between Ps and As. On non-deduced context, matching needs to
   //   happen both ways, according to [temp.arg.template]p3, but this is
   //   currently implemented as a special case elsewhere.
-  if (::DeduceTemplateArguments(*this, A, AArgs, PArgs, Info, Deduced,
-/*NumberOfArgumentsMustMatch=*/false,
-IsDeduced ? PackFold::ArgumentToParameter
-  : PackFold::ParameterToArgument) !=
-  TemplateDeductionResult::Success)
+  switch (TemplateDeductionResult Result = ::DeduceTemplateArguments(
+  *this, A, AArgs, PArgs, Info, Deduced,
+  /*NumberOfArgumentsMustMatch=*/false,
+  IsDeduced ? PackFold::ArgumentToParameter : PackFold::Both)) {
+  case clang::TemplateDeductionResult::Success:
+break;
+
+  case TemplateDeductionResult::MiscellaneousDeductionFailure:
+Diag(AArg->getLocation(), diag::err_template_param_list_different_arity)
+<< (A->size() > P->size()) << /*isTemplateTemplateParameter=*/true
+<< SourceRange(A->getTemplateLoc(), P->getRAngleLoc());
+return false;
+  case TemplateDeductionResult::NonDeducedMismatch:
+Diag(AArg->getLocation(), diag::err_non_deduced_mismatch)
+<< Info.FirstArg << Info.SecondArg;
+return false;
+  case TemplateDeductionResult::Inconsistent:
+Diag(getAsNamedDecl(Info.Param)->getLocation(),
+ diag::err_inconsistent_deduction)
+<< Info.FirstArg << Info.SecondArg;
+return false;
+  case TemplateDeductionResult::AlreadyDiagnosed:
 return false;
 
+  // None of these should happen for a plain deduction.
+  case TemplateDeductionResult::Invalid:
+  case TemplateDeductionResult::InstantiationDepth:
+  case TemplateDeductionResult::Incomplete:
+  case TemplateDeductionResult::IncompletePack:
+  case TemplateDeductionResult::Underqualified:
+  case TemplateDeductionResult::SubstitutionFailure:
+  case TemplateDeductionResult::DeducedMismatch:
+  case TemplateDeductionResult::DeducedMismatchNested:
+  case TemplateDeductionResult::TooManyArguments:
+  case TemplateDeductionResult::TooFewArguments:
+  case TemplateDeductionResult::InvalidExplicitArguments:
+  case TemplateDeductionResult::NonDependentConversionFailure:
+  case TemplateDeductionResult::ConstraintsNotSatisfied:
+  case TemplateDeductionResult::CUDATargetMismatch:

mizvekov wrote:

I think the sheer amount of enumerators here is an indication of this growing 
without careful design.

We could probably refactor this and collapse a lot of these cases into fewer 
cases, and such.

I think it would also be helpful to not have one TemplateDeductionResult to 
rule them all, when some times you are dealing with the subset of the problem 
and a lot of these cases don't apply at all.

https://github.com/llvm/llvm-project/pull/96023
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [libcxx] [clang] Finish implementation of P0522 (PR #96023)

2024-06-19 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/96023

>From 7c84cd61f2c1bf7ec30d77aaf6b1a87cccf96d2f Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Mon, 17 Jun 2024 21:39:08 -0300
Subject: [PATCH] [clang] Finish implementation of P0522

This finishes the clang implementation of P0522, getting rid
of the fallback to the old, pre-P0522 rules.

Before this patch, when partial ordering template template parameters,
we would perform, in order:
* If the old rules would match, we would accept it. Otherwise, don't
  generate diagnostics yet.
* If the new rules would match, just accept it. Otherwise, don't
  generate any diagnostics yet again.
* Apply the old rules again, this time with diagnostics.

This situation was far from ideal, as we would sometimes:
* Accept some things we shouldn't.
* Reject some things we shouldn't.
* Only diagnose rejection in terms of the old rules.

With this patch, we apply the P0522 rules throughout.

This needed to extend template argument deduction in order
to accept the historial rule for TTP matching pack parameter to non-pack
arguments.
This change also makes us accept some combinations of historical and P0522
allowances we wouldn't before.

It also fixes a bunch of bugs that were documented in the test suite,
which I am not sure there are issues already created for them.

This causes a lot of changes to the way these failures are diagnosed,
with related test suite churn.

The problem here is that the old rules were very simple and
non-recursive, making it easy to provide customized diagnostics,
and to keep them consistent with each other.

The new rules are a lot more complex and rely on template argument
deduction, substitutions, and they are recursive.

The approach taken here is to mostly rely on existing diagnostics,
and create a new instantiation context that keeps track of this context.

So for example when a substitution failure occurs, we use the error
produced there unmodified, and just attach notes to it explaining
that it occurred in the context of partial ordering this template
argument against that template parameter.

This diverges from the old diagnostics, which would lead with an
error pointing to the template argument, explain the problem
in subsequent notes, and produce a final note pointing to the parameter.
---
 clang/docs/ReleaseNotes.rst   |   9 +-
 .../clang/Basic/DiagnosticSemaKinds.td|   7 +
 clang/include/clang/Sema/Sema.h   |  14 +-
 clang/lib/Frontend/FrontendActions.cpp|   2 +
 clang/lib/Sema/SemaTemplate.cpp   |  94 ++---
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 341 +-
 clang/lib/Sema/SemaTemplateInstantiate.cpp|  15 +
 .../temp/temp.arg/temp.arg.template/p3-0x.cpp |  31 +-
 clang/test/CXX/temp/temp.param/p12.cpp|  21 +-
 clang/test/Modules/cxx-templates.cpp  |  15 +-
 clang/test/SemaCXX/make_integer_seq.cpp   |   5 +-
 clang/test/SemaTemplate/cwg2398.cpp   |  30 +-
 clang/test/SemaTemplate/temp_arg_nontype.cpp  |  45 +--
 clang/test/SemaTemplate/temp_arg_template.cpp |  38 +-
 .../SemaTemplate/temp_arg_template_p0522.cpp  |  70 ++--
 .../Templight/templight-empty-entries-fix.cpp |  12 +
 .../templight-prior-template-arg.cpp  |  33 +-
 .../type_traits/is_specialization.verify.cpp  |   2 +-
 18 files changed, 504 insertions(+), 280 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7112d1f889fef..abe535f55fb2a 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -176,6 +176,8 @@ C++17 Feature Support
   the values produced by GCC, so these macros should not be used from header
   files because they may not be stable across multiple TUs (the values may vary
   based on compiler version as well as CPU tuning). #GH60174
+- The implementation of the relaxed template template argument matching rules 
is
+  more complete and reliable, and should provide more accurate diagnostics.
 
 C++14 Feature Support
 ^
@@ -589,6 +591,10 @@ Improvements to Clang's diagnostics
 - Clang no longer emits a "declared here" note for a builtin function that has 
no declaration in source.
   Fixes #GH93369.
 
+- Clang now properly explains the reason a template template argument failed to
+  match a template template parameter, in terms of the C++17 relaxed matching 
rules
+  instead of the old ones.
+
 Improvements to Clang's time-trace
 --
 
@@ -887,7 +893,8 @@ Bug Fixes to C++ Support
   between the addresses of two labels (a GNU extension) to a pointer within a 
constant expression. (#GH95366).
 - Fix immediate escalation bugs in the presence of dependent call arguments. 
(#GH94935)
 - Clang now diagnoses explicit specializations with storage class specifiers 
in all contexts.
-
+- Fixes to several issues in partial ordering of template template parameters, 
which
+  were documented in the test suite

[llvm-branch-commits] [clang] [libcxx] [clang] Finish implementation of P0522 (PR #96023)

2024-06-19 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/96023

>From dd761ef307502c69dd6fdbf2fa56275f56e8cb6a Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Mon, 17 Jun 2024 21:39:08 -0300
Subject: [PATCH] [clang] Finish implementation of P0522

This finishes the clang implementation of P0522, getting rid
of the fallback to the old, pre-P0522 rules.

Before this patch, when partial ordering template template parameters,
we would perform, in order:
* If the old rules would match, we would accept it. Otherwise, don't
  generate diagnostics yet.
* If the new rules would match, just accept it. Otherwise, don't
  generate any diagnostics yet again.
* Apply the old rules again, this time with diagnostics.

This situation was far from ideal, as we would sometimes:
* Accept some things we shouldn't.
* Reject some things we shouldn't.
* Only diagnose rejection in terms of the old rules.

With this patch, we apply the P0522 rules throughout.

This needed to extend template argument deduction in order
to accept the historial rule for TTP matching pack parameter to non-pack
arguments.
This change also makes us accept some combinations of historical and P0522
allowances we wouldn't before.

It also fixes a bunch of bugs that were documented in the test suite,
which I am not sure there are issues already created for them.

This causes a lot of changes to the way these failures are diagnosed,
with related test suite churn.

The problem here is that the old rules were very simple and
non-recursive, making it easy to provide customized diagnostics,
and to keep them consistent with each other.

The new rules are a lot more complex and rely on template argument
deduction, substitutions, and they are recursive.

The approach taken here is to mostly rely on existing diagnostics,
and create a new instantiation context that keeps track of this context.

So for example when a substitution failure occurs, we use the error
produced there unmodified, and just attach notes to it explaining
that it occurred in the context of partial ordering this template
argument against that template parameter.

This diverges from the old diagnostics, which would lead with an
error pointing to the template argument, explain the problem
in subsequent notes, and produce a final note pointing to the parameter.
---
 clang/docs/ReleaseNotes.rst   |   9 +-
 .../clang/Basic/DiagnosticSemaKinds.td|   7 +
 clang/include/clang/Sema/Sema.h   |  14 +-
 clang/lib/Frontend/FrontendActions.cpp|   2 +
 clang/lib/Sema/SemaTemplate.cpp   |  94 ++---
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 341 +-
 clang/lib/Sema/SemaTemplateInstantiate.cpp|  15 +
 .../temp/temp.arg/temp.arg.template/p3-0x.cpp |  31 +-
 clang/test/CXX/temp/temp.param/p12.cpp|  21 +-
 clang/test/Modules/cxx-templates.cpp  |  15 +-
 clang/test/SemaCXX/make_integer_seq.cpp   |   5 +-
 clang/test/SemaTemplate/cwg2398.cpp   |  30 +-
 clang/test/SemaTemplate/temp_arg_nontype.cpp  |  45 +--
 clang/test/SemaTemplate/temp_arg_template.cpp |  38 +-
 .../SemaTemplate/temp_arg_template_p0522.cpp  |  70 ++--
 .../Templight/templight-empty-entries-fix.cpp |  12 +
 .../templight-prior-template-arg.cpp  |  33 +-
 .../type_traits/is_specialization.verify.cpp  |   2 +-
 18 files changed, 504 insertions(+), 280 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7112d1f889fef..abe535f55fb2a 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -176,6 +176,8 @@ C++17 Feature Support
   the values produced by GCC, so these macros should not be used from header
   files because they may not be stable across multiple TUs (the values may vary
   based on compiler version as well as CPU tuning). #GH60174
+- The implementation of the relaxed template template argument matching rules 
is
+  more complete and reliable, and should provide more accurate diagnostics.
 
 C++14 Feature Support
 ^
@@ -589,6 +591,10 @@ Improvements to Clang's diagnostics
 - Clang no longer emits a "declared here" note for a builtin function that has 
no declaration in source.
   Fixes #GH93369.
 
+- Clang now properly explains the reason a template template argument failed to
+  match a template template parameter, in terms of the C++17 relaxed matching 
rules
+  instead of the old ones.
+
 Improvements to Clang's time-trace
 --
 
@@ -887,7 +893,8 @@ Bug Fixes to C++ Support
   between the addresses of two labels (a GNU extension) to a pointer within a 
constant expression. (#GH95366).
 - Fix immediate escalation bugs in the presence of dependent call arguments. 
(#GH94935)
 - Clang now diagnoses explicit specializations with storage class specifiers 
in all contexts.
-
+- Fixes to several issues in partial ordering of template template parameters, 
which
+  were documented in the test suite

[llvm-branch-commits] [clang] [libcxx] [clang] Finish implementation of P0522 (PR #96023)

2024-06-21 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/96023

>From e5df11098caf4500b6cb3e2de8f9c927b609955a Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Mon, 17 Jun 2024 21:39:08 -0300
Subject: [PATCH] [clang] Finish implementation of P0522

This finishes the clang implementation of P0522, getting rid
of the fallback to the old, pre-P0522 rules.

Before this patch, when partial ordering template template parameters,
we would perform, in order:
* If the old rules would match, we would accept it. Otherwise, don't
  generate diagnostics yet.
* If the new rules would match, just accept it. Otherwise, don't
  generate any diagnostics yet again.
* Apply the old rules again, this time with diagnostics.

This situation was far from ideal, as we would sometimes:
* Accept some things we shouldn't.
* Reject some things we shouldn't.
* Only diagnose rejection in terms of the old rules.

With this patch, we apply the P0522 rules throughout.

This needed to extend template argument deduction in order
to accept the historial rule for TTP matching pack parameter to non-pack
arguments.
This change also makes us accept some combinations of historical and P0522
allowances we wouldn't before.

It also fixes a bunch of bugs that were documented in the test suite,
which I am not sure there are issues already created for them.

This causes a lot of changes to the way these failures are diagnosed,
with related test suite churn.

The problem here is that the old rules were very simple and
non-recursive, making it easy to provide customized diagnostics,
and to keep them consistent with each other.

The new rules are a lot more complex and rely on template argument
deduction, substitutions, and they are recursive.

The approach taken here is to mostly rely on existing diagnostics,
and create a new instantiation context that keeps track of this context.

So for example when a substitution failure occurs, we use the error
produced there unmodified, and just attach notes to it explaining
that it occurred in the context of partial ordering this template
argument against that template parameter.

This diverges from the old diagnostics, which would lead with an
error pointing to the template argument, explain the problem
in subsequent notes, and produce a final note pointing to the parameter.
---
 clang/docs/ReleaseNotes.rst   |   9 +-
 .../clang/Basic/DiagnosticSemaKinds.td|   7 +
 clang/include/clang/Sema/Sema.h   |  14 +-
 clang/lib/Frontend/FrontendActions.cpp|   2 +
 clang/lib/Sema/SemaTemplate.cpp   |  94 ++---
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 339 +-
 clang/lib/Sema/SemaTemplateInstantiate.cpp|  15 +
 .../temp/temp.arg/temp.arg.template/p3-0x.cpp |  31 +-
 clang/test/CXX/temp/temp.param/p12.cpp|  21 +-
 clang/test/Modules/cxx-templates.cpp  |  15 +-
 clang/test/SemaCXX/make_integer_seq.cpp   |   5 +-
 clang/test/SemaTemplate/cwg2398.cpp   |  27 +-
 clang/test/SemaTemplate/temp_arg_nontype.cpp  |  45 ++-
 clang/test/SemaTemplate/temp_arg_template.cpp |  38 +-
 .../SemaTemplate/temp_arg_template_p0522.cpp  |  70 ++--
 .../Templight/templight-empty-entries-fix.cpp |  12 +
 .../templight-prior-template-arg.cpp  |  33 +-
 .../type_traits/is_specialization.verify.cpp  |   8 +-
 18 files changed, 504 insertions(+), 281 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7112d1f889fef..abe535f55fb2a 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -176,6 +176,8 @@ C++17 Feature Support
   the values produced by GCC, so these macros should not be used from header
   files because they may not be stable across multiple TUs (the values may vary
   based on compiler version as well as CPU tuning). #GH60174
+- The implementation of the relaxed template template argument matching rules 
is
+  more complete and reliable, and should provide more accurate diagnostics.
 
 C++14 Feature Support
 ^
@@ -589,6 +591,10 @@ Improvements to Clang's diagnostics
 - Clang no longer emits a "declared here" note for a builtin function that has 
no declaration in source.
   Fixes #GH93369.
 
+- Clang now properly explains the reason a template template argument failed to
+  match a template template parameter, in terms of the C++17 relaxed matching 
rules
+  instead of the old ones.
+
 Improvements to Clang's time-trace
 --
 
@@ -887,7 +893,8 @@ Bug Fixes to C++ Support
   between the addresses of two labels (a GNU extension) to a pointer within a 
constant expression. (#GH95366).
 - Fix immediate escalation bugs in the presence of dependent call arguments. 
(#GH94935)
 - Clang now diagnoses explicit specializations with storage class specifiers 
in all contexts.
-
+- Fixes to several issues in partial ordering of template template parameters, 
which
+  were documented in the test suite

[llvm-branch-commits] [clang] [libcxx] [clang] Finish implementation of P0522 (PR #96023)

2024-06-21 Thread Matheus Izvekov via llvm-branch-commits

mizvekov wrote:

@ldionne I had to adjust the libcxx expectation change.

The simple regex won't work, as the error diagnostic is now produced in 
different source locations.

I have changed it so it uses a preprocessor conditional, but that new solution 
will still break if libcxx-CI is using an outdated trunk clang.

Let me know if you have a better idea.

https://github.com/llvm/llvm-project/pull/96023
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang-tools-extra] [clang] Implement CWG2398 provisional TTP matching to class templates (PR #94981)

2024-07-29 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov edited 
https://github.com/llvm/llvm-project/pull/94981
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang-tools-extra] [clang] Implement CWG2398 provisional TTP matching to class templates (PR #94981)

2024-07-29 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov edited 
https://github.com/llvm/llvm-project/pull/94981
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [libcxx] [clang] Finish implementation of P0522 (PR #96023)

2024-07-30 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/96023

>From 4fb1c50098372d6b2f1bc50948ffdf56e1a9efff Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Mon, 17 Jun 2024 21:39:08 -0300
Subject: [PATCH] [clang] Finish implementation of P0522

This finishes the clang implementation of P0522, getting rid
of the fallback to the old, pre-P0522 rules.

Before this patch, when partial ordering template template parameters,
we would perform, in order:
* If the old rules would match, we would accept it. Otherwise, don't
  generate diagnostics yet.
* If the new rules would match, just accept it. Otherwise, don't
  generate any diagnostics yet again.
* Apply the old rules again, this time with diagnostics.

This situation was far from ideal, as we would sometimes:
* Accept some things we shouldn't.
* Reject some things we shouldn't.
* Only diagnose rejection in terms of the old rules.

With this patch, we apply the P0522 rules throughout.

This needed to extend template argument deduction in order
to accept the historial rule for TTP matching pack parameter to non-pack
arguments.
This change also makes us accept some combinations of historical and P0522
allowances we wouldn't before.

It also fixes a bunch of bugs that were documented in the test suite,
which I am not sure there are issues already created for them.

This causes a lot of changes to the way these failures are diagnosed,
with related test suite churn.

The problem here is that the old rules were very simple and
non-recursive, making it easy to provide customized diagnostics,
and to keep them consistent with each other.

The new rules are a lot more complex and rely on template argument
deduction, substitutions, and they are recursive.

The approach taken here is to mostly rely on existing diagnostics,
and create a new instantiation context that keeps track of this context.

So for example when a substitution failure occurs, we use the error
produced there unmodified, and just attach notes to it explaining
that it occurred in the context of partial ordering this template
argument against that template parameter.

This diverges from the old diagnostics, which would lead with an
error pointing to the template argument, explain the problem
in subsequent notes, and produce a final note pointing to the parameter.
---
 clang/docs/ReleaseNotes.rst   |   8 +
 .../clang/Basic/DiagnosticSemaKinds.td|   7 +
 clang/include/clang/Sema/Sema.h   |  14 +-
 clang/lib/Frontend/FrontendActions.cpp|   2 +
 clang/lib/Sema/SemaTemplate.cpp   |  94 ++---
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 352 +-
 clang/lib/Sema/SemaTemplateInstantiate.cpp|  15 +
 .../temp/temp.arg/temp.arg.template/p3-0x.cpp |  31 +-
 clang/test/CXX/temp/temp.param/p12.cpp|  21 +-
 clang/test/Modules/cxx-templates.cpp  |  15 +-
 clang/test/SemaCXX/make_integer_seq.cpp   |   5 +-
 clang/test/SemaTemplate/cwg2398.cpp   |  19 +-
 clang/test/SemaTemplate/temp_arg_nontype.cpp  |  46 ++-
 clang/test/SemaTemplate/temp_arg_template.cpp |  38 +-
 .../SemaTemplate/temp_arg_template_p0522.cpp  |  70 ++--
 .../Templight/templight-empty-entries-fix.cpp |  12 +
 .../templight-prior-template-arg.cpp  |  33 +-
 .../type_traits/is_specialization.verify.cpp  |   8 +-
 18 files changed, 516 insertions(+), 274 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 903461532940c..043604b3e5195 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -67,6 +67,8 @@ C++ Language Changes
 
 C++17 Feature Support
 ^
+- The implementation of the relaxed template template argument matching rules 
is
+  more complete and reliable, and should provide more accurate diagnostics.
 
 C++14 Feature Support
 ^
@@ -133,6 +135,10 @@ Improvements to Clang's diagnostics
 
 - Clang now diagnoses undefined behavior in constant expressions more 
consistently. This includes invalid shifts, and signed overflow in arithmetic.
 
+- Clang now properly explains the reason a template template argument failed to
+  match a template template parameter, in terms of the C++17 relaxed matching 
rules
+  instead of the old ones.
+
 Improvements to Clang's time-trace
 --
 
@@ -158,6 +164,8 @@ Bug Fixes to C++ Support
 - Fixed a failed assertion when checking invalid delete operator declaration. 
(#GH96191)
 - When performing partial ordering of function templates, clang now checks that
   the deduction was consistent. Fixes (#GH18291).
+- Fixes to several issues in partial ordering of template template parameters, 
which
+  were documented in the test suite.
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 810abe4f23e31..bb7bba73d1964 100644
--- a/clang/in

[llvm-branch-commits] [clang] [libcxx] [clang] Finish implementation of P0522 (PR #96023)

2024-07-31 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/96023

>From 7e9832053a2dab0cae464a087f61378c8f3ab509 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Mon, 17 Jun 2024 21:39:08 -0300
Subject: [PATCH] [clang] Finish implementation of P0522

This finishes the clang implementation of P0522, getting rid
of the fallback to the old, pre-P0522 rules.

Before this patch, when partial ordering template template parameters,
we would perform, in order:
* If the old rules would match, we would accept it. Otherwise, don't
  generate diagnostics yet.
* If the new rules would match, just accept it. Otherwise, don't
  generate any diagnostics yet again.
* Apply the old rules again, this time with diagnostics.

This situation was far from ideal, as we would sometimes:
* Accept some things we shouldn't.
* Reject some things we shouldn't.
* Only diagnose rejection in terms of the old rules.

With this patch, we apply the P0522 rules throughout.

This needed to extend template argument deduction in order
to accept the historial rule for TTP matching pack parameter to non-pack
arguments.
This change also makes us accept some combinations of historical and P0522
allowances we wouldn't before.

It also fixes a bunch of bugs that were documented in the test suite,
which I am not sure there are issues already created for them.

This causes a lot of changes to the way these failures are diagnosed,
with related test suite churn.

The problem here is that the old rules were very simple and
non-recursive, making it easy to provide customized diagnostics,
and to keep them consistent with each other.

The new rules are a lot more complex and rely on template argument
deduction, substitutions, and they are recursive.

The approach taken here is to mostly rely on existing diagnostics,
and create a new instantiation context that keeps track of this context.

So for example when a substitution failure occurs, we use the error
produced there unmodified, and just attach notes to it explaining
that it occurred in the context of partial ordering this template
argument against that template parameter.

This diverges from the old diagnostics, which would lead with an
error pointing to the template argument, explain the problem
in subsequent notes, and produce a final note pointing to the parameter.
---
 clang/docs/ReleaseNotes.rst   |   8 +
 .../clang/Basic/DiagnosticSemaKinds.td|   7 +
 clang/include/clang/Sema/Sema.h   |  14 +-
 clang/lib/Frontend/FrontendActions.cpp|   2 +
 clang/lib/Sema/SemaTemplate.cpp   |  94 ++---
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 353 +-
 clang/lib/Sema/SemaTemplateInstantiate.cpp|  15 +
 .../temp/temp.arg/temp.arg.template/p3-0x.cpp |  31 +-
 clang/test/CXX/temp/temp.param/p12.cpp|  21 +-
 clang/test/Modules/cxx-templates.cpp  |  15 +-
 clang/test/SemaCXX/make_integer_seq.cpp   |   5 +-
 clang/test/SemaTemplate/cwg2398.cpp   |  19 +-
 clang/test/SemaTemplate/temp_arg_nontype.cpp  |  46 ++-
 clang/test/SemaTemplate/temp_arg_template.cpp |  38 +-
 .../SemaTemplate/temp_arg_template_p0522.cpp  |  70 ++--
 .../Templight/templight-empty-entries-fix.cpp |  12 +
 .../templight-prior-template-arg.cpp  |  33 +-
 .../type_traits/is_specialization.verify.cpp  |   2 +-
 18 files changed, 512 insertions(+), 273 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 903461532940c..043604b3e5195 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -67,6 +67,8 @@ C++ Language Changes
 
 C++17 Feature Support
 ^
+- The implementation of the relaxed template template argument matching rules 
is
+  more complete and reliable, and should provide more accurate diagnostics.
 
 C++14 Feature Support
 ^
@@ -133,6 +135,10 @@ Improvements to Clang's diagnostics
 
 - Clang now diagnoses undefined behavior in constant expressions more 
consistently. This includes invalid shifts, and signed overflow in arithmetic.
 
+- Clang now properly explains the reason a template template argument failed to
+  match a template template parameter, in terms of the C++17 relaxed matching 
rules
+  instead of the old ones.
+
 Improvements to Clang's time-trace
 --
 
@@ -158,6 +164,8 @@ Bug Fixes to C++ Support
 - Fixed a failed assertion when checking invalid delete operator declaration. 
(#GH96191)
 - When performing partial ordering of function templates, clang now checks that
   the deduction was consistent. Fixes (#GH18291).
+- Fixes to several issues in partial ordering of template template parameters, 
which
+  were documented in the test suite.
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 810abe4f23e31..bb7bba73d1964 100644
--- a/clang/in

[llvm-branch-commits] [clang] [libcxx] [clang] Finish implementation of P0522 (PR #96023)

2024-07-31 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/96023

>From be948d566e5e7cd1932d3c81c5500ae83f085f7a Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Mon, 17 Jun 2024 21:39:08 -0300
Subject: [PATCH] [clang] Finish implementation of P0522

This finishes the clang implementation of P0522, getting rid
of the fallback to the old, pre-P0522 rules.

Before this patch, when partial ordering template template parameters,
we would perform, in order:
* If the old rules would match, we would accept it. Otherwise, don't
  generate diagnostics yet.
* If the new rules would match, just accept it. Otherwise, don't
  generate any diagnostics yet again.
* Apply the old rules again, this time with diagnostics.

This situation was far from ideal, as we would sometimes:
* Accept some things we shouldn't.
* Reject some things we shouldn't.
* Only diagnose rejection in terms of the old rules.

With this patch, we apply the P0522 rules throughout.

This needed to extend template argument deduction in order
to accept the historial rule for TTP matching pack parameter to non-pack
arguments.
This change also makes us accept some combinations of historical and P0522
allowances we wouldn't before.

It also fixes a bunch of bugs that were documented in the test suite,
which I am not sure there are issues already created for them.

This causes a lot of changes to the way these failures are diagnosed,
with related test suite churn.

The problem here is that the old rules were very simple and
non-recursive, making it easy to provide customized diagnostics,
and to keep them consistent with each other.

The new rules are a lot more complex and rely on template argument
deduction, substitutions, and they are recursive.

The approach taken here is to mostly rely on existing diagnostics,
and create a new instantiation context that keeps track of this context.

So for example when a substitution failure occurs, we use the error
produced there unmodified, and just attach notes to it explaining
that it occurred in the context of partial ordering this template
argument against that template parameter.

This diverges from the old diagnostics, which would lead with an
error pointing to the template argument, explain the problem
in subsequent notes, and produce a final note pointing to the parameter.
---
 clang/docs/ReleaseNotes.rst   |   8 +
 .../clang/Basic/DiagnosticSemaKinds.td|   7 +
 clang/include/clang/Sema/Sema.h   |  14 +-
 clang/lib/Frontend/FrontendActions.cpp|   2 +
 clang/lib/Sema/SemaTemplate.cpp   |  94 ++---
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 353 +-
 clang/lib/Sema/SemaTemplateInstantiate.cpp|  15 +
 .../temp/temp.arg/temp.arg.template/p3-0x.cpp |  31 +-
 clang/test/CXX/temp/temp.param/p12.cpp|  21 +-
 clang/test/Modules/cxx-templates.cpp  |  15 +-
 clang/test/SemaCXX/make_integer_seq.cpp   |   5 +-
 clang/test/SemaTemplate/cwg2398.cpp   | 139 ++-
 clang/test/SemaTemplate/temp_arg_nontype.cpp  |  46 ++-
 clang/test/SemaTemplate/temp_arg_template.cpp |  38 +-
 .../SemaTemplate/temp_arg_template_p0522.cpp  |  70 ++--
 .../Templight/templight-empty-entries-fix.cpp |  12 +
 .../templight-prior-template-arg.cpp  |  33 +-
 .../type_traits/is_specialization.verify.cpp  |   2 +-
 18 files changed, 632 insertions(+), 273 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 903461532940c..043604b3e5195 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -67,6 +67,8 @@ C++ Language Changes
 
 C++17 Feature Support
 ^
+- The implementation of the relaxed template template argument matching rules 
is
+  more complete and reliable, and should provide more accurate diagnostics.
 
 C++14 Feature Support
 ^
@@ -133,6 +135,10 @@ Improvements to Clang's diagnostics
 
 - Clang now diagnoses undefined behavior in constant expressions more 
consistently. This includes invalid shifts, and signed overflow in arithmetic.
 
+- Clang now properly explains the reason a template template argument failed to
+  match a template template parameter, in terms of the C++17 relaxed matching 
rules
+  instead of the old ones.
+
 Improvements to Clang's time-trace
 --
 
@@ -158,6 +164,8 @@ Bug Fixes to C++ Support
 - Fixed a failed assertion when checking invalid delete operator declaration. 
(#GH96191)
 - When performing partial ordering of function templates, clang now checks that
   the deduction was consistent. Fixes (#GH18291).
+- Fixes to several issues in partial ordering of template template parameters, 
which
+  were documented in the test suite.
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 810abe4f23e31..bb7bba73d1964 100644
--- a/cla

[llvm-branch-commits] [clang] [clang] remove unneeded template deduction canonicalizations (PR #101594)

2024-08-02 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov edited 
https://github.com/llvm/llvm-project/pull/101594
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] remove unneeded template deduction canonicalizations (PR #101594)

2024-08-02 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/101594

>From 86c6801ad60e867ab95051eb6e279a97aeefa4ce Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Thu, 1 Aug 2024 19:18:52 -0300
Subject: [PATCH] [clang] remove unneeded template deduction canonicalizations

This is mostly a cleanups patch, with some hard to observe
sugar preservation improvements.

Except for the function template deduction changes
which improve some pre-existing diagnostics a little bit.
---
 clang/lib/Sema/SemaTemplate.cpp   |  4 +-
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 86 +++
 .../cxx1y-generic-lambdas-variadics.cpp   |  8 +-
 clang/test/SemaCXX/cxx1y-generic-lambdas.cpp  |  4 +-
 4 files changed, 39 insertions(+), 63 deletions(-)

diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index c22e329bef2b9..cb16e8caa9a8a 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -4202,7 +4202,7 @@ Sema::CheckVarTemplateId(VarTemplateDecl *Template, 
SourceLocation TemplateLoc,
 TemplateDeductionInfo Info(FailedCandidates.getLocation());
 
 if (TemplateDeductionResult Result =
-DeduceTemplateArguments(Partial, CanonicalConverted, Info);
+DeduceTemplateArguments(Partial, SugaredConverted, Info);
 Result != TemplateDeductionResult::Success) {
   // Store the failed-deduction information for use in diagnostics, later.
   // TODO: Actually use the failed-deduction info?
@@ -4213,7 +4213,7 @@ Sema::CheckVarTemplateId(VarTemplateDecl *Template, 
SourceLocation TemplateLoc,
 } else {
   Matched.push_back(PartialSpecMatchResult());
   Matched.back().Partial = Partial;
-  Matched.back().Args = Info.takeCanonical();
+  Matched.back().Args = Info.takeSugared();
 }
   }
 
diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index db7f233dcef73..eeeb780299e78 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -503,7 +503,6 @@ static TemplateDeductionResult 
DeduceNonTypeTemplateArgument(
 const NonTypeTemplateParmDecl *NTTP, ValueDecl *D, QualType T,
 TemplateDeductionInfo &Info,
 SmallVectorImpl &Deduced) {
-  D = D ? cast(D->getCanonicalDecl()) : nullptr;
   TemplateArgument New(D, T);
   return DeduceNonTypeTemplateArgument(
   S, TemplateParams, NTTP, DeducedTemplateArgument(New), T, Info, Deduced);
@@ -1380,11 +1379,6 @@ static bool isForwardingReference(QualType Param, 
unsigned FirstInnerIndex) {
   return false;
 }
 
-static CXXRecordDecl *getCanonicalRD(QualType T) {
-  return cast(
-  T->castAs()->getDecl()->getCanonicalDecl());
-}
-
 ///  Attempt to deduce the template arguments by checking the base types
 ///  according to (C++20 [temp.deduct.call] p4b3.
 ///
@@ -1439,7 +1433,7 @@ DeduceTemplateBases(Sema &S, const CXXRecordDecl *RD,
 for (const auto &Base : RD->bases()) {
   QualType T = Base.getType();
   assert(T->isRecordType() && "Base class that isn't a record?");
-  if (Visited.insert(::getCanonicalRD(T)).second)
+  if (Visited.insert(T->getAsCXXRecordDecl()).second)
 ToVisit.push_back(T);
 }
   };
@@ -1460,7 +1454,7 @@ DeduceTemplateBases(Sema &S, const CXXRecordDecl *RD,
 
 // If this was a successful deduction, add it to the list of matches,
 // otherwise we need to continue searching its bases.
-const CXXRecordDecl *RD = ::getCanonicalRD(NextT);
+const CXXRecordDecl *RD = NextT->getAsCXXRecordDecl();
 if (BaseResult == TemplateDeductionResult::Success)
   Matches.insert({RD, DeducedCopy});
 else
@@ -1481,7 +1475,7 @@ DeduceTemplateBases(Sema &S, const CXXRecordDecl *RD,
 // We can give up once we have a single item (or have run out of things to
 // search) since cyclical inheritance isn't valid.
 while (Matches.size() > 1 && !ToVisit.empty()) {
-  const CXXRecordDecl *RD = ::getCanonicalRD(ToVisit.pop_back_val());
+  const CXXRecordDecl *RD = ToVisit.pop_back_val()->getAsCXXRecordDecl();
   Matches.erase(RD);
 
   // Always add all bases, since the inheritance tree can contain
@@ -2030,15 +2024,16 @@ static TemplateDeductionResult 
DeduceTemplateArgumentsByTypeMatch(
   if (!S.isCompleteType(Info.getLocation(), A))
 return Result;
 
-  if (getCanonicalRD(A)->isInvalidDecl())
+  const CXXRecordDecl *RD = A->getAsCXXRecordDecl();
+  if (RD->isInvalidDecl())
 return Result;
 
   // Reset the incorrectly deduced argument from above.
   Deduced = DeducedOrig;
 
   // Check bases according to C++14 [temp.deduct.call] p4b3:
-  auto BaseResult = DeduceTemplateBases(S, getCanonicalRD(A),
-TemplateParams, P, Info, Deduced);
+  auto BaseResult =
+  DeduceTemplateBases(S, RD, TemplateParams, P, Info, Deduced);
   return BaseResul

[llvm-branch-commits] [clang] [libcxx] [clang] Reland: Instantiate concepts with sugared template arguments (PR #101782)

2024-08-02 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/101782

Since we don't unique specializations for concepts, we can just instantiate 
them with the sugared template arguments, at negligible cost.

If we don't track their specializations, we can't resugar them later anyway, 
and that would be more expensive than just instantiating them sugared in the 
first place since it would require an additional pass.

This was a previously reverted patch due to a performance regression, which was 
very simple to fix, as we were only missing the canonicalizations for the key 
to the satisfcation cache.

Fixes #59271

Differential Revision: https://reviews.llvm.org/D136566

>From d566dbe3b037c153994cb073a46aa283e333cca5 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Sun, 23 Oct 2022 11:37:20 +0200
Subject: [PATCH] [clang] Reland: Instantiate concepts with sugared template
 arguments

Since we don't unique specializations for concepts, we can just instantiate
them with the sugared template arguments, at negligible cost.

If we don't track their specializations, we can't resugar them later
anyway, and that would be more expensive than just instantiating them
sugared in the first place since it would require an additional pass.

This was a previously reverted patch due to a performance regression,
which was very simple to fix, as we were only missing the
canonicalizations for the key to the satisfcation cache.

Fixes #59271

Differential Revision: https://reviews.llvm.org/D136566
---
 clang/docs/ReleaseNotes.rst  |  1 +
 clang/include/clang/Sema/Template.h  |  6 +++---
 clang/lib/Sema/SemaConcept.cpp   | 11 +++
 clang/lib/Sema/SemaExprCXX.cpp   |  5 ++---
 clang/lib/Sema/SemaTemplate.cpp  | 10 +-
 clang/lib/Sema/SemaTemplateDeduction.cpp | 16 
 clang/lib/Serialization/ASTReaderDecl.cpp|  2 +-
 clang/test/AST/ast-dump-concepts.cpp | 10 ++
 .../expr.prim.req/compound-requirement.cpp   | 10 +-
 .../expr.prim.req/nested-requirement.cpp |  2 +-
 .../expr.prim.req/simple-requirement.cpp |  4 ++--
 .../expr.prim/expr.prim.req/type-requirement.cpp | 12 ++--
 .../temp/temp.constr/temp.constr.normal/p1.cpp   |  2 +-
 clang/test/CXX/temp/temp.param/p10-2a.cpp|  4 ++--
 .../SemaTemplate/concepts-recursive-inst.cpp | 12 ++--
 clang/test/SemaTemplate/concepts.cpp |  4 ++--
 .../SemaTemplate/instantiate-requires-expr.cpp   | 16 +---
 clang/test/SemaTemplate/pr52970.cpp  |  2 +-
 .../cpp17_iterator_concepts.verify.cpp   |  2 +-
 19 files changed, 73 insertions(+), 58 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 34aa4c73796ed..0889410476d53 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -144,6 +144,7 @@ Improvements to Clang's diagnostics
 - Clang now diagnoses undefined behavior in constant expressions more 
consistently. This includes invalid shifts, and signed overflow in arithmetic.
 
 - -Wdangling-assignment-gsl is enabled by default.
+- Clang now does a better job preserving the type as written when specializing 
concepts.
 
 Improvements to Clang's time-trace
 --
diff --git a/clang/include/clang/Sema/Template.h 
b/clang/include/clang/Sema/Template.h
index 0340c23fd170d..d616865afe807 100644
--- a/clang/include/clang/Sema/Template.h
+++ b/clang/include/clang/Sema/Template.h
@@ -234,7 +234,8 @@ enum class TemplateSubstitutionKind : char {
 /// Replaces the current 'innermost' level with the provided argument list.
 /// This is useful for type deduction cases where we need to get the entire
 /// list from the AST, but then add the deduced innermost list.
-void replaceInnermostTemplateArguments(Decl *AssociatedDecl, ArgList Args) 
{
+void replaceInnermostTemplateArguments(Decl *AssociatedDecl, ArgList Args,
+   bool Final = false) {
   assert((!TemplateArgumentLists.empty() || NumRetainedOuterLevels) &&
  "Replacing in an empty list?");
 
@@ -246,8 +247,7 @@ enum class TemplateSubstitutionKind : char {
 TemplateArgumentLists[0].Args = Args;
   } else {
 --NumRetainedOuterLevels;
-TemplateArgumentLists.push_back(
-{{AssociatedDecl, /*Final=*/false}, Args});
+TemplateArgumentLists.push_back({{AssociatedDecl, Final}, Args});
   }
 }
 
diff --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index 7d7a94e9fd637..75ccefa2a487e 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -414,7 +414,8 @@ DiagRecursiveConstraintEval(Sema &S, llvm::FoldingSetNodeID 
&ID,
   E->Profile(ID, S.Context, /*Canonical=*/true);
   for (const auto &List : MLTAL)
 for (const auto &TemplateArg

[llvm-branch-commits] [clang] [libcxx] [clang] Reland: Instantiate concepts with sugared template arguments (PR #101782)

2024-08-02 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/101782

>From 9919bb4550f266375be19ce2af46735fb451ff86 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Sun, 23 Oct 2022 11:37:20 +0200
Subject: [PATCH] [clang] Reland: Instantiate concepts with sugared template
 arguments

Since we don't unique specializations for concepts, we can just instantiate
them with the sugared template arguments, at negligible cost.

If we don't track their specializations, we can't resugar them later
anyway, and that would be more expensive than just instantiating them
sugared in the first place since it would require an additional pass.

This was a previously reverted patch due to a performance regression,
which was very simple to fix, as we were only missing the
canonicalizations for the key to the satisfcation cache.

Fixes #59271

Differential Revision: https://reviews.llvm.org/D136566
---
 clang/docs/ReleaseNotes.rst  |  1 +
 clang/include/clang/Sema/Template.h  |  6 +++---
 clang/lib/Sema/SemaConcept.cpp   | 11 +++
 clang/lib/Sema/SemaExprCXX.cpp   |  5 ++---
 clang/lib/Sema/SemaTemplate.cpp  | 10 +-
 clang/lib/Sema/SemaTemplateDeduction.cpp | 16 
 clang/lib/Serialization/ASTReaderDecl.cpp|  2 +-
 clang/test/AST/ast-dump-concepts.cpp | 10 ++
 .../expr.prim.req/compound-requirement.cpp   | 10 +-
 .../expr.prim.req/nested-requirement.cpp |  2 +-
 .../expr.prim.req/simple-requirement.cpp |  4 ++--
 .../expr.prim/expr.prim.req/type-requirement.cpp | 12 ++--
 .../temp/temp.constr/temp.constr.normal/p1.cpp   |  2 +-
 clang/test/CXX/temp/temp.param/p10-2a.cpp|  4 ++--
 .../SemaTemplate/concepts-recursive-inst.cpp | 12 ++--
 clang/test/SemaTemplate/concepts.cpp |  4 ++--
 .../SemaTemplate/instantiate-requires-expr.cpp   | 16 +---
 clang/test/SemaTemplate/pr52970.cpp  |  2 +-
 .../cpp17_iterator_concepts.verify.cpp   |  2 +-
 19 files changed, 73 insertions(+), 58 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 34aa4c73796ed..3ceaf54d6ce2e 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -144,6 +144,7 @@ Improvements to Clang's diagnostics
 - Clang now diagnoses undefined behavior in constant expressions more 
consistently. This includes invalid shifts, and signed overflow in arithmetic.
 
 - -Wdangling-assignment-gsl is enabled by default.
+- Clang now does a better job preserving the template arguments as written 
when specializing concepts.
 
 Improvements to Clang's time-trace
 --
diff --git a/clang/include/clang/Sema/Template.h 
b/clang/include/clang/Sema/Template.h
index 0340c23fd170d..d616865afe807 100644
--- a/clang/include/clang/Sema/Template.h
+++ b/clang/include/clang/Sema/Template.h
@@ -234,7 +234,8 @@ enum class TemplateSubstitutionKind : char {
 /// Replaces the current 'innermost' level with the provided argument list.
 /// This is useful for type deduction cases where we need to get the entire
 /// list from the AST, but then add the deduced innermost list.
-void replaceInnermostTemplateArguments(Decl *AssociatedDecl, ArgList Args) 
{
+void replaceInnermostTemplateArguments(Decl *AssociatedDecl, ArgList Args,
+   bool Final = false) {
   assert((!TemplateArgumentLists.empty() || NumRetainedOuterLevels) &&
  "Replacing in an empty list?");
 
@@ -246,8 +247,7 @@ enum class TemplateSubstitutionKind : char {
 TemplateArgumentLists[0].Args = Args;
   } else {
 --NumRetainedOuterLevels;
-TemplateArgumentLists.push_back(
-{{AssociatedDecl, /*Final=*/false}, Args});
+TemplateArgumentLists.push_back({{AssociatedDecl, Final}, Args});
   }
 }
 
diff --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index 7d7a94e9fd637..75ccefa2a487e 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -414,7 +414,8 @@ DiagRecursiveConstraintEval(Sema &S, llvm::FoldingSetNodeID 
&ID,
   E->Profile(ID, S.Context, /*Canonical=*/true);
   for (const auto &List : MLTAL)
 for (const auto &TemplateArg : List.Args)
-  TemplateArg.Profile(ID, S.Context);
+  S.Context.getCanonicalTemplateArgument(TemplateArg)
+  .Profile(ID, S.Context);
 
   // Note that we have to do this with our own collection, because there are
   // times where a constraint-expression check can cause us to need to evaluate
@@ -638,8 +639,8 @@ bool Sema::CheckConstraintSatisfaction(
   // here.
   llvm::SmallVector FlattenedArgs;
   for (auto List : TemplateArgsLists)
-FlattenedArgs.insert(FlattenedArgs.end(), List.Args.begin(),
- List.Args.end());
+for (const TemplateArg

[llvm-branch-commits] [clang] [clang-tools-extra] [lldb] [clang] Reland: Instantiate alias templates with sugar (PR #101858)

2024-08-03 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/101858

This makes use of the changes introduced in D134604, in order to instantiate 
alias templates witn a final sugared substitution.

This comes at no additional relevant cost.
Since we don't track / unique them in specializations, we wouldn't be able to 
resugar them later anyway.

Differential Revision: https://reviews.llvm.org/D136565

>From 4615439837bfcc78fc611e6f8e1aca2d02ac3aa6 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Sun, 23 Oct 2022 16:57:12 +0200
Subject: [PATCH] [clang] Reland: Instantiate alias templates with sugar

This makes use of the changes introduced in D134604, in order to
instantiate alias templates witn a final sugared substitution.

This comes at no additional relevant cost.
Since we don't track / unique them in specializations, we wouldn't be
able to resugar them later anyway.

Differential Revision: https://reviews.llvm.org/D136565
---
 .../clangd/unittests/HoverTests.cpp   |  2 +-
 .../unused-local-non-trivial-variable.cpp |  2 +-
 clang/lib/Sema/SemaTemplate.cpp   |  4 +-
 clang/test/AST/ast-dump-template-decls.cpp| 35 +++---
 clang/test/CXX/temp/temp.deduct.guide/p3.cpp  |  2 +-
 .../test/Misc/diag-template-diffing-cxx11.cpp | 21 +++---
 clang/test/SemaCXX/nullability.cpp|  4 +-
 clang/test/SemaCXX/sizeless-1.cpp |  2 +-
 .../SemaHLSL/VectorOverloadResolution.hlsl| 10 +--
 clang/test/SemaTemplate/deduction-guide.cpp   | 70 +--
 clang/test/SemaTemplate/make_integer_seq.cpp  |  8 +--
 clang/test/SemaTemplate/temp_arg_nontype.cpp  |  2 +-
 .../shared_ptr/TestSharedPtrFromStdModule.py  |  6 +-
 .../TestDbgInfoContentWeakPtrFromStdModule.py |  2 +-
 .../weak_ptr/TestWeakPtrFromStdModule.py  |  6 +-
 15 files changed, 75 insertions(+), 101 deletions(-)

diff --git a/clang-tools-extra/clangd/unittests/HoverTests.cpp 
b/clang-tools-extra/clangd/unittests/HoverTests.cpp
index 8d6d4223d7260..69f6df46c87ce 100644
--- a/clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ b/clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -1325,7 +1325,7 @@ class Foo final {})cpp";
  HI.LocalScope = "";
  HI.Kind = index::SymbolKind::TypeAlias;
  HI.Definition = "template  using AA = A";
- HI.Type = {"A", "type-parameter-0-0"}; // FIXME: should be 'T'
+ HI.Type = {"A", "T"};
  HI.TemplateParameters = {
  {{"typename"}, std::string("T"), std::nullopt}};
}},
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-local-non-trivial-variable.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-local-non-trivial-variable.cpp
index 3fdc24b94a6cb..721c55b1fb538 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-local-non-trivial-variable.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-local-non-trivial-variable.cpp
@@ -76,7 +76,7 @@ T qux(T Generic) {
 async::Future TemplateType;
 // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: unused local variable 
'TemplateType' of type 'async::Future' 
[bugprone-unused-local-non-trivial-variable]
 a::Future AliasTemplateType;
-// CHECK-MESSAGES: :[[@LINE-1]]:18: warning: unused local variable 
'AliasTemplateType' of type 'a::Future' (aka 'Future') 
[bugprone-unused-local-non-trivial-variable]
+// CHECK-MESSAGES: :[[@LINE-1]]:18: warning: unused local variable 
'AliasTemplateType' of type 'a::Future' (aka 'Future') 
[bugprone-unused-local-non-trivial-variable]
 [[maybe_unused]] async::Future MaybeUnused;
 return Generic;
 }
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 720862ec0bffa..1346a4a3f0012 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -3334,8 +3334,8 @@ QualType Sema::CheckTemplateIdType(TemplateName Name,
 
 // Only substitute for the innermost template argument list.
 MultiLevelTemplateArgumentList TemplateArgLists;
-TemplateArgLists.addOuterTemplateArguments(Template, CanonicalConverted,
-   /*Final=*/false);
+TemplateArgLists.addOuterTemplateArguments(Template, SugaredConverted,
+   /*Final=*/true);
 TemplateArgLists.addOuterRetainedLevels(
 AliasTemplate->getTemplateParameters()->getDepth());
 
diff --git a/clang/test/AST/ast-dump-template-decls.cpp 
b/clang/test/AST/ast-dump-template-decls.cpp
index f0a6204ce3cfa..9f578e5afe561 100644
--- a/clang/test/AST/ast-dump-template-decls.cpp
+++ b/clang/test/AST/ast-dump-template-decls.cpp
@@ -123,8 +123,6 @@ using type2 = typename C::type1;
 // CHECK-NEXT: TemplateArgument type 'void'
 // CHECK-NEXT: BuiltinType 0x{{[^ ]*}} 'void'
 // CHECK-NEXT: FunctionProtoType 0x{{[^ ]*}} 'void (int)' cdecl
-// CHECK-NEXT: SubstTemplateTypeParmType 0x{{[^ ]*}} 'void' sugar class depth 
0 index 0 U
-//

[llvm-branch-commits] [clang] [clang-tools-extra] [lldb] [clang] Reland: Instantiate alias templates with sugar (PR #101858)

2024-08-03 Thread Matheus Izvekov via llvm-branch-commits

mizvekov wrote:

@alexfh I can't observe anymore the performance regression you reported on the 
original phab DR (q2.cc test case).

The original reduction doesn't compile anymore starting from clang-18, so I 
took the same base test and applied it to current libc++, but the memory usage 
and wall time are pretty close.

Let me know if you have an additional test case.

https://github.com/llvm/llvm-project/pull/101858
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] CTAD alias: fix the transformation for the require-clause expr (PR #90961)

2024-05-03 Thread Matheus Izvekov via llvm-branch-commits


@@ -2744,31 +2744,155 @@ bool hasDeclaredDeductionGuides(DeclarationName Name, 
DeclContext *DC) {
   return false;
 }
 
+unsigned getTemplateDepth(NamedDecl *TemplateParam) {

mizvekov wrote:

I think this is potentially misleading, as we already have multiple unrelated 
`getTemplateDepth`, see `Sema.h` / `SemaTemplate.cpp`, `DeclBase.h`, `Expr.h`.

https://github.com/llvm/llvm-project/pull/90961
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] CTAD alias: fix the transformation for the require-clause expr (PR #90961)

2024-05-03 Thread Matheus Izvekov via llvm-branch-commits


@@ -2744,31 +2744,155 @@ bool hasDeclaredDeductionGuides(DeclarationName Name, 
DeclContext *DC) {
   return false;
 }
 
+unsigned getTemplateDepth(NamedDecl *TemplateParam) {
+  if (auto *TTP = dyn_cast(TemplateParam))
+return TTP->getDepth();
+  if (auto *TTP = dyn_cast(TemplateParam))
+return TTP->getDepth();
+  if (auto *NTTP = dyn_cast(TemplateParam))
+return NTTP->getDepth();
+  llvm_unreachable("Unhandled template parameter types");
+}
+
 NamedDecl *transformTemplateParameter(Sema &SemaRef, DeclContext *DC,
   NamedDecl *TemplateParam,
   MultiLevelTemplateArgumentList &Args,
-  unsigned NewIndex) {
+  unsigned NewIndex, unsigned NewDepth) {
   if (auto *TTP = dyn_cast(TemplateParam))
-return transformTemplateTypeParam(SemaRef, DC, TTP, Args, TTP->getDepth(),
+return transformTemplateTypeParam(SemaRef, DC, TTP, Args, NewDepth,
   NewIndex);
   if (auto *TTP = dyn_cast(TemplateParam))
 return transformTemplateParam(SemaRef, DC, TTP, Args, NewIndex,
-  TTP->getDepth());
+  NewDepth);
   if (auto *NTTP = dyn_cast(TemplateParam))
 return transformTemplateParam(SemaRef, DC, NTTP, Args, NewIndex,
-  NTTP->getDepth());
+  NewDepth);
   llvm_unreachable("Unhandled template parameter types");
 }
 
-Expr *transformRequireClause(Sema &SemaRef, FunctionTemplateDecl *FTD,
- llvm::ArrayRef TransformedArgs) 
{
-  Expr *RC = FTD->getTemplateParameters()->getRequiresClause();
+// Transform the require-clause of F if any.
+// The return result is expected to be the require-clause for the synthesized
+// alias deduction guide.
+Expr *transformRequireClause(
+Sema &SemaRef, FunctionTemplateDecl *F,
+TypeAliasTemplateDecl *AliasTemplate,
+ArrayRef DeduceResults) {
+  Expr *RC = F->getTemplateParameters()->getRequiresClause();
   if (!RC)
 return nullptr;
+
+  auto &Context = SemaRef.Context;
+  LocalInstantiationScope Scope(SemaRef);
+
+  // In the clang AST, constraint nodes are not instantiated at all unless they
+  // are being evaluated. This means that occurrences of template parameters
+  // in the require-clause expr have subtle differences compared to occurrences
+  // in other places, such as function parameters. When transforming the
+  // require-clause, we must respect these differences, particularly regarding
+  // the 'depth' information:
+  //   1) In the transformed require-clause, occurrences of template parameters
+  //   must use the "uninstantiated" depth;
+  //   2) When substituting on the require-clause expr of the underlying
+  //   deduction guide, we must use the entire set of template argument lists.
+  //
+  // It's important to note that we're performing this transformation on an
+  // *instantiated* AliasTemplate.
+
+  // For 1), if the alias template is nested within a class template, we
+  // calcualte the 'uninstantiated' depth by adding the substitution level 
back.
+  unsigned AdjustDepth = 0;
+  if (auto *PrimaryTemplate = 
AliasTemplate->getInstantiatedFromMemberTemplate())
+AdjustDepth = PrimaryTemplate->getTemplateDepth();
+  
+  // We rebuild all template parameters with the uninstantiated depth, and
+  // build template arguments refer to them.
+  SmallVector AdjustedAliasTemplateArgs;
+
+  for (auto *TP : *AliasTemplate->getTemplateParameters()) {
+// Rebuild any internal references to earlier parameters and reindex
+// as we go.
+MultiLevelTemplateArgumentList Args;
+Args.setKind(TemplateSubstitutionKind::Rewrite);
+Args.addOuterTemplateArguments(AdjustedAliasTemplateArgs);
+NamedDecl *NewParam = transformTemplateParameter(
+SemaRef, AliasTemplate->getDeclContext(), TP, Args,
+/*NewIndex=*/AdjustedAliasTemplateArgs.size(),
+getTemplateDepth(TP) + AdjustDepth);
+
+auto NewTemplateArgument = Context.getCanonicalTemplateArgument(

mizvekov wrote:

Why do we need to canonicalize the argument here?

https://github.com/llvm/llvm-project/pull/90961
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] CTAD alias: fix the transformation for the require-clause expr (PR #90961)

2024-05-03 Thread Matheus Izvekov via llvm-branch-commits


@@ -2744,31 +2744,155 @@ bool hasDeclaredDeductionGuides(DeclarationName Name, 
DeclContext *DC) {
   return false;
 }
 
+unsigned getTemplateDepth(NamedDecl *TemplateParam) {

mizvekov wrote:

```suggestion
unsigned getTemplateParameterDepth(NamedDecl *TemplateParam) {
```

https://github.com/llvm/llvm-project/pull/90961
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] Revert "[clang] Revert default behavior change of P0522R0 implementation (#91811)" (PR #91837)

2024-05-10 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/91837

With blocking issues fixed, re-enable relaxed template template argument 
matching by reverting these commits.

This reverts commit 4198aebc96cb0236fc63e29a92d886e6a2e3fedb. This reverts 
commit 2d5634a4b39d8e5497b6a67caa54049b3cfade8e.

>From 3a4489465d921b1ce98fc4339f491343f466c918 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Sat, 11 May 2024 00:42:27 -0300
Subject: [PATCH] Revert "[clang] Revert default behavior change of P0522R0
 implementation (#91811)"

With blocking issues fixed, re-enable relaxed template template argument 
matching
by reverting these commits.

This reverts commit 4198aebc96cb0236fc63e29a92d886e6a2e3fedb.
This reverts commit 2d5634a4b39d8e5497b6a67caa54049b3cfade8e.
---
 clang/lib/Driver/ToolChains/Clang.cpp  | 14 +++---
 .../Driver/frelaxed-template-template-args.cpp |  6 +++---
 clang/test/Driver/rewrite-legacy-objc.m|  6 +++---
 clang/test/Driver/rewrite-objc.m   |  2 +-
 4 files changed, 14 insertions(+), 14 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index f0cc018b6668f..42feb1650574e 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -7249,15 +7249,15 @@ void Clang::ConstructJob(Compilation &C, const 
JobAction &JA,
   Args.addOptOutFlag(CmdArgs, options::OPT_fassume_unique_vtables,
  options::OPT_fno_assume_unique_vtables);
 
-  // -fno-relaxed-template-template-args is deprecated.
-  if (Arg *A = Args.getLastArg(options::OPT_frelaxed_template_template_args,
-   
options::OPT_fno_relaxed_template_template_args);
-  A &&
-  A->getOption().matches(options::OPT_fno_relaxed_template_template_args))
+  // -frelaxed-template-template-args is deprecated.
+  if (Arg *A =
+  Args.getLastArg(options::OPT_frelaxed_template_template_args,
+  options::OPT_fno_relaxed_template_template_args)) {
 D.Diag(diag::warn_drv_deprecated_arg)
 << A->getAsString(Args) << /*hasReplacement=*/false;
-  else
-CmdArgs.push_back("-fno-relaxed-template-template-args");
+if 
(A->getOption().matches(options::OPT_fno_relaxed_template_template_args))
+  CmdArgs.push_back("-fno-relaxed-template-template-args");
+  }
 
   // -fsized-deallocation is off by default, as it is an ABI-breaking change 
for
   // most platforms.
diff --git a/clang/test/Driver/frelaxed-template-template-args.cpp 
b/clang/test/Driver/frelaxed-template-template-args.cpp
index 136c360276a15..57fc4e3da6e5d 100644
--- a/clang/test/Driver/frelaxed-template-template-args.cpp
+++ b/clang/test/Driver/frelaxed-template-template-args.cpp
@@ -1,7 +1,7 @@
 // RUN: %clang -fsyntax-only -### %s 2>&1 | FileCheck --check-prefix=CHECK-DEF 
%s
-// RUN: %clang -fsyntax-only -frelaxed-template-template-args %s 2>&1 | 
FileCheck --check-prefix=CHECK-ON --allow-empty %s
+// RUN: %clang -fsyntax-only -frelaxed-template-template-args %s 2>&1 | 
FileCheck --check-prefix=CHECK-ON %s
 // RUN: %clang -fsyntax-only -fno-relaxed-template-template-args %s 2>&1 | 
FileCheck --check-prefix=CHECK-OFF %s
 
-// CHECK-DEF: "-cc1"{{.*}} "-fno-relaxed-template-template-args"
-// CHECK-ON-NOT: warning: argument '-frelaxed-template-template-args' is 
deprecated [-Wdeprecated]
+// CHECK-DEF-NOT: "-cc1"{{.*}} "-fno-relaxed-template-template-args"
+// CHECK-ON:  warning: argument '-frelaxed-template-template-args' is 
deprecated [-Wdeprecated]
 // CHECK-OFF: warning: argument '-fno-relaxed-template-template-args' is 
deprecated [-Wdeprecated]
diff --git a/clang/test/Driver/rewrite-legacy-objc.m 
b/clang/test/Driver/rewrite-legacy-objc.m
index d45fb8c405c52..413a7a7a61f05 100644
--- a/clang/test/Driver/rewrite-legacy-objc.m
+++ b/clang/test/Driver/rewrite-legacy-objc.m
@@ -3,11 +3,11 @@
 // TEST0: "-cc1"
 // TEST0: "-rewrite-objc"
 // FIXME: CHECK-NOT is broken somehow, it doesn't work here. Check adjacency 
instead.
-// TEST0: "-stack-protector" "1" "-fblocks" 
"-fencode-extended-block-signature" "-fregister-global-dtors-with-atexit" 
"-fgnuc-version=4.2.1"{{.*}} "-fobjc-runtime=macosx-fragile" 
"-fno-objc-infer-related-result-type" "-fobjc-exceptions" "-fexceptions" 
"-fno-relaxed-template-template-args" "-fmax-type-align=16"
+// TEST0: "-stack-protector" "1" "-fblocks" 
"-fencode-extended-block-signature" "-fregister-global-dtors-with-atexit" 
"-fgnuc-version=4.2.1"{{.*}} "-fobjc-runtime=macosx-fragile" 
"-fno-objc-infer-related-result-type" "-fobjc-exceptions" "-fexceptions" 
"-fmax-type-align=16"
 // TEST0: rewrite-legacy-objc.m"
 // RUN: %clang --target=i386-apple-macosx10.9.0 -rewrite-legacy-objc %s -o - 
-### 2>&1 | \
 // RUN:   FileCheck -check-prefix=TEST1 %s
 // RUN: %clang --target=i386-apple-macosx10.6.0 -rewrite-legacy-objc %s -o - 
-### 2>&1 | \
 // RUN:   FileCheck -check-prefix=TEST2 %s
-// TEST1: "-sta

[llvm-branch-commits] [clang] Revert "[clang] Revert default behavior change of P0522R0 implementation (#91811)" (PR #91837)

2024-05-10 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov edited 
https://github.com/llvm/llvm-project/pull/91837
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang-tools-extra] [clang] NFCI: use TemplateArgumentLoc for type-param DefaultArgument (PR #92854)

2024-05-20 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/92854

This is an enabler for a future patch.

>From 29f6855012c917040a84b5f1bfc3f6652c82f668 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Mon, 20 May 2024 16:30:46 -0300
Subject: [PATCH] [clang] NFCI: use TemplateArgumentLoc for type-param
 DefaultArgument

This is an enabler for a future patch.
---
 .../ForwardingReferenceOverloadCheck.cpp  |  4 +-
 .../bugprone/IncorrectEnableIfCheck.cpp   |  5 +-
 .../modernize/UseConstraintsCheck.cpp |  8 ++-
 clang-tools-extra/clangd/Hover.cpp|  8 ++-
 clang/include/clang/AST/ASTNodeTraverser.h|  2 +-
 clang/include/clang/AST/DeclTemplate.h| 17 ++---
 clang/include/clang/AST/RecursiveASTVisitor.h |  2 +-
 clang/include/clang/Sema/Sema.h   |  4 +-
 clang/lib/AST/ASTContext.cpp  |  3 +-
 clang/lib/AST/ASTImporter.cpp |  6 +-
 clang/lib/AST/DeclPrinter.cpp |  3 +-
 clang/lib/AST/DeclTemplate.cpp| 17 +++--
 clang/lib/AST/JSONNodeDumper.cpp  |  2 +-
 clang/lib/AST/ODRDiagsEmitter.cpp | 12 ++--
 clang/lib/AST/ODRHash.cpp |  2 +-
 clang/lib/AST/TypePrinter.cpp |  4 +-
 clang/lib/ExtractAPI/DeclarationFragments.cpp |  8 +--
 clang/lib/Index/IndexDecl.cpp |  3 +-
 clang/lib/Sema/HLSLExternalSemaSource.cpp | 48 +++--
 clang/lib/Sema/SemaTemplate.cpp   | 69 ++-
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 10 +--
 clang/lib/Sema/SemaTemplateInstantiate.cpp| 11 +--
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  |  9 ++-
 clang/lib/Serialization/ASTReaderDecl.cpp |  3 +-
 clang/lib/Serialization/ASTWriterDecl.cpp |  2 +-
 clang/tools/libclang/CIndex.cpp   |  7 +-
 clang/unittests/AST/ASTImporterTest.cpp   |  2 +-
 27 files changed, 144 insertions(+), 127 deletions(-)

diff --git 
a/clang-tools-extra/clang-tidy/bugprone/ForwardingReferenceOverloadCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/ForwardingReferenceOverloadCheck.cpp
index 36687a8e761e8..c87b3ea7e2616 100644
--- a/clang-tools-extra/clang-tidy/bugprone/ForwardingReferenceOverloadCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/ForwardingReferenceOverloadCheck.cpp
@@ -54,7 +54,9 @@ AST_MATCHER(QualType, isEnableIf) {
 AST_MATCHER_P(TemplateTypeParmDecl, hasDefaultArgument,
   clang::ast_matchers::internal::Matcher, TypeMatcher) {
   return Node.hasDefaultArgument() &&
- TypeMatcher.matches(Node.getDefaultArgument(), Finder, Builder);
+ TypeMatcher.matches(
+ Node.getDefaultArgument().getArgument().getAsType(), Finder,
+ Builder);
 }
 AST_MATCHER(TemplateDecl, hasAssociatedConstraints) {
   return Node.hasAssociatedConstraints();
diff --git a/clang-tools-extra/clang-tidy/bugprone/IncorrectEnableIfCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/IncorrectEnableIfCheck.cpp
index 09aaf3e31d5dd..75f1107904fce 100644
--- a/clang-tools-extra/clang-tidy/bugprone/IncorrectEnableIfCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/IncorrectEnableIfCheck.cpp
@@ -19,10 +19,11 @@ namespace {
 AST_MATCHER_P(TemplateTypeParmDecl, hasUnnamedDefaultArgument,
   ast_matchers::internal::Matcher, InnerMatcher) {
   if (Node.getIdentifier() != nullptr || !Node.hasDefaultArgument() ||
-  Node.getDefaultArgumentInfo() == nullptr)
+  Node.getDefaultArgument().getArgument().isNull())
 return false;
 
-  TypeLoc DefaultArgTypeLoc = Node.getDefaultArgumentInfo()->getTypeLoc();
+  TypeLoc DefaultArgTypeLoc =
+  Node.getDefaultArgument().getTypeSourceInfo()->getTypeLoc();
   return InnerMatcher.matches(DefaultArgTypeLoc, Finder, Builder);
 }
 
diff --git a/clang-tools-extra/clang-tidy/modernize/UseConstraintsCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseConstraintsCheck.cpp
index 7a021fe14436a..ea4d99586c711 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseConstraintsCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseConstraintsCheck.cpp
@@ -177,9 +177,11 @@ matchTrailingTemplateParam(const FunctionTemplateDecl 
*FunctionTemplate) {
   dyn_cast(LastParam)) {
 if (LastTemplateParam->hasDefaultArgument() &&
 LastTemplateParam->getIdentifier() == nullptr) {
-  return {matchEnableIfSpecialization(
-  LastTemplateParam->getDefaultArgumentInfo()->getTypeLoc()),
-  LastTemplateParam};
+  return {
+  matchEnableIfSpecialization(LastTemplateParam->getDefaultArgument()
+  .getTypeSourceInfo()
+  ->getTypeLoc()),
+  LastTemplateParam};
 }
   }
   return {};
diff --git a/clang-tools-extra/clangd/Hover.cpp 
b/clang-tools-extra/clangd/Hover.cpp
index 51124ab371b2a..de103e011c708 100644
--- a/clang-tools-extra/clangd/Hover.cpp
+++ b/clang-tools-extra/c

[llvm-branch-commits] [clang] [clang] Implement CWG2398 provisional TTP matching to class templates (PR #92855)

2024-05-20 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/92855

This solves some ambuguity introduced in P0522 regarding how template template 
parameters are partially ordered, and should reduce the negative impact of 
enabling `-frelaxed-template-template-args` by default.

When performing template argument deduction, we extend the provisional wording 
introduced in https://github.com/llvm/llvm-project/pull/89807 so it also covers 
deduction of class templates.

Given the following example:
```C++
template  struct A;
template  struct B;

template  class TT1, class T5> struct B>;   // #1
template   struct B>; // #2

template struct B>;
```
Prior to P0522, `#2` was picked. Afterwards, this became ambiguous. This patch 
restores the pre-P0522 behavior, `#2` is picked again.

This has the beneficial side effect of making the following code valid:
```C++
template struct A {};
A v;
template class TT> void f(TT);

// OK: TT picks 'float' as the default argument for the second parameter.
void g() { f(v); }
```

---

Since this changes provisional implementation of CWG2398 which has not been 
released yet, and already contains a changelog entry, we don't provide a 
changelog entry here.

>From de5b6aa7f6c071440b909327ed7a21fad6c2317e Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Mon, 20 May 2024 01:15:03 -0300
Subject: [PATCH] [clang] Implement CWG2398 provisional TTP matching to class
 templates

This solves some ambuguity introduced in P0522 regarding how
template template parameters are partially ordered, and should reduce
the negative impact of enabling `-frelaxed-template-template-args`
by default.

When performing template argument deduction, we extend the provisional
wording introduced in https://github.com/llvm/llvm-project/pull/89807
so it also covers deduction of class templates.

Given the following example:
```C++
template  struct A;
template  struct B;

template  class TT1, class T5> struct B>;   // #1
template   struct B>; // #2

template struct B>;
```
Prior to P0522, `#2` was picked. Afterwards, this became ambiguous.
This patch restores the pre-P0522 behavior, `#2` is picked again.

This has the beneficial side effect of making the following code valid:
```C++
template struct A {};
A v;
template class TT> void f(TT);

// OK: TT picks 'float' as the default argument for the second parameter.
void g() { f(v); }
```

---

Since this changes provisional implementation of CWG2398 which has
not been released yet, and already contains a changelog entry,
we don't provide a changelog entry here.
---
 clang/lib/Sema/SemaTemplate.cpp   |  5 +-
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 72 +++
 .../CXX/temp/temp.decls/temp.alias/p2.cpp |  5 +-
 clang/test/SemaTemplate/cwg2398.cpp   |  3 -
 4 files changed, 51 insertions(+), 34 deletions(-)

diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 6af35ac8911bb..b7479cbcdba23 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -1807,6 +1807,8 @@ static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
 // Returns the template parameter list with all default template argument
 // information.
 static TemplateParameterList *GetTemplateParameterList(TemplateDecl *TD) {
+  if (TD->isImplicit())
+return TD->getTemplateParameters();
   // Make sure we get the template parameter list from the most
   // recent declaration, since that is the only one that is guaranteed to
   // have all the default template argument information.
@@ -1827,7 +1829,8 @@ static TemplateParameterList 
*GetTemplateParameterList(TemplateDecl *TD) {
   //template  friend struct C;
   //  };
   //  template struct S;
-  while (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None &&
+  while ((D->isImplicit() ||
+  D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None) &&
  D->getPreviousDecl())
 D = D->getPreviousDecl();
   return cast(D)->getTemplateParameters();
diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index f16a07e1a1b34..791e44658bd96 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -583,37 +583,53 @@ DeduceTemplateArguments(Sema &S, TemplateParameterList 
*TemplateParams,
   return TemplateDeductionResult::Success;
 
 auto NewDeduced = DeducedTemplateArgument(Arg);
-// Provisional resolution for CWG2398: If Arg is also a template template
-// param, and it names a template specialization, then we deduce a
-// synthesized template template parameter based on A, but using the TS's
-// arguments as defaults.
-if (auto *TempArg = dyn_cast_or_null(
-Arg.getAsTemplateDecl())) {
+// Provisional resolution for CWG2398: If Arg names a template
+// specialization, then we deduce a synthesized template template parameter
+  

[llvm-branch-commits] [clang] [clang-tools-extra] [clang] NFCI: use TemplateArgumentLoc for type-param DefaultArgument (PR #92854)

2024-05-20 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov edited 
https://github.com/llvm/llvm-project/pull/92854
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang-tools-extra] [clang] NFCI: use TemplateArgumentLoc for type-param DefaultArgument (PR #92854)

2024-05-20 Thread Matheus Izvekov via llvm-branch-commits


@@ -10082,7 +10082,9 @@ class Sema final : public SemaBase {
 
   bool SubstTemplateArgument(const TemplateArgumentLoc &Input,
  const MultiLevelTemplateArgumentList 
&TemplateArgs,
- TemplateArgumentLoc &Output);
+ TemplateArgumentLoc &Output,
+ SourceLocation Loc = {},
+ const DeclarationName &Entity = {});

mizvekov wrote:

There are a few places we used SubsType, because we only had a type, now we use 
SubstTemplateArgument.

SubstTemplateArgument was missing arguments for setting Instantiation location 
and entity names.
Adding those is needed so we don't regress in diagnostics.

https://github.com/llvm/llvm-project/pull/92854
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang-tools-extra] [clang] NFCI: use TemplateArgumentLoc for type-param DefaultArgument (PR #92854)

2024-05-20 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov edited 
https://github.com/llvm/llvm-project/pull/92854
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang-tools-extra] [clang] NFCI: use TemplateArgumentLoc for type-param DefaultArgument (PR #92854)

2024-05-21 Thread Matheus Izvekov via llvm-branch-commits

mizvekov wrote:

> I don't quite get the justification for this, but also don't see any downside 
> for it, so I think this is acceptable.

It's unfortunate GitHub does not show a PR stack like phab did.

This is needed for another patch you already reviewed: 
https://github.com/llvm/llvm-project/pull/92855

It allows forming default arguments for packs as part of TTP template argument 
deduction, based on the same principles already implemented in 
https://github.com/llvm/llvm-project/pull/89807

https://github.com/llvm/llvm-project/pull/92854
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang-tools-extra] [clang] Implement CWG2398 provisional TTP matching to class templates (PR #92855)

2024-05-21 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov edited 
https://github.com/llvm/llvm-project/pull/92855
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] Implement CWG2398 provisional TTP matching to class templates (PR #92855)

2024-05-21 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/92855

>From 73d456c632a1419c39316d38dcdc358b8e4f9636 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Mon, 20 May 2024 01:15:03 -0300
Subject: [PATCH] [clang] Implement CWG2398 provisional TTP matching to class
 templates

This solves some ambuguity introduced in P0522 regarding how
template template parameters are partially ordered, and should reduce
the negative impact of enabling `-frelaxed-template-template-args`
by default.

When performing template argument deduction, we extend the provisional
wording introduced in https://github.com/llvm/llvm-project/pull/89807
so it also covers deduction of class templates.

Given the following example:
```C++
template  struct A;
template  struct B;

template  class TT1, class T5> struct B>;   // #1
template   struct B>; // #2

template struct B>;
```
Prior to P0522, `#2` was picked. Afterwards, this became ambiguous.
This patch restores the pre-P0522 behavior, `#2` is picked again.

This has the beneficial side effect of making the following code valid:
```C++
template struct A {};
A v;
template class TT> void f(TT);

// OK: TT picks 'float' as the default argument for the second parameter.
void g() { f(v); }
```

---

Since this changes provisional implementation of CWG2398 which has
not been released yet, and already contains a changelog entry,
we don't provide a changelog entry here.
---
 clang/lib/Sema/SemaTemplate.cpp   |  5 +-
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 76 +++
 .../CXX/temp/temp.decls/temp.alias/p2.cpp |  5 +-
 clang/test/SemaTemplate/cwg2398.cpp   |  3 -
 4 files changed, 53 insertions(+), 36 deletions(-)

diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 39e9dbed0c3e0..268f079980a6c 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -1807,6 +1807,8 @@ static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
 // Returns the template parameter list with all default template argument
 // information.
 static TemplateParameterList *GetTemplateParameterList(TemplateDecl *TD) {
+  if (TD->isImplicit())
+return TD->getTemplateParameters();
   // Make sure we get the template parameter list from the most
   // recent declaration, since that is the only one that is guaranteed to
   // have all the default template argument information.
@@ -1827,7 +1829,8 @@ static TemplateParameterList 
*GetTemplateParameterList(TemplateDecl *TD) {
   //template  friend struct C;
   //  };
   //  template struct S;
-  while (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None &&
+  while ((D->isImplicit() ||
+  D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None) &&
  D->getPreviousDecl())
 D = D->getPreviousDecl();
   return cast(D)->getTemplateParameters();
diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index f16a07e1a1b34..76f47e9cb2560 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -527,8 +527,8 @@ static NamedDecl *getTemplateParameterWithDefault(Sema &S, 
NamedDecl *A,
 R->setDefaultArgument(
 S.Context,
 S.getTrivialTemplateArgumentLoc(Default, QualType(), 
SourceLocation()));
-if (R->hasTypeConstraint()) {
-  auto *C = R->getTypeConstraint();
+if (T->hasTypeConstraint()) {
+  auto *C = T->getTypeConstraint();
   R->setTypeConstraint(C->getConceptReference(),
C->getImmediatelyDeclaredConstraint());
 }
@@ -583,37 +583,53 @@ DeduceTemplateArguments(Sema &S, TemplateParameterList 
*TemplateParams,
   return TemplateDeductionResult::Success;
 
 auto NewDeduced = DeducedTemplateArgument(Arg);
-// Provisional resolution for CWG2398: If Arg is also a template template
-// param, and it names a template specialization, then we deduce a
-// synthesized template template parameter based on A, but using the TS's
-// arguments as defaults.
-if (auto *TempArg = dyn_cast_or_null(
-Arg.getAsTemplateDecl())) {
+// Provisional resolution for CWG2398: If Arg names a template
+// specialization, then we deduce a synthesized template template parameter
+// based on A, but using the TS's arguments as defaults.
+if (DefaultArguments.size() != 0) {
   assert(Arg.getKind() == TemplateName::Template);
-  assert(!TempArg->isExpandedParameterPack());
-
+  TemplateDecl *TempArg = Arg.getAsTemplateDecl();
   TemplateParameterList *As = TempArg->getTemplateParameters();
-  if (DefaultArguments.size() != 0) {
-assert(DefaultArguments.size() <= As->size());
-SmallVector Params(As->size());
-for (unsigned I = 0; I < DefaultArguments.size(); ++I)
-  Params[I] = getTemplateParameterWithDefault(S, As->getParam(I),
-   

[llvm-branch-commits] [clang] [clang] add fallback to expr in the template differ when comparing ValueDecl (PR #93266)

2024-05-23 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/93266

None

>From e74a7e69381731465efb8332890e0ebdc061fbb1 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Thu, 23 May 2024 23:57:01 -0300
Subject: [PATCH] [clang] add fallback to expr in the template differ when
 comparing ValueDecl

---
 clang/docs/ReleaseNotes.rst | 1 +
 clang/lib/AST/ASTDiagnostic.cpp | 5 +
 clang/test/Misc/diag-template-diffing-cxx26.cpp | 4 ++--
 3 files changed, 8 insertions(+), 2 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6e8687fadc6f7..5e217a76c81a1 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -784,6 +784,7 @@ Miscellaneous Bug Fixes
 - Fixed an infinite recursion in ASTImporter, on return type declared inside
   body of C++11 lambda without trailing return (#GH68775).
 - Fixed declaration name source location of instantiated function definitions 
(GH71161).
+- Missing fallback to expression in the template differ when comparing 
ValueDecls.
 
 Miscellaneous Clang Crashes Fixed
 ^
diff --git a/clang/lib/AST/ASTDiagnostic.cpp b/clang/lib/AST/ASTDiagnostic.cpp
index 7e4a5709a44ce..1885b21178666 100644
--- a/clang/lib/AST/ASTDiagnostic.cpp
+++ b/clang/lib/AST/ASTDiagnostic.cpp
@@ -1936,6 +1936,11 @@ class TemplateDiff {
   return;
 }
 
+if (E) {
+  PrintExpr(E);
+  return;
+}
+
 OS << "(no argument)";
   }
 
diff --git a/clang/test/Misc/diag-template-diffing-cxx26.cpp 
b/clang/test/Misc/diag-template-diffing-cxx26.cpp
index cc174d6c334fb..2b6dd86a9885d 100644
--- a/clang/test/Misc/diag-template-diffing-cxx26.cpp
+++ b/clang/test/Misc/diag-template-diffing-cxx26.cpp
@@ -19,10 +19,10 @@ namespace GH93068 {
 // expected-note@#A {{no known conversion from 'A<0>' to 'const A<&n[1]> 
&' for 1st argument}}
 // expected-note@#A {{no known conversion from 'A<0>' to 'A<&n[1]> &&' for 
1st argument}}
 
-// notree-error@#2 {{no viable conversion from 'A' to 'A<(no 
argument)>'}}
+// notree-error@#2 {{no viable conversion from 'A' to 'A'}}
 /* tree-error@#2 {{no viable conversion
   A<
-[n != (no argument)]>}}*/
+[n != n + 1]>}}*/
 
 A v2 = A(); // #2
 // expected-note@#A {{no known conversion from 'A' to 'const A<&n[1]> 
&' for 1st argument}}

___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] add fallback to expr in the template differ when comparing ValueDecl (PR #93266)

2024-05-24 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/93266

>From e74a7e69381731465efb8332890e0ebdc061fbb1 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Thu, 23 May 2024 23:57:01 -0300
Subject: [PATCH 1/2] [clang] add fallback to expr in the template differ when
 comparing ValueDecl

---
 clang/docs/ReleaseNotes.rst | 1 +
 clang/lib/AST/ASTDiagnostic.cpp | 5 +
 clang/test/Misc/diag-template-diffing-cxx26.cpp | 4 ++--
 3 files changed, 8 insertions(+), 2 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6e8687fadc6f7..5e217a76c81a1 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -784,6 +784,7 @@ Miscellaneous Bug Fixes
 - Fixed an infinite recursion in ASTImporter, on return type declared inside
   body of C++11 lambda without trailing return (#GH68775).
 - Fixed declaration name source location of instantiated function definitions 
(GH71161).
+- Missing fallback to expression in the template differ when comparing 
ValueDecls.
 
 Miscellaneous Clang Crashes Fixed
 ^
diff --git a/clang/lib/AST/ASTDiagnostic.cpp b/clang/lib/AST/ASTDiagnostic.cpp
index 7e4a5709a44ce..1885b21178666 100644
--- a/clang/lib/AST/ASTDiagnostic.cpp
+++ b/clang/lib/AST/ASTDiagnostic.cpp
@@ -1936,6 +1936,11 @@ class TemplateDiff {
   return;
 }
 
+if (E) {
+  PrintExpr(E);
+  return;
+}
+
 OS << "(no argument)";
   }
 
diff --git a/clang/test/Misc/diag-template-diffing-cxx26.cpp 
b/clang/test/Misc/diag-template-diffing-cxx26.cpp
index cc174d6c334fb..2b6dd86a9885d 100644
--- a/clang/test/Misc/diag-template-diffing-cxx26.cpp
+++ b/clang/test/Misc/diag-template-diffing-cxx26.cpp
@@ -19,10 +19,10 @@ namespace GH93068 {
 // expected-note@#A {{no known conversion from 'A<0>' to 'const A<&n[1]> 
&' for 1st argument}}
 // expected-note@#A {{no known conversion from 'A<0>' to 'A<&n[1]> &&' for 
1st argument}}
 
-// notree-error@#2 {{no viable conversion from 'A' to 'A<(no 
argument)>'}}
+// notree-error@#2 {{no viable conversion from 'A' to 'A'}}
 /* tree-error@#2 {{no viable conversion
   A<
-[n != (no argument)]>}}*/
+[n != n + 1]>}}*/
 
 A v2 = A(); // #2
 // expected-note@#A {{no known conversion from 'A' to 'const A<&n[1]> 
&' for 1st argument}}

>From 4b12139395d8bcabd053ed6db11aa049ee95d5c3 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Fri, 24 May 2024 11:29:13 -0300
Subject: [PATCH 2/2] Update clang/docs/ReleaseNotes.rst

Co-authored-by: Erich Keane 
---
 clang/docs/ReleaseNotes.rst | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5e217a76c81a1..a63b0c2460cd7 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -784,7 +784,7 @@ Miscellaneous Bug Fixes
 - Fixed an infinite recursion in ASTImporter, on return type declared inside
   body of C++11 lambda without trailing return (#GH68775).
 - Fixed declaration name source location of instantiated function definitions 
(GH71161).
-- Missing fallback to expression in the template differ when comparing 
ValueDecls.
+- Improve diagnostic output to print an expression instead of 'no argument` 
when comparing Values as template arguments.
 
 Miscellaneous Clang Crashes Fixed
 ^

___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] Preserve Qualifiers and type sugar in TemplateNames (PR #93433)

2024-05-26 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/93433

This patch improves the preservation of qualifiers and loss of type sugar in 
TemplateNames.

This problem is analogous to https://reviews.llvm.org/D112374 and this patch 
takes a very similar approach to that patch, except the impact here is much 
lesser.

When a TemplateName was written bare, without qualifications, we wouldn't 
produce a QualifiedTemplate which could be used to disambiguate it from a 
Canonical TemplateName. This had effects in the TemplateName printer, which had 
workarounds to deal with this, and wouldn't print the TemplateName as-written 
in most situations.

There are also some related fixes to help preserve this type sugar along the 
way into diagnostics, so that this patch can be properly tested.

- Fix dropping the template keyword.
- Fix type deduction to preserve sugar in TST TemplateNames.

>From a1fe052b0fb0c96fc5ae38af7f13b19110d8096d Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Sat, 25 May 2024 13:57:39 -0300
Subject: [PATCH] [clang] Preserve Qualifiers and type sugar in TemplateNames

This patch improves the preservation of qualifiers
and loss of type sugar in TemplateNames.

This problem is analogous to https://reviews.llvm.org/D112374
and this patch takes a very similar approach to that patch,
except the impact here is much lesser.

When a TemplateName was written bare, without qualifications,
we wouldn't produce a QualifiedTemplate which could be used
to disambiguate it from a Canonical TemplateName. This had
effects in the TemplateName printer, which had workarounds
to deal with this, and wouldn't print the TemplateName
as-written in most situations.

There are also some related fixes to help preserve this type
sugar along the way into diagnostics, so that this patch can
be properly tested.

- Fix dropping the template keyword.
- Fix type deduction to preserve sugar in TST TemplateNames.
---
 clang/docs/ReleaseNotes.rst   |  2 +
 clang/include/clang/AST/TemplateName.h|  2 +-
 clang/include/clang/Sema/Sema.h   |  3 +
 clang/lib/AST/ASTContext.cpp  | 16 ++---
 clang/lib/AST/DeclTemplate.cpp|  7 +-
 clang/lib/AST/ODRHash.cpp |  9 ++-
 clang/lib/AST/TemplateBase.cpp|  2 +-
 clang/lib/AST/TemplateName.cpp| 64 +--
 clang/lib/AST/TextNodeDumper.cpp  |  4 +-
 clang/lib/AST/Type.cpp|  3 +-
 clang/lib/AST/TypePrinter.cpp |  4 +-
 clang/lib/Sema/SemaDecl.cpp   | 15 ++---
 clang/lib/Sema/SemaDeclCXX.cpp| 12 ++--
 clang/lib/Sema/SemaExpr.cpp   |  4 +-
 clang/lib/Sema/SemaExprMember.cpp |  3 +-
 clang/lib/Sema/SemaTemplate.cpp   | 25 +---
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 62 +-
 clang/lib/Sema/SemaType.cpp   | 14 ++--
 clang/lib/Sema/TreeTransform.h|  8 +--
 clang/test/AST/ast-dump-ctad-alias.cpp|  6 +-
 clang/test/AST/ast-dump-decl.cpp  |  8 +--
 clang/test/AST/ast-dump-expr.cpp  |  2 +-
 clang/test/AST/ast-dump-template-decls.cpp|  6 +-
 clang/test/AST/ast-dump-template-name.cpp |  4 +-
 clang/test/AST/ast-dump-using-template.cpp|  6 +-
 clang/test/CXX/drs/cwg1xx.cpp |  4 +-
 .../over.match.oper/p3-2a.cpp |  4 +-
 .../temp.deduct/temp.deduct.type/p9-0x.cpp|  4 +-
 clang/test/Index/print-type.cpp   |  2 +-
 clang/test/OpenMP/declare_mapper_messages.cpp |  2 +-
 .../Parser/cxx-template-template-recovery.cpp |  4 +-
 .../cxx1y-variable-templates_in_class.cpp | 10 +--
 clang/test/SemaTemplate/cwg2398.cpp   |  2 +-
 .../instantiate-requires-expr.cpp |  4 +-
 .../nested-implicit-deduction-guides.cpp  |  2 +-
 clang/unittests/AST/TemplateNameTest.cpp  | 40 ++--
 36 files changed, 222 insertions(+), 147 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 403a107edef17..257e1df6e6503 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -802,6 +802,8 @@ Bug Fixes to AST Handling
 - Clang now properly preserves ``FoundDecls`` within a ``ConceptReference``. 
(#GH82628)
 - The presence of the ``typename`` keyword is now stored in 
``TemplateTemplateParmDecl``.
 - Fixed malformed AST generated for anonymous union access in templates. 
(#GH90842)
+- Improved preservation of qualifiers and sugar in TemplateNames, including
+  template keyword.
 
 Miscellaneous Bug Fixes
 ^^^
diff --git a/clang/include/clang/AST/TemplateName.h 
b/clang/include/clang/AST/TemplateName.h
index b7732e54ba107..6bb03f90ac36a 100644
--- a/clang/include/clang/AST/TemplateName.h
+++ b/clang/include/clang/AST/TemplateName.h
@@ -332,7 +332,7 @@ class TemplateName {
   /// unexpanded parameter pack 

[llvm-branch-commits] [clang] [libcxx] [clang] Preserve Qualifiers and type sugar in TemplateNames (PR #93433)

2024-05-26 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/93433

>From 91fa7c94aa5c0936484e75f1cf88df2489b9f587 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Sat, 25 May 2024 13:57:39 -0300
Subject: [PATCH] [clang] Preserve Qualifiers and type sugar in TemplateNames

This patch improves the preservation of qualifiers
and loss of type sugar in TemplateNames.

This problem is analogous to https://reviews.llvm.org/D112374
and this patch takes a very similar approach to that patch,
except the impact here is much lesser.

When a TemplateName was written bare, without qualifications,
we wouldn't produce a QualifiedTemplate which could be used
to disambiguate it from a Canonical TemplateName. This had
effects in the TemplateName printer, which had workarounds
to deal with this, and wouldn't print the TemplateName
as-written in most situations.

There are also some related fixes to help preserve this type
sugar along the way into diagnostics, so that this patch can
be properly tested.

- Fix dropping the template keyword.
- Fix type deduction to preserve sugar in TST TemplateNames.
---
 clang/docs/ReleaseNotes.rst   |  2 +
 clang/include/clang/AST/TemplateName.h|  2 +-
 clang/include/clang/Sema/Sema.h   |  3 +
 clang/lib/AST/ASTContext.cpp  | 16 ++---
 clang/lib/AST/DeclTemplate.cpp|  7 +-
 clang/lib/AST/ODRHash.cpp |  9 ++-
 clang/lib/AST/TemplateBase.cpp|  2 +-
 clang/lib/AST/TemplateName.cpp| 64 +--
 clang/lib/AST/TextNodeDumper.cpp  |  4 +-
 clang/lib/AST/Type.cpp|  3 +-
 clang/lib/AST/TypePrinter.cpp |  4 +-
 clang/lib/Sema/SemaDecl.cpp   | 15 ++---
 clang/lib/Sema/SemaDeclCXX.cpp| 12 ++--
 clang/lib/Sema/SemaExpr.cpp   |  4 +-
 clang/lib/Sema/SemaExprMember.cpp |  3 +-
 clang/lib/Sema/SemaTemplate.cpp   | 25 +---
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 62 +-
 clang/lib/Sema/SemaType.cpp   | 14 ++--
 clang/lib/Sema/TreeTransform.h|  8 +--
 clang/test/AST/ast-dump-ctad-alias.cpp|  6 +-
 clang/test/AST/ast-dump-decl.cpp  |  8 +--
 clang/test/AST/ast-dump-expr.cpp  |  2 +-
 clang/test/AST/ast-dump-template-decls.cpp|  6 +-
 clang/test/AST/ast-dump-template-name.cpp |  4 +-
 clang/test/AST/ast-dump-using-template.cpp|  6 +-
 clang/test/CXX/drs/cwg1xx.cpp |  4 +-
 .../over.match.oper/p3-2a.cpp |  4 +-
 .../temp.deduct/temp.deduct.type/p9-0x.cpp|  4 +-
 clang/test/Index/print-type.cpp   |  2 +-
 clang/test/OpenMP/declare_mapper_messages.cpp |  2 +-
 .../Parser/cxx-template-template-recovery.cpp |  4 +-
 .../cxx1y-variable-templates_in_class.cpp | 10 +--
 clang/test/SemaTemplate/cwg2398.cpp   |  2 +-
 .../instantiate-requires-expr.cpp |  4 +-
 .../nested-implicit-deduction-guides.cpp  |  2 +-
 clang/unittests/AST/TemplateNameTest.cpp  | 40 ++--
 .../map/map.cons/deduct.verify.cpp| 24 +++
 .../multimap/multimap.cons/deduct.verify.cpp  | 22 +++
 .../multiset/multiset.cons/deduct.verify.cpp  | 10 +--
 .../set/set.cons/deduct.verify.cpp| 10 +--
 .../priqueue.cons/deduct.verify.cpp   | 10 +--
 .../queue/queue.cons/deduct.verify.cpp|  6 +-
 .../stack/stack.cons/deduct.verify.cpp|  6 +-
 .../array/array.cons/deduct.verify.cpp|  2 +-
 .../deque/deque.cons/deduct.verify.cpp|  2 +-
 .../forwardlist.cons/deduct.verify.cpp|  2 +-
 .../list/list.cons/deduct.verify.cpp  |  2 +-
 .../vector/vector.cons/deduct.verify.cpp  |  2 +-
 .../unord.map.cnstr/deduct.verify.cpp | 16 ++---
 .../unord.multimap.cnstr/deduct.verify.cpp| 16 ++---
 .../unord.multiset.cnstr/deduct.verify.cpp| 16 ++---
 .../unord.set.cnstr/deduct.verify.cpp | 16 ++---
 .../range.adaptors/range.join/ctad.verify.cpp |  2 +-
 .../re.regex.construct/deduct.verify.cpp  |  4 +-
 .../func.wrap.func.con/deduct_F.verify.cpp|  6 +-
 .../optional.object.ctor/deduct.verify.cpp|  2 +-
 56 files changed, 310 insertions(+), 235 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index f7562ce74f4ed..af8188b7ca3b1 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -804,6 +804,8 @@ Bug Fixes to AST Handling
 - Clang now properly preserves ``FoundDecls`` within a ``ConceptReference``. 
(#GH82628)
 - The presence of the ``typename`` keyword is now stored in 
``TemplateTemplateParmDecl``.
 - Fixed malformed AST generated for anonymous union access in templates. 
(#GH90842)
+- Improved preservation of qualifiers and sugar in TemplateNames, including
+  template keyword.
 
 Miscellaneous Bug Fixes
 ^^^
diff --

[llvm-branch-commits] [clang] [libcxx] [clang] Preserve Qualifiers and type sugar in TemplateNames (PR #93433)

2024-05-27 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/93433

>From 40e3c0fd00a9a3327123d43c6ad6447a14b4e543 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Sat, 25 May 2024 13:57:39 -0300
Subject: [PATCH] [clang] Preserve Qualifiers and type sugar in TemplateNames

This patch improves the preservation of qualifiers
and loss of type sugar in TemplateNames.

This problem is analogous to https://reviews.llvm.org/D112374
and this patch takes a very similar approach to that patch,
except the impact here is much lesser.

When a TemplateName was written bare, without qualifications,
we wouldn't produce a QualifiedTemplate which could be used
to disambiguate it from a Canonical TemplateName. This had
effects in the TemplateName printer, which had workarounds
to deal with this, and wouldn't print the TemplateName
as-written in most situations.

There are also some related fixes to help preserve this type
sugar along the way into diagnostics, so that this patch can
be properly tested.

- Fix dropping the template keyword.
- Fix type deduction to preserve sugar in TST TemplateNames.
---
 clang/docs/ReleaseNotes.rst   |  2 +
 clang/include/clang/AST/TemplateName.h|  2 +-
 clang/include/clang/Sema/Sema.h   |  3 +
 clang/lib/AST/ASTContext.cpp  | 16 ++---
 clang/lib/AST/DeclTemplate.cpp|  7 +-
 clang/lib/AST/ODRHash.cpp |  9 ++-
 clang/lib/AST/TemplateBase.cpp|  2 +-
 clang/lib/AST/TemplateName.cpp| 64 +--
 clang/lib/AST/TextNodeDumper.cpp  |  4 +-
 clang/lib/AST/Type.cpp|  3 +-
 clang/lib/AST/TypePrinter.cpp |  4 +-
 clang/lib/Sema/SemaDecl.cpp   | 15 ++---
 clang/lib/Sema/SemaDeclCXX.cpp| 12 ++--
 clang/lib/Sema/SemaExpr.cpp   |  4 +-
 clang/lib/Sema/SemaExprMember.cpp |  3 +-
 clang/lib/Sema/SemaTemplate.cpp   | 25 +---
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 62 +-
 clang/lib/Sema/SemaType.cpp   | 14 ++--
 clang/lib/Sema/TreeTransform.h|  8 +--
 clang/test/AST/ast-dump-ctad-alias.cpp|  6 +-
 clang/test/AST/ast-dump-decl.cpp  |  8 +--
 clang/test/AST/ast-dump-expr.cpp  |  2 +-
 clang/test/AST/ast-dump-template-decls.cpp|  6 +-
 clang/test/AST/ast-dump-template-name.cpp |  4 +-
 clang/test/AST/ast-dump-using-template.cpp|  6 +-
 clang/test/CXX/drs/cwg1xx.cpp |  4 +-
 .../over.match.oper/p3-2a.cpp |  4 +-
 .../temp.deduct/temp.deduct.type/p9-0x.cpp|  4 +-
 clang/test/Index/print-type.cpp   |  2 +-
 clang/test/OpenMP/declare_mapper_messages.cpp |  2 +-
 .../Parser/cxx-template-template-recovery.cpp |  4 +-
 .../cxx1y-variable-templates_in_class.cpp | 10 +--
 clang/test/SemaTemplate/cwg2398.cpp   |  2 +-
 .../instantiate-requires-expr.cpp |  4 +-
 .../nested-implicit-deduction-guides.cpp  |  2 +-
 clang/unittests/AST/TemplateNameTest.cpp  | 40 ++--
 .../map/map.cons/deduct.verify.cpp| 24 +++
 .../multimap/multimap.cons/deduct.verify.cpp  | 22 +++
 .../multiset/multiset.cons/deduct.verify.cpp  | 10 +--
 .../set/set.cons/deduct.verify.cpp| 10 +--
 .../priqueue.cons/deduct.verify.cpp   | 10 +--
 .../queue/queue.cons/deduct.verify.cpp|  6 +-
 .../stack/stack.cons/deduct.verify.cpp|  6 +-
 .../array/array.cons/deduct.verify.cpp|  2 +-
 .../deque/deque.cons/deduct.verify.cpp|  2 +-
 .../forwardlist.cons/deduct.verify.cpp|  2 +-
 .../list/list.cons/deduct.verify.cpp  |  2 +-
 .../vector/vector.cons/deduct.verify.cpp  |  2 +-
 .../unord.map.cnstr/deduct.verify.cpp | 16 ++---
 .../unord.multimap.cnstr/deduct.verify.cpp| 16 ++---
 .../unord.multiset.cnstr/deduct.verify.cpp| 16 ++---
 .../unord.set.cnstr/deduct.verify.cpp | 16 ++---
 .../range.adaptors/range.join/ctad.verify.cpp |  2 +-
 .../re.regex.construct/deduct.verify.cpp  |  4 +-
 .../func.wrap.func.con/deduct_F.verify.cpp|  6 +-
 .../optional.object.ctor/deduct.verify.cpp|  2 +-
 56 files changed, 310 insertions(+), 235 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index f7562ce74f4ed..af8188b7ca3b1 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -804,6 +804,8 @@ Bug Fixes to AST Handling
 - Clang now properly preserves ``FoundDecls`` within a ``ConceptReference``. 
(#GH82628)
 - The presence of the ``typename`` keyword is now stored in 
``TemplateTemplateParmDecl``.
 - Fixed malformed AST generated for anonymous union access in templates. 
(#GH90842)
+- Improved preservation of qualifiers and sugar in TemplateNames, including
+  template keyword.
 
 Miscellaneous Bug Fixes
 ^^^
diff --

[llvm-branch-commits] [clang] [clang] fix printing of canonical template template parameters take 2 (PR #93448)

2024-05-27 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/93448

Since they can also occur as the template name of
template specializations, handle them from TemplateName printing instead of 
TemplateArgument.

>From 7876afed3dec889805b2947e61ca10953a5a7456 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Mon, 27 May 2024 05:51:18 -0300
Subject: [PATCH] [clang] fix printing of canonical template template
 parameters take 2

Since they can also occur as the template name of
template specializations, handle them from TemplateName
printing instead of TemplateArgument.
---
 clang/lib/AST/TemplateBase.cpp  | 11 +--
 clang/lib/AST/TemplateName.cpp  | 14 ++
 clang/test/SemaTemplate/deduction-guide.cpp | 10 +-
 3 files changed, 20 insertions(+), 15 deletions(-)

diff --git a/clang/lib/AST/TemplateBase.cpp b/clang/lib/AST/TemplateBase.cpp
index 4d4991d8c38b5..bb0820f4177e4 100644
--- a/clang/lib/AST/TemplateBase.cpp
+++ b/clang/lib/AST/TemplateBase.cpp
@@ -539,16 +539,7 @@ void TemplateArgument::print(const PrintingPolicy &Policy, 
raw_ostream &Out,
 break;
 
   case Template: {
-TemplateName TN = getAsTemplate();
-if (const auto *TD = TN.getAsTemplateDecl();
-TD && TD->getDeclName().isEmpty()) {
-  assert(isa(TD) &&
- "Unexpected anonymous template");
-  const auto *TTP = cast(TD);
-  Out << "template-parameter-" << TTP->getDepth() << "-" << 
TTP->getIndex();
-} else {
-  TN.print(Out, Policy);
-}
+getAsTemplate().print(Out, Policy);
 break;
   }
 
diff --git a/clang/lib/AST/TemplateName.cpp b/clang/lib/AST/TemplateName.cpp
index 3aae998eceeb0..1ce31f09f2a6a 100644
--- a/clang/lib/AST/TemplateName.cpp
+++ b/clang/lib/AST/TemplateName.cpp
@@ -292,6 +292,14 @@ void TemplateName::Profile(llvm::FoldingSetNodeID &ID) {
 
 void TemplateName::print(raw_ostream &OS, const PrintingPolicy &Policy,
  Qualified Qual) const {
+  auto handleCanonicalTTP = [](TemplateDecl *TD, raw_ostream &OS) {
+if (TemplateTemplateParmDecl *TTP = dyn_cast(TD);
+TTP && TTP->getIdentifier() == nullptr) {
+  OS << "template-parameter-" << TTP->getDepth() << "-" << TTP->getIndex();
+  return true;
+}
+return false;
+  };
   if (NameKind Kind = getKind();
   Kind == TemplateName::Template || Kind == TemplateName::UsingTemplate) {
 // After `namespace ns { using std::vector }`, what is the fully-qualified
@@ -304,6 +312,8 @@ void TemplateName::print(raw_ostream &OS, const 
PrintingPolicy &Policy,
 // names more often than to export them, thus using the original name is
 // most useful in this case.
 TemplateDecl *Template = getAsTemplateDecl();
+if (handleCanonicalTTP(Template, OS))
+  return;
 if (Qual == Qualified::None)
   OS << *Template;
 else
@@ -320,6 +330,10 @@ void TemplateName::print(raw_ostream &OS, const 
PrintingPolicy &Policy,
Underlying.getKind() == TemplateName::UsingTemplate);
 
 TemplateDecl *UTD = Underlying.getAsTemplateDecl();
+
+if (handleCanonicalTTP(UTD, OS))
+  return;
+
 if (IdentifierInfo *II = UTD->getIdentifier();
 Policy.CleanUglifiedParameters && II &&
 isa(UTD))
diff --git a/clang/test/SemaTemplate/deduction-guide.cpp 
b/clang/test/SemaTemplate/deduction-guide.cpp
index 96b4cd9622a24..100b580fe9f02 100644
--- a/clang/test/SemaTemplate/deduction-guide.cpp
+++ b/clang/test/SemaTemplate/deduction-guide.cpp
@@ -315,19 +315,19 @@ namespace TTP {
 // CHECK-NEXT:  |-TemplateTypeParmDecl {{.+}} class depth 0 index 0 T{{$}}
 // CHECK-NEXT:  |-TemplateTemplateParmDecl {{.+}} depth 0 index 1 TT{{$}}
 // CHECK-NEXT:  | `-TemplateTypeParmDecl {{.+}} class depth 1 index 0{{$}}
-// CHECK-NEXT:  |-CXXDeductionGuideDecl {{.+}} 'auto () -> B'{{$}}
-// CHECK-NEXT:  | `-ParmVarDecl {{.+}} ''{{$}}
+// CHECK-NEXT:  |-CXXDeductionGuideDecl {{.+}} 'auto 
(template-parameter-0-1) -> B'{{$}}
+// CHECK-NEXT:  | `-ParmVarDecl {{.+}} 'template-parameter-0-1'{{$}}
 // CHECK-NEXT:  `-CXXDeductionGuideDecl {{.+}} 'auto (A) -> TTP::B'
 // CHECK-NEXT:|-TemplateArgument type 'int'
 // CHECK-NEXT:| `-BuiltinType {{.+}} 'int'{{$}}
 // CHECK-NEXT:|-TemplateArgument template 'TTP::A'{{$}}
 // CHECK-NEXT:| `-ClassTemplateDecl {{.+}} A{{$}}
 // CHECK-NEXT:`-ParmVarDecl {{.+}} 'A':'TTP::A'{{$}}
-// CHECK-NEXT:  FunctionProtoType {{.+}} 'auto () -> B' dependent 
trailing_return cdecl{{$}}
+// CHECK-NEXT:  FunctionProtoType {{.+}} 'auto (template-parameter-0-1) -> 
B' dependent trailing_return cdecl{{$}}
 // CHECK-NEXT:  |-InjectedClassNameType {{.+}} 'B' dependent{{$}}
 // CHECK-NEXT:  | `-CXXRecord {{.+}} 'B'{{$}}
-// CHECK-NEXT:  `-ElaboratedType {{.+}} '' sugar dependent{{$}}
-// CHECK-NEXT:`-TemplateSpecializationType {{.+}} '' dependent {{$}}
+// CHECK-NEXT:  `-ElaboratedType {{.+}} 'template-parameter-0-1' sugar 
dependent{{$}}
+// CHECK-NEXT:`-Template

[llvm-branch-commits] [clang] [libcxx] [clang] Preserve Qualifiers and type sugar in TemplateNames (PR #93433)

2024-05-27 Thread Matheus Izvekov via llvm-branch-commits


@@ -9304,7 +9299,8 @@ TemplateName 
ASTContext::getAssumedTemplateName(DeclarationName Name) const {
 TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
   bool TemplateKeyword,
   TemplateName Template) const 
{
-  assert(NNS && "Missing nested-name-specifier in qualified template name");

mizvekov wrote:

In 'QualifiedTemplateName', there are two qualifiers: The nested name 
specifier, and the template keyword.

Just as a template might be written without a template keyword qualifier, it 
can also be written without a nested name qualifier. You can have one, the 
other, both, or none.

This assert was already wrong in that it was valid to have a template written 
with template keyword, but written without any nested name. For example an 
object access to a member template: `p->template foo<...>`.
That is fixed in this patch and you can see that in tests.

When we know how a template was written, we wish to print them as that.

We have a third situation here: A canonical template name, that is, a template 
which we have no information on how it was written. We want to be able to tell 
these apart, because we don't wish to print them as if they had no qualifiers. 
Quite the contrary, we want to synthesize a maximal nested name for them, based 
on their DC, and print them with that.

Otherwise, there is no in-band NestedNameSpecifier non-null value to indicate 
an empty nested name. Null is what we use here, and what is used in other 
places, like for example the aforementioned ElaboratedType.

In fact, as I mentioned before, this issue is much similar to what we had for 
ElaboratedType before https://reviews.llvm.org/D112374, except in that case we 
already recognized that a class name might be written with elaboration, but no 
nested name, unlike here which the 'only a template keyword' situation was 
forgotten.

In that case, a `nullptr` was already used to represent an empty 
NestedNameSpecifier, as expected.

https://github.com/llvm/llvm-project/pull/93433
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang-tools-extra] [clangd] check for synthesized symbols when tracking include locations (PR #75128)

2023-12-11 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/75128

This fixes https://github.com/llvm/llvm-project/issues/75115

In C mode with MSVC compatibility, when the `assert` macro is defined, as a 
workaround, `static_assert` is implicitly defined as well, if not already so, 
in order to work around a broken `assert.h` implementation.
This workaround was implemented in 
https://github.com/llvm/llvm-project/commit/8da090381d567d0ec555840f6b2a651d2997e4b3

A synthesized symbol does not occur in source code, and therefore should not 
have valid source location, but this was not checked when inserting this into a 
`symbol -> include file` map.

The invalid FileID value is used for empty key representation in the include 
file hash table, so it's not valid to insert it.

>From 51de797d836f75a76b14e08eb2c1dfff1d1586ec Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Mon, 11 Dec 2023 17:45:12 -0300
Subject: [PATCH] [clangd] check for synthesized symbols when tracking include
 locations

This fixes https://github.com/llvm/llvm-project/issues/75115

In C mode with MSVC compatibility, when the `assert` macro is defined,
as a workaround, `static_assert` is implicitly defined as well,
if not already so, in order to work around a broken `assert.h`
implementation.
This workaround was implemented in 
https://github.com/llvm/llvm-project/commit/8da090381d567d0ec555840f6b2a651d2997e4b3

A synthesized symbol does not occur in source code, and therefore
should not have valid source location, but this was not checked when
inserting this into a `symbol -> include file` map.

The invalid FileID value is used for empty key representation in
the include file hash table, so it's not valid to insert it.
---
 clang-tools-extra/clangd/index/SymbolCollector.cpp |  6 +-
 clang-tools-extra/clangd/test/GH75115.test | 11 +++
 2 files changed, 12 insertions(+), 5 deletions(-)

diff --git a/clang-tools-extra/clangd/index/SymbolCollector.cpp 
b/clang-tools-extra/clangd/index/SymbolCollector.cpp
index aac6676a995fed..e9e76abb90a2d6 100644
--- a/clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ b/clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -821,7 +821,11 @@ void SymbolCollector::setIncludeLocation(const Symbol &S, 
SourceLocation DefLoc,
 
   // Use the expansion location to get the #include header since this is
   // where the symbol is exposed.
-  IncludeFiles[S.ID] = SM.getDecomposedExpansionLoc(DefLoc).first;
+  FileID FID = SM.getDecomposedExpansionLoc(DefLoc).first;
+  if (FID.isInvalid())
+return;
+
+  IncludeFiles[S.ID] = FID;
 
   // We update providers for a symbol with each occurence, as SymbolCollector
   // might run while parsing, rather than at the end of a translation unit.
diff --git a/clang-tools-extra/clangd/test/GH75115.test 
b/clang-tools-extra/clangd/test/GH75115.test
index 030392f1d69b30..dc86f5b9a6cee0 100644
--- a/clang-tools-extra/clangd/test/GH75115.test
+++ b/clang-tools-extra/clangd/test/GH75115.test
@@ -1,12 +1,15 @@
 // RUN: rm -rf %t.dir && mkdir -p %t.dir
 // RUN: echo '[{"directory": "%/t.dir", "command": "clang 
--target=x86_64-pc-windows-msvc -x c GH75115.test", "file": "GH75115.test"}]' > 
%t.dir/compile_commands.json
-// RUN: not --crash clangd -enable-config=0 --compile-commands-dir=%t.dir 
-check=%s 2>&1 | FileCheck -strict-whitespace %s
-
-// FIXME: Crashes
+// RUN: clangd -enable-config=0 --compile-commands-dir=%t.dir -check=%s 2>&1 | 
FileCheck -strict-whitespace %s
 
 // CHECK: Building preamble...
 // CHECK-NEXT: Built preamble
 // CHECK-NEXT: Indexing headers...
-// CHECK-NEXT: !KeyInfoT::isEqual(Val, EmptyKey) && !KeyInfoT::isEqual(Val, 
TombstoneKey) && "Empty/Tombstone value shouldn't be inserted into map!"
+// CHECK-NEXT: Building AST...
+// CHECK-NEXT: Indexing AST...
+// CHECK-NEXT: Building inlay hints
+// CHECK-NEXT: semantic highlighting
+// CHECK-NEXT: Testing features at each token
+// CHECK-NEXT: All checks completed, 0 errors
 
 #define assert

___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang-tools-extra] [clangd] check for synthesized symbols when tracking include locations (PR #75128)

2023-12-12 Thread Matheus Izvekov via llvm-branch-commits

mizvekov wrote:

> Hi @mizvekov thanks for the fix, but I am not sure if this is at the right 
> level. The way you're bailing out currently prevents clangd from indexing all 
> implicit definitions, even if we have a hard-coded mapping for them (based on 
> the symbol name).
> 
> Also the map you're preventing the insertion stores FileIDs as values, not 
> keys, hence it isn't the place firing assertion failures. Can you instead 
> move the logic to SymbolCollector::finish, which uses FileIDs to determine 
> includers for objective-c symbols? we should only perform that logic if 
> there's a valid FileID.

I see. Though the situation you describe seems impossible at the present state 
of the implementation.

For standard library stuff, we have hardcoded std::move and std::remove, 
implemented 
[here](https://github.com/llvm/llvm-project/blob/6d8fe3dc9a4f6225c4c84de578469efc50d7684d/clang-tools-extra/include-cleaner/lib/FindHeaders.cpp#L117)
 but those require some sort of user provided declaration somewhere in code, 
which will have a valid source location, and we indeed unit test that.

As an aside, I think in the above case we should honor the `-freestanding` 
flag, but currently we do not.

For the builtin-which-requires-include case, that is unimplemented, with a 
FIXME note: 
https://github.com/llvm/llvm-project/blob/6d8fe3dc9a4f6225c4c84de578469efc50d7684d/clang-tools-extra/include-cleaner/lib/FindHeaders.cpp#L177

I agree in principle to the change you suggested, even if presently non 
testable, but I still think it makes sense to skip inserting invalid FileIDs 
into the `IncludeFiles` map.

https://github.com/llvm/llvm-project/pull/75128
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang-tools-extra] [clangd] check for synthesized symbols when tracking include locations (PR #75128)

2023-12-12 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/75128

>From 3fb75008987c28c9d63d209f36caaced8b37c4a6 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Wed, 13 Dec 2023 01:44:16 -0300
Subject: [PATCH] [clangd] check for synthesized symbols when tracking include
 locations

This fixes https://github.com/llvm/llvm-project/issues/75115

In C mode with MSVC compatibility, when the `assert` macro is defined,
as a workaround, `static_assert` is implicitly defined as well,
if not already so, in order to work around a broken `assert.h`
implementation.
This workaround was implemented in 
https://github.com/llvm/llvm-project/commit/8da090381d567d0ec555840f6b2a651d2997e4b3

A synthesized symbol does not occur in source code, and therefore
should not have valid source location, but this was not checked when
inserting this into a `symbol -> include file` map.

The invalid FileID value is used for empty key representation in
the include file hash table, so it's not valid to insert it.
---
 clang-tools-extra/clangd/index/SymbolCollector.cpp |  8 
 clang-tools-extra/clangd/test/GH75115.test | 11 +++
 2 files changed, 11 insertions(+), 8 deletions(-)

diff --git a/clang-tools-extra/clangd/index/SymbolCollector.cpp 
b/clang-tools-extra/clangd/index/SymbolCollector.cpp
index aac6676a995fed..5d995cdae6d665 100644
--- a/clang-tools-extra/clangd/index/SymbolCollector.cpp
+++ b/clang-tools-extra/clangd/index/SymbolCollector.cpp
@@ -821,7 +821,8 @@ void SymbolCollector::setIncludeLocation(const Symbol &S, 
SourceLocation DefLoc,
 
   // Use the expansion location to get the #include header since this is
   // where the symbol is exposed.
-  IncludeFiles[S.ID] = SM.getDecomposedExpansionLoc(DefLoc).first;
+  if (FileID FID = SM.getDecomposedExpansionLoc(DefLoc).first; FID.isValid())
+IncludeFiles[S.ID] = FID;
 
   // We update providers for a symbol with each occurence, as SymbolCollector
   // might run while parsing, rather than at the end of a translation unit.
@@ -893,16 +894,15 @@ void SymbolCollector::finish() {
 const Symbol *S = Symbols.find(SID);
 if (!S)
   continue;
-assert(IncludeFiles.contains(SID));
 
-const auto FID = IncludeFiles.at(SID);
+FileID FID = IncludeFiles.lookup(SID);
 // Determine if the FID is #include'd or #import'ed.
 Symbol::IncludeDirective Directives = Symbol::Invalid;
 auto CollectDirectives = shouldCollectIncludePath(S->SymInfo.Kind);
 if ((CollectDirectives & Symbol::Include) != 0)
   Directives |= Symbol::Include;
 // Only allow #import for symbols from ObjC-like files.
-if ((CollectDirectives & Symbol::Import) != 0) {
+if ((CollectDirectives & Symbol::Import) != 0 && FID.isValid()) {
   auto [It, Inserted] = FileToContainsImportsOrObjC.try_emplace(FID);
   if (Inserted)
 It->second = FilesWithObjCConstructs.contains(FID) ||
diff --git a/clang-tools-extra/clangd/test/GH75115.test 
b/clang-tools-extra/clangd/test/GH75115.test
index 030392f1d69b30..dc86f5b9a6cee0 100644
--- a/clang-tools-extra/clangd/test/GH75115.test
+++ b/clang-tools-extra/clangd/test/GH75115.test
@@ -1,12 +1,15 @@
 // RUN: rm -rf %t.dir && mkdir -p %t.dir
 // RUN: echo '[{"directory": "%/t.dir", "command": "clang 
--target=x86_64-pc-windows-msvc -x c GH75115.test", "file": "GH75115.test"}]' > 
%t.dir/compile_commands.json
-// RUN: not --crash clangd -enable-config=0 --compile-commands-dir=%t.dir 
-check=%s 2>&1 | FileCheck -strict-whitespace %s
-
-// FIXME: Crashes
+// RUN: clangd -enable-config=0 --compile-commands-dir=%t.dir -check=%s 2>&1 | 
FileCheck -strict-whitespace %s
 
 // CHECK: Building preamble...
 // CHECK-NEXT: Built preamble
 // CHECK-NEXT: Indexing headers...
-// CHECK-NEXT: !KeyInfoT::isEqual(Val, EmptyKey) && !KeyInfoT::isEqual(Val, 
TombstoneKey) && "Empty/Tombstone value shouldn't be inserted into map!"
+// CHECK-NEXT: Building AST...
+// CHECK-NEXT: Indexing AST...
+// CHECK-NEXT: Building inlay hints
+// CHECK-NEXT: semantic highlighting
+// CHECK-NEXT: Testing features at each token
+// CHECK-NEXT: All checks completed, 0 errors
 
 #define assert

___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [libcxx] [clang] Finish implementation of P0522 (PR #96023)

2024-08-28 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/96023

>From 84f988ee7c2d8fc5f777bc98850f6ab126fb3b71 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Mon, 17 Jun 2024 21:39:08 -0300
Subject: [PATCH] [clang] Finish implementation of P0522

This finishes the clang implementation of P0522, getting rid
of the fallback to the old, pre-P0522 rules.

Before this patch, when partial ordering template template parameters,
we would perform, in order:
* If the old rules would match, we would accept it. Otherwise, don't
  generate diagnostics yet.
* If the new rules would match, just accept it. Otherwise, don't
  generate any diagnostics yet again.
* Apply the old rules again, this time with diagnostics.

This situation was far from ideal, as we would sometimes:
* Accept some things we shouldn't.
* Reject some things we shouldn't.
* Only diagnose rejection in terms of the old rules.

With this patch, we apply the P0522 rules throughout.

This needed to extend template argument deduction in order
to accept the historial rule for TTP matching pack parameter to non-pack
arguments.
This change also makes us accept some combinations of historical and P0522
allowances we wouldn't before.

It also fixes a bunch of bugs that were documented in the test suite,
which I am not sure there are issues already created for them.

This causes a lot of changes to the way these failures are diagnosed,
with related test suite churn.

The problem here is that the old rules were very simple and
non-recursive, making it easy to provide customized diagnostics,
and to keep them consistent with each other.

The new rules are a lot more complex and rely on template argument
deduction, substitutions, and they are recursive.

The approach taken here is to mostly rely on existing diagnostics,
and create a new instantiation context that keeps track of this context.

So for example when a substitution failure occurs, we use the error
produced there unmodified, and just attach notes to it explaining
that it occurred in the context of partial ordering this template
argument against that template parameter.

This diverges from the old diagnostics, which would lead with an
error pointing to the template argument, explain the problem
in subsequent notes, and produce a final note pointing to the parameter.
---
 clang/docs/ReleaseNotes.rst   |  10 +
 .../clang/Basic/DiagnosticSemaKinds.td|   7 +
 clang/include/clang/Sema/Sema.h   |  14 +-
 clang/lib/Frontend/FrontendActions.cpp|   2 +
 clang/lib/Sema/SemaTemplate.cpp   |  94 ++---
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 353 +-
 clang/lib/Sema/SemaTemplateInstantiate.cpp|  15 +
 .../temp/temp.arg/temp.arg.template/p3-0x.cpp |  31 +-
 clang/test/CXX/temp/temp.param/p12.cpp|  21 +-
 clang/test/Modules/cxx-templates.cpp  |  15 +-
 clang/test/SemaCXX/make_integer_seq.cpp   |   5 +-
 clang/test/SemaTemplate/cwg2398.cpp   | 138 ++-
 clang/test/SemaTemplate/temp_arg_nontype.cpp  |  46 ++-
 clang/test/SemaTemplate/temp_arg_template.cpp |  38 +-
 .../SemaTemplate/temp_arg_template_p0522.cpp  |  82 ++--
 .../Templight/templight-empty-entries-fix.cpp |  12 +
 .../templight-prior-template-arg.cpp  |  33 +-
 .../type_traits/is_specialization.verify.cpp  |   2 +-
 18 files changed, 641 insertions(+), 277 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2639fe3270200d..3826a19e28a666 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -129,6 +129,10 @@ C++23 Feature Support
 C++20 Feature Support
 ^
 
+C++17 Feature Support
+^
+- The implementation of the relaxed template template argument matching rules 
is
+  more complete and reliable, and should provide more accurate diagnostics.
 
 Resolutions to C++ Defect Reports
 ^
@@ -255,6 +259,10 @@ Improvements to Clang's diagnostics
 
 - Clang now diagnoses when the result of a [[nodiscard]] function is discarded 
after being cast in C. Fixes #GH104391.
 
+- Clang now properly explains the reason a template template argument failed to
+  match a template template parameter, in terms of the C++17 relaxed matching 
rules
+  instead of the old ones.
+
 - Don't emit duplicated dangling diagnostics. (#GH93386).
 
 - Improved diagnostic when trying to befriend a concept. (#GH45182).
@@ -322,6 +330,8 @@ Bug Fixes to C++ Support
 - Correctly check constraints of explicit instantiations of member functions. 
(#GH46029)
 - When performing partial ordering of function templates, clang now checks that
   the deduction was consistent. Fixes (#GH18291).
+- Fixes to several issues in partial ordering of template template parameters, 
which
+  were documented in the test suite.
 - Fixed an assertion failure about a constraint of a friend function template 
references to a value with greater
   

[llvm-branch-commits] [clang] release/19.x: Revert "[clang] fix broken canonicalization of DeducedTemplateSpeciatizationType (#95202)" (PR #106516)

2024-08-29 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov approved this pull request.


https://github.com/llvm/llvm-project/pull/106516
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [libcxx] [clang] Finish implementation of P0522 (PR #96023)

2024-09-04 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/96023

>From da2a66a8b7105a1cbfc5bd98c7b41addc6ec543b Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Mon, 17 Jun 2024 21:39:08 -0300
Subject: [PATCH] [clang] Finish implementation of P0522

This finishes the clang implementation of P0522, getting rid
of the fallback to the old, pre-P0522 rules.

Before this patch, when partial ordering template template parameters,
we would perform, in order:
* If the old rules would match, we would accept it. Otherwise, don't
  generate diagnostics yet.
* If the new rules would match, just accept it. Otherwise, don't
  generate any diagnostics yet again.
* Apply the old rules again, this time with diagnostics.

This situation was far from ideal, as we would sometimes:
* Accept some things we shouldn't.
* Reject some things we shouldn't.
* Only diagnose rejection in terms of the old rules.

With this patch, we apply the P0522 rules throughout.

This needed to extend template argument deduction in order
to accept the historial rule for TTP matching pack parameter to non-pack
arguments.
This change also makes us accept some combinations of historical and P0522
allowances we wouldn't before.

It also fixes a bunch of bugs that were documented in the test suite,
which I am not sure there are issues already created for them.

This causes a lot of changes to the way these failures are diagnosed,
with related test suite churn.

The problem here is that the old rules were very simple and
non-recursive, making it easy to provide customized diagnostics,
and to keep them consistent with each other.

The new rules are a lot more complex and rely on template argument
deduction, substitutions, and they are recursive.

The approach taken here is to mostly rely on existing diagnostics,
and create a new instantiation context that keeps track of this context.

So for example when a substitution failure occurs, we use the error
produced there unmodified, and just attach notes to it explaining
that it occurred in the context of partial ordering this template
argument against that template parameter.

This diverges from the old diagnostics, which would lead with an
error pointing to the template argument, explain the problem
in subsequent notes, and produce a final note pointing to the parameter.
---
 clang/docs/ReleaseNotes.rst   |  10 +
 .../clang/Basic/DiagnosticSemaKinds.td|   7 +
 clang/include/clang/Sema/Sema.h   |  14 +-
 clang/lib/Frontend/FrontendActions.cpp|   2 +
 clang/lib/Sema/SemaTemplate.cpp   |  94 ++---
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 353 +-
 clang/lib/Sema/SemaTemplateInstantiate.cpp|  15 +
 .../temp/temp.arg/temp.arg.template/p3-0x.cpp |  31 +-
 clang/test/CXX/temp/temp.param/p12.cpp|  21 +-
 clang/test/Modules/cxx-templates.cpp  |  15 +-
 clang/test/SemaCXX/make_integer_seq.cpp   |   5 +-
 clang/test/SemaTemplate/cwg2398.cpp   | 160 +++-
 clang/test/SemaTemplate/temp_arg_nontype.cpp  |  46 ++-
 clang/test/SemaTemplate/temp_arg_template.cpp |  38 +-
 .../SemaTemplate/temp_arg_template_p0522.cpp  |  82 ++--
 .../Templight/templight-empty-entries-fix.cpp |  12 +
 .../templight-prior-template-arg.cpp  |  33 +-
 .../type_traits/is_specialization.verify.cpp  |   2 +-
 18 files changed, 663 insertions(+), 277 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2639fe3270200d..3826a19e28a666 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -129,6 +129,10 @@ C++23 Feature Support
 C++20 Feature Support
 ^
 
+C++17 Feature Support
+^
+- The implementation of the relaxed template template argument matching rules 
is
+  more complete and reliable, and should provide more accurate diagnostics.
 
 Resolutions to C++ Defect Reports
 ^
@@ -255,6 +259,10 @@ Improvements to Clang's diagnostics
 
 - Clang now diagnoses when the result of a [[nodiscard]] function is discarded 
after being cast in C. Fixes #GH104391.
 
+- Clang now properly explains the reason a template template argument failed to
+  match a template template parameter, in terms of the C++17 relaxed matching 
rules
+  instead of the old ones.
+
 - Don't emit duplicated dangling diagnostics. (#GH93386).
 
 - Improved diagnostic when trying to befriend a concept. (#GH45182).
@@ -322,6 +330,8 @@ Bug Fixes to C++ Support
 - Correctly check constraints of explicit instantiations of member functions. 
(#GH46029)
 - When performing partial ordering of function templates, clang now checks that
   the deduction was consistent. Fixes (#GH18291).
+- Fixes to several issues in partial ordering of template template parameters, 
which
+  were documented in the test suite.
 - Fixed an assertion failure about a constraint of a friend function template 
references to a value with greater
  

[llvm-branch-commits] [clang] [clang] Finish implementation of P0522 (PR #96023)

2024-09-04 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/96023

>From 958703dfc41c6aa186e5129dc804b532b48ef00e Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Mon, 17 Jun 2024 21:39:08 -0300
Subject: [PATCH] [clang] Finish implementation of P0522

This finishes the clang implementation of P0522, getting rid
of the fallback to the old, pre-P0522 rules.

Before this patch, when partial ordering template template parameters,
we would perform, in order:
* If the old rules would match, we would accept it. Otherwise, don't
  generate diagnostics yet.
* If the new rules would match, just accept it. Otherwise, don't
  generate any diagnostics yet again.
* Apply the old rules again, this time with diagnostics.

This situation was far from ideal, as we would sometimes:
* Accept some things we shouldn't.
* Reject some things we shouldn't.
* Only diagnose rejection in terms of the old rules.

With this patch, we apply the P0522 rules throughout.

This needed to extend template argument deduction in order
to accept the historial rule for TTP matching pack parameter to non-pack
arguments.
This change also makes us accept some combinations of historical and P0522
allowances we wouldn't before.

It also fixes a bunch of bugs that were documented in the test suite,
which I am not sure there are issues already created for them.

This causes a lot of changes to the way these failures are diagnosed,
with related test suite churn.

The problem here is that the old rules were very simple and
non-recursive, making it easy to provide customized diagnostics,
and to keep them consistent with each other.

The new rules are a lot more complex and rely on template argument
deduction, substitutions, and they are recursive.

The approach taken here is to mostly rely on existing diagnostics,
and create a new instantiation context that keeps track of this context.

So for example when a substitution failure occurs, we use the error
produced there unmodified, and just attach notes to it explaining
that it occurred in the context of partial ordering this template
argument against that template parameter.

This diverges from the old diagnostics, which would lead with an
error pointing to the template argument, explain the problem
in subsequent notes, and produce a final note pointing to the parameter.
---
 clang/docs/ReleaseNotes.rst   |  10 +
 .../clang/Basic/DiagnosticSemaKinds.td|   7 +
 clang/include/clang/Sema/Sema.h   |  14 +-
 clang/lib/Frontend/FrontendActions.cpp|   2 +
 clang/lib/Sema/SemaTemplate.cpp   |  94 ++---
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 353 +-
 clang/lib/Sema/SemaTemplateInstantiate.cpp|  15 +
 .../temp/temp.arg/temp.arg.template/p3-0x.cpp |  31 +-
 clang/test/CXX/temp/temp.param/p12.cpp|  21 +-
 clang/test/Modules/cxx-templates.cpp  |  15 +-
 clang/test/SemaCXX/make_integer_seq.cpp   |   5 +-
 clang/test/SemaTemplate/cwg2398.cpp   | 160 +++-
 clang/test/SemaTemplate/temp_arg_nontype.cpp  |  26 +-
 clang/test/SemaTemplate/temp_arg_template.cpp |  38 +-
 .../SemaTemplate/temp_arg_template_p0522.cpp  |  82 ++--
 .../Templight/templight-empty-entries-fix.cpp |  12 +
 .../templight-prior-template-arg.cpp  |  33 +-
 17 files changed, 652 insertions(+), 266 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index f2ad84ea80b0da..4274848d154806 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -129,6 +129,10 @@ C++23 Feature Support
 C++20 Feature Support
 ^
 
+C++17 Feature Support
+^
+- The implementation of the relaxed template template argument matching rules 
is
+  more complete and reliable, and should provide more accurate diagnostics.
 
 Resolutions to C++ Defect Reports
 ^
@@ -260,6 +264,10 @@ Improvements to Clang's diagnostics
 
 - Clang now diagnoses when the result of a [[nodiscard]] function is discarded 
after being cast in C. Fixes #GH104391.
 
+- Clang now properly explains the reason a template template argument failed to
+  match a template template parameter, in terms of the C++17 relaxed matching 
rules
+  instead of the old ones.
+
 - Don't emit duplicated dangling diagnostics. (#GH93386).
 
 - Improved diagnostic when trying to befriend a concept. (#GH45182).
@@ -341,6 +349,8 @@ Bug Fixes to C++ Support
 - Correctly check constraints of explicit instantiations of member functions. 
(#GH46029)
 - When performing partial ordering of function templates, clang now checks that
   the deduction was consistent. Fixes (#GH18291).
+- Fixes to several issues in partial ordering of template template parameters, 
which
+  were documented in the test suite.
 - Fixed an assertion failure about a constraint of a friend function template 
references to a value with greater
   template depth than the friend function template. (#GH98

[llvm-branch-commits] [clang] [clang] CWG2398: improve overload resolution backwards compat (PR #107350)

2024-09-04 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/107350

With this change, we discriminate if the primary template and which partial 
specializations would have participated in overload resolution prior to P0522 
changes.

We collect those in an initial set. If this set is not empty, or the primary 
template would have matched, we proceed with this set as the candidates for 
overload resolution.

Otherwise, we build a new overload set with everything else, and proceed as 
usual.

>From 7de7d24ddbd2a932f045c1a4455126388978d21c Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Thu, 5 Sep 2024 00:25:40 -0300
Subject: [PATCH] [clang] CWG2398: improve overload resolution backwards compat

With this change, we discriminate if the primary template and which partial
specializations would have participated in overload resolution prior to
P0522 changes.

We collect those in an initial set. If this set is not empty, or the
primary template would have matched, we proceed with this set as the
candidates for overload resolution.

Otherwise, we build a new overload set with everything else, and proceed
as usual.
---
 clang/include/clang/Sema/Sema.h  | 14 ---
 clang/include/clang/Sema/TemplateDeduction.h | 13 ++
 clang/lib/Sema/SemaLookup.cpp|  3 +-
 clang/lib/Sema/SemaTemplate.cpp  | 44 
 clang/lib/Sema/SemaTemplateDeduction.cpp | 43 +--
 clang/lib/Sema/SemaTemplateInstantiate.cpp   | 24 ++-
 clang/test/SemaTemplate/cwg2398.cpp  |  6 +--
 7 files changed, 95 insertions(+), 52 deletions(-)

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index f11d6bc6f865a8..0338641d6c461e 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -11703,7 +11703,8 @@ class Sema final : public SemaBase {
 SourceLocation RAngleLoc, unsigned ArgumentPackIndex,
 SmallVectorImpl &SugaredConverted,
 SmallVectorImpl &CanonicalConverted,
-CheckTemplateArgumentKind CTAK);
+CheckTemplateArgumentKind CTAK,
+bool *MatchedPackOnParmToNonPackOnArg);
 
   /// Check that the given template arguments can be provided to
   /// the given template, converting the arguments along the way.
@@ -11750,7 +11751,8 @@ class Sema final : public SemaBase {
   SmallVectorImpl &SugaredConverted,
   SmallVectorImpl &CanonicalConverted,
   bool UpdateArgsWithConversions = true,
-  bool *ConstraintsNotSatisfied = nullptr, bool PartialOrderingTTP = 
false);
+  bool *ConstraintsNotSatisfied = nullptr, bool PartialOrderingTTP = false,
+  bool *MatchedPackOnParmToNonPackOnArg = nullptr);
 
   bool CheckTemplateTypeArgument(
   TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg,
@@ -11784,7 +11786,8 @@ class Sema final : public SemaBase {
   /// It returns true if an error occurred, and false otherwise.
   bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
  TemplateParameterList *Params,
- TemplateArgumentLoc &Arg, bool IsDeduced);
+ TemplateArgumentLoc &Arg, bool IsDeduced,
+ bool *MatchedPackOnParmToNonPackOnArg);
 
   void NoteTemplateLocation(const NamedDecl &Decl,
 std::optional ParamRange = {});
@@ -12485,7 +12488,7 @@ class Sema final : public SemaBase {
   bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
   TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg,
   const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
-  bool IsDeduced);
+  bool IsDeduced, bool *MatchedPackOnParmToNonPackOnArg);
 
   /// Mark which template parameters are used in a given expression.
   ///
@@ -13484,7 +13487,8 @@ class Sema final : public SemaBase {
   bool InstantiateClassTemplateSpecialization(
   SourceLocation PointOfInstantiation,
   ClassTemplateSpecializationDecl *ClassTemplateSpec,
-  TemplateSpecializationKind TSK, bool Complain = true);
+  TemplateSpecializationKind TSK, bool Complain = true,
+  bool PrimaryHasMatchedPackOnParmToNonPackOnArg = false);
 
   /// Instantiates the definitions of all of the member
   /// of the given class, which is an instantiation of a class template
diff --git a/clang/include/clang/Sema/TemplateDeduction.h 
b/clang/include/clang/Sema/TemplateDeduction.h
index 28b014fd84e4b3..9c12eef5c42a06 100644
--- a/clang/include/clang/Sema/TemplateDeduction.h
+++ b/clang/include/clang/Sema/TemplateDeduction.h
@@ -51,6 +51,11 @@ class TemplateDeductionInfo {
   /// Have we suppressed an error during deduction?
   bool HasSFINAEDiagnostic = false;
 
+  /// Have we matched any packs on the parameter side, versus any non-packs on
+  /// the argu

[llvm-branch-commits] [clang] release/19.x: [Clang][Concepts] Fix the constraint equivalence checking involving parameter packs (#102131) (PR #106043)

2024-09-16 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov approved this pull request.


https://github.com/llvm/llvm-project/pull/106043
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] 4ae3353 - [clang] fix concepts crash on substitution failure during normalization

2021-08-03 Thread Matheus Izvekov via llvm-branch-commits

Author: Matheus Izvekov
Date: 2021-08-03T12:53:18+02:00
New Revision: 4ae33534bd8c52c4f054bb4676632c37f49f56b2

URL: 
https://github.com/llvm/llvm-project/commit/4ae33534bd8c52c4f054bb4676632c37f49f56b2
DIFF: 
https://github.com/llvm/llvm-project/commit/4ae33534bd8c52c4f054bb4676632c37f49f56b2.diff

LOG: [clang] fix concepts crash on substitution failure during normalization

When substitution failed on the first constrained template argument (but
only the first), we would assert / crash. Checking for failure was only
being performed from the second constraint on.

This changes it so the checking is performed in that case,
and the code is also now simplified a little bit to hopefully
avoid this confusion.

Signed-off-by: Matheus Izvekov 

Reviewed By: rsmith

Differential Revision: https://reviews.llvm.org/D106907

Added: 


Modified: 
clang/lib/Sema/SemaConcept.cpp
clang/test/CXX/temp/temp.constr/temp.constr.normal/p1.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index f2c70d0a56efb..931c9e3e2738d 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -742,22 +742,15 @@ Optional
 NormalizedConstraint::fromConstraintExprs(Sema &S, NamedDecl *D,
   ArrayRef E) {
   assert(E.size() != 0);
-  auto First = fromConstraintExpr(S, D, E[0]);
-  if (E.size() == 1)
-return First;
-  auto Second = fromConstraintExpr(S, D, E[1]);
-  if (!Second)
+  auto Conjunction = fromConstraintExpr(S, D, E[0]);
+  if (!Conjunction)
 return None;
-  llvm::Optional Conjunction;
-  Conjunction.emplace(S.Context, std::move(*First), std::move(*Second),
-  CCK_Conjunction);
-  for (unsigned I = 2; I < E.size(); ++I) {
+  for (unsigned I = 1; I < E.size(); ++I) {
 auto Next = fromConstraintExpr(S, D, E[I]);
 if (!Next)
-  return llvm::Optional{};
-NormalizedConstraint NewConjunction(S.Context, std::move(*Conjunction),
+  return None;
+*Conjunction = NormalizedConstraint(S.Context, std::move(*Conjunction),
 std::move(*Next), CCK_Conjunction);
-*Conjunction = std::move(NewConjunction);
   }
   return Conjunction;
 }

diff  --git a/clang/test/CXX/temp/temp.constr/temp.constr.normal/p1.cpp 
b/clang/test/CXX/temp/temp.constr/temp.constr.normal/p1.cpp
index 153d4a56bea31..2134968101470 100644
--- a/clang/test/CXX/temp/temp.constr/temp.constr.normal/p1.cpp
+++ b/clang/test/CXX/temp/temp.constr/temp.constr.normal/p1.cpp
@@ -67,3 +67,18 @@ namespace non_type_pack {
 
   static_assert((foo<1>(), true));
 }
+
+namespace PR47174 {
+// This checks that we don't crash with a failed substitution on the first 
constrained argument when
+// performing normalization.
+template 
+requires true struct S3; // expected-note {{template is declared here}}
+template 
+requires true struct S3; // expected-error {{class template partial 
specialization is not more specialized than the primary template}}
+
+// Same as above, for the second position (but this was already working).
+template 
+requires true struct S4; // expected-note {{template is declared here}}
+template 
+requires true struct S4; // expected-error {{class template partial 
specialization is not more specialized than the primary template}}
+} // namespace PR47174



___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] CWG2398: improve overload resolution backwards compat (PR #107350)

2024-10-09 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov edited 
https://github.com/llvm/llvm-project/pull/107350
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] WIP: Implement TTP 'reversed' pack matching for deduced function template calls. (PR #111457)

2024-10-07 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/111457

Clang previously missed implementing the historical rule 
https://eel.is/c++draft/temp.arg.template#3.sentence-3 for deduced function 
template calls.

This patch implements this rule, but only on the
'frelaxed-template-template-args' mode, which is
currently the default.

As its negation is deprecated and will be removed soon, this patch does not 
change the implementation in that case.

WIP, as it's missing some changes which will help in not breaking compatibility 
in overload resolution.

>From 1e8fbca963bb13d38ee6f9907ca8e5039bd08a8d Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Sat, 5 Oct 2024 21:56:51 -0300
Subject: [PATCH] [clang] WIP: Implement TTP 'reversed' pack matching for
 deduced function template calls.

Clang previously missed implementing the historical rule
https://eel.is/c++draft/temp.arg.template#3.sentence-3
for deduced function template calls.

This patch implements this rule, but only on the
'frelaxed-template-template-args' patch, which is
currently the default mode.

As it's negation is deprecated and will be removed soon,
this patch does not change the implementation there.

WIP, as it's missing some changes which will help in not breaking
compatibility in overload resolution.
---
 clang/include/clang/Sema/Sema.h  | 14 +++--
 clang/lib/Sema/SemaLookup.cpp|  1 +
 clang/lib/Sema/SemaOverload.cpp  |  5 +-
 clang/lib/Sema/SemaTemplate.cpp  | 23 +++
 clang/lib/Sema/SemaTemplateDeduction.cpp | 76 ++--
 clang/test/SemaTemplate/cwg2398.cpp  | 34 +++
 6 files changed, 102 insertions(+), 51 deletions(-)

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 5d38862ce59f0c..05857884fdc2e1 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -11636,7 +11636,7 @@ class Sema final : public SemaBase {
 SourceLocation RAngleLoc, unsigned ArgumentPackIndex,
 SmallVectorImpl &SugaredConverted,
 SmallVectorImpl &CanonicalConverted,
-CheckTemplateArgumentKind CTAK,
+CheckTemplateArgumentKind CTAK, bool PartialOrdering,
 bool *MatchedPackOnParmToNonPackOnArg);
 
   /// Check that the given template arguments can be provided to
@@ -11719,7 +11719,8 @@ class Sema final : public SemaBase {
   /// It returns true if an error occurred, and false otherwise.
   bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
  TemplateParameterList *Params,
- TemplateArgumentLoc &Arg, bool IsDeduced,
+ TemplateArgumentLoc &Arg,
+ bool PartialOrdering,
  bool *MatchedPackOnParmToNonPackOnArg);
 
   void NoteTemplateLocation(const NamedDecl &Decl,
@@ -12231,8 +12232,8 @@ class Sema final : public SemaBase {
   SmallVectorImpl &Deduced,
   unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
   sema::TemplateDeductionInfo &Info,
-  SmallVectorImpl const *OriginalCallArgs = nullptr,
-  bool PartialOverloading = false,
+  SmallVectorImpl const *OriginalCallArgs,
+  bool PartialOverloading, bool PartialOrdering,
   llvm::function_ref CheckNonDependent = [] { return false; });
 
   /// Perform template argument deduction from a function call
@@ -12266,7 +12267,8 @@ class Sema final : public SemaBase {
   TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef Args,
   FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
   bool PartialOverloading, bool AggregateDeductionCandidate,
-  QualType ObjectType, Expr::Classification ObjectClassification,
+  bool PartialOrdering, QualType ObjectType,
+  Expr::Classification ObjectClassification,
   llvm::function_ref)> CheckNonDependent);
 
   /// Deduce template arguments when taking the address of a function
@@ -12421,7 +12423,7 @@ class Sema final : public SemaBase {
   bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
   TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg,
   const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
-  bool IsDeduced, bool *MatchedPackOnParmToNonPackOnArg);
+  bool PartialOrdering, bool *MatchedPackOnParmToNonPackOnArg);
 
   /// Mark which template parameters are used in a given expression.
   ///
diff --git a/clang/lib/Sema/SemaLookup.cpp b/clang/lib/Sema/SemaLookup.cpp
index 31422c213ac249..60fa195221c938 100644
--- a/clang/lib/Sema/SemaLookup.cpp
+++ b/clang/lib/Sema/SemaLookup.cpp
@@ -3667,6 +3667,7 @@ Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
   if (CheckTemplateArgument(
   Params->getParam(0), Arg, FD, R.getNameLoc(), 

[llvm-branch-commits] [clang] [clang] WIP: Implement TTP 'reversed' pack matching for deduced function template calls. (PR #111457)

2024-10-07 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov edited 
https://github.com/llvm/llvm-project/pull/111457
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] release/19.x: [Clang] Remove the special-casing for RequiresExprBodyDecl in BuildResolvedCallExpr() after fd87d765c0 (#111277) (PR #111324)

2024-10-06 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov approved this pull request.


https://github.com/llvm/llvm-project/pull/111324
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] Implement TTP P0522 pack matching for deduced function template calls. (PR #111457)

2024-10-09 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/111457

>From 1975bae70df78c437d10a361a15aca27f218460e Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Sat, 5 Oct 2024 21:56:51 -0300
Subject: [PATCH] [clang] Implement TTP 'reversed' pack matching for deduced
 function template calls.

Clang previously missed implementing P0522 pack matching
for deduced function template calls.
---
 clang/docs/ReleaseNotes.rst  |  4 ++
 clang/include/clang/Sema/Overload.h  |  7 +-
 clang/include/clang/Sema/Sema.h  | 23 ---
 clang/lib/Sema/SemaLookup.cpp|  1 +
 clang/lib/Sema/SemaOverload.cpp  | 50 +--
 clang/lib/Sema/SemaTemplate.cpp  | 23 +++
 clang/lib/Sema/SemaTemplateDeduction.cpp | 76 --
 clang/test/SemaTemplate/cwg2398.cpp  | 81 
 8 files changed, 193 insertions(+), 72 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 153901fb3b1ed7..71967b1d27fbad 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -151,6 +151,10 @@ C++ Language Changes
 - The builtin type alias ``__builtin_common_type`` has been added to improve 
the
   performance of ``std::common_type``.
 
+- When matching a template to a template template parameter in the context of 
a deduced
+  function template call, clang now implements ``[temp.arg.template]p3.3``,
+  allowing a pack on the parameter to match a non-pack argument.
+
 C++2c Feature Support
 ^
 
diff --git a/clang/include/clang/Sema/Overload.h 
b/clang/include/clang/Sema/Overload.h
index c716a25bb673b8..8b7480636c36e7 100644
--- a/clang/include/clang/Sema/Overload.h
+++ b/clang/include/clang/Sema/Overload.h
@@ -925,6 +925,8 @@ class Sema;
 
 bool TookAddressOfOverload : 1;
 
+bool HasMatchedPackOnParmToNonPackOnArg : 1;
+
 /// True if the candidate was found using ADL.
 CallExpr::ADLCallKind IsADLCandidate : 1;
 
@@ -999,8 +1001,9 @@ class Sema;
 friend class OverloadCandidateSet;
 OverloadCandidate()
 : IsSurrogate(false), IgnoreObjectArgument(false),
-  TookAddressOfOverload(false), IsADLCandidate(CallExpr::NotADL),
-  RewriteKind(CRK_None) {}
+  TookAddressOfOverload(false),
+  HasMatchedPackOnParmToNonPackOnArg(false),
+  IsADLCandidate(CallExpr::NotADL), RewriteKind(CRK_None) {}
   };
 
   /// OverloadCandidateSet - A set of overload candidates, used in C++
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index d99a0c7af4b0ca..5f045860acb7b2 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -10132,7 +10132,8 @@ class Sema final : public SemaBase {
   ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
   ConversionSequenceList EarlyConversions = std::nullopt,
   OverloadCandidateParamOrder PO = {},
-  bool AggregateCandidateDeduction = false);
+  bool AggregateCandidateDeduction = false,
+  bool HasMatchedPackOnParmToNonPackOnArg = false);
 
   /// Add all of the function declarations in the given function set to
   /// the overload candidate set.
@@ -10167,7 +10168,8 @@ class Sema final : public SemaBase {
  bool SuppressUserConversions = false,
  bool PartialOverloading = false,
  ConversionSequenceList EarlyConversions = std::nullopt,
- OverloadCandidateParamOrder PO = {});
+ OverloadCandidateParamOrder PO = {},
+ bool HasMatchedPackOnParmToNonPackOnArg = false);
 
   /// Add a C++ member function template as a candidate to the candidate
   /// set, using template argument deduction to produce an appropriate member
@@ -10213,7 +10215,8 @@ class Sema final : public SemaBase {
   CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
   CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
   OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
-  bool AllowExplicit, bool AllowResultConversion = true);
+  bool AllowExplicit, bool AllowResultConversion = true,
+  bool HasMatchedPackOnParmToNonPackOnArg = false);
 
   /// Adds a conversion function template specialization
   /// candidate to the overload set, using template argument deduction
@@ -11637,7 +11640,7 @@ class Sema final : public SemaBase {
 SourceLocation RAngleLoc, unsigned ArgumentPackIndex,
 SmallVectorImpl &SugaredConverted,
 SmallVectorImpl &CanonicalConverted,
-CheckTemplateArgumentKind CTAK,
+CheckTemplateArgumentKind CTAK, bool PartialOrdering,
 bool *MatchedPackOnParmToNonPackOnArg);
 
   /// Check that the given template arguments can be provided to
@@ -11720,7 +11723,8 @@ class Sema final : public SemaBase {
   //

[llvm-branch-commits] [clang] [clang] CWG2398: improve overload resolution backwards compat (PR #107350)

2024-10-09 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/107350

>From aa016046df11993dff967eff970530c73ecf849e Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Thu, 5 Sep 2024 00:25:40 -0300
Subject: [PATCH] [clang] CWG2398: improve overload resolution backwards compat

With this change, we discriminate if the primary template and which partial
specializations would have participated in overload resolution prior to
P0522 changes.

We collect those in an initial set. If this set is not empty, or the
primary template would have matched, we proceed with this set as the
candidates for overload resolution.

Otherwise, we build a new overload set with everything else, and proceed
as usual.
---
 clang/docs/ReleaseNotes.rst  |  3 +-
 clang/include/clang/Sema/Sema.h  | 14 ---
 clang/include/clang/Sema/TemplateDeduction.h | 13 ++
 clang/lib/Sema/SemaLookup.cpp|  3 +-
 clang/lib/Sema/SemaTemplate.cpp  | 44 
 clang/lib/Sema/SemaTemplateDeduction.cpp | 43 +--
 clang/lib/Sema/SemaTemplateInstantiate.cpp   | 24 ++-
 clang/test/SemaTemplate/cwg2398.cpp  |  6 +--
 8 files changed, 97 insertions(+), 53 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7270e6898dbc7f..153901fb3b1ed7 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -204,7 +204,8 @@ Resolutions to C++ Defect Reports
   (`CWG2351: void{} `_).
 
 - Clang now has improved resolution to CWG2398, allowing class templates to 
have
-  default arguments deduced when partial ordering.
+  default arguments deduced when partial ordering, and better backwards 
compatibility
+  in overload resolution.
 
 - Clang now allows comparing unequal object pointers that have been cast to 
``void *``
   in constant expressions. These comparisons always worked in non-constant 
expressions.
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 043456438b6d03..d99a0c7af4b0ca 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -11637,7 +11637,8 @@ class Sema final : public SemaBase {
 SourceLocation RAngleLoc, unsigned ArgumentPackIndex,
 SmallVectorImpl &SugaredConverted,
 SmallVectorImpl &CanonicalConverted,
-CheckTemplateArgumentKind CTAK);
+CheckTemplateArgumentKind CTAK,
+bool *MatchedPackOnParmToNonPackOnArg);
 
   /// Check that the given template arguments can be provided to
   /// the given template, converting the arguments along the way.
@@ -11684,7 +11685,8 @@ class Sema final : public SemaBase {
   SmallVectorImpl &SugaredConverted,
   SmallVectorImpl &CanonicalConverted,
   bool UpdateArgsWithConversions = true,
-  bool *ConstraintsNotSatisfied = nullptr, bool PartialOrderingTTP = 
false);
+  bool *ConstraintsNotSatisfied = nullptr, bool PartialOrderingTTP = false,
+  bool *MatchedPackOnParmToNonPackOnArg = nullptr);
 
   bool CheckTemplateTypeArgument(
   TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg,
@@ -11718,7 +11720,8 @@ class Sema final : public SemaBase {
   /// It returns true if an error occurred, and false otherwise.
   bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
  TemplateParameterList *Params,
- TemplateArgumentLoc &Arg, bool IsDeduced);
+ TemplateArgumentLoc &Arg, bool IsDeduced,
+ bool *MatchedPackOnParmToNonPackOnArg);
 
   void NoteTemplateLocation(const NamedDecl &Decl,
 std::optional ParamRange = {});
@@ -12419,7 +12422,7 @@ class Sema final : public SemaBase {
   bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
   TemplateParameterList *PParam, TemplateDecl *PArg, TemplateDecl *AArg,
   const DefaultArguments &DefaultArgs, SourceLocation ArgLoc,
-  bool IsDeduced);
+  bool IsDeduced, bool *MatchedPackOnParmToNonPackOnArg);
 
   /// Mark which template parameters are used in a given expression.
   ///
@@ -13410,7 +13413,8 @@ class Sema final : public SemaBase {
   bool InstantiateClassTemplateSpecialization(
   SourceLocation PointOfInstantiation,
   ClassTemplateSpecializationDecl *ClassTemplateSpec,
-  TemplateSpecializationKind TSK, bool Complain = true);
+  TemplateSpecializationKind TSK, bool Complain = true,
+  bool PrimaryHasMatchedPackOnParmToNonPackOnArg = false);
 
   /// Instantiates the definitions of all of the member
   /// of the given class, which is an instantiation of a class template
diff --git a/clang/include/clang/Sema/TemplateDeduction.h 
b/clang/include/clang/Sema/TemplateDeduction.h
index 28b0

[llvm-branch-commits] [clang] [clang] Implement TTP P0522 pack matching for deduced function template calls. (PR #111457)

2024-10-09 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov edited 
https://github.com/llvm/llvm-project/pull/111457
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] Implement TTP P0522 pack matching for deduced function template calls. (PR #111457)

2024-10-09 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov edited 
https://github.com/llvm/llvm-project/pull/111457
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] Implement TTP P0522 pack matching for deduced function template calls. (PR #111457)

2024-10-09 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/111457

>From 0df57333178d360c441956cc2509f5eca4434c0e Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Sat, 5 Oct 2024 21:56:51 -0300
Subject: [PATCH] [clang] Implement TTP 'reversed' pack matching for deduced
 function template calls.

Clang previously missed implementing P0522 pack matching
for deduced function template calls.
---
 clang/docs/ReleaseNotes.rst  |  4 ++
 clang/include/clang/Sema/Overload.h  |  7 +-
 clang/include/clang/Sema/Sema.h  | 23 ---
 clang/lib/Sema/SemaLookup.cpp|  1 +
 clang/lib/Sema/SemaOverload.cpp  | 50 +--
 clang/lib/Sema/SemaTemplate.cpp  | 23 +++
 clang/lib/Sema/SemaTemplateDeduction.cpp | 76 --
 clang/test/SemaTemplate/cwg2398.cpp  | 81 
 8 files changed, 193 insertions(+), 72 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 153901fb3b1ed7..1324b28d84c3d0 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -151,6 +151,10 @@ C++ Language Changes
 - The builtin type alias ``__builtin_common_type`` has been added to improve 
the
   performance of ``std::common_type``.
 
+- When matching a template to a template template parameter in the context of 
a deduced
+  function template call, clang now implements P0522 pack rules,
+  allowing a non-pack parameter to match a pack argument.
+
 C++2c Feature Support
 ^
 
diff --git a/clang/include/clang/Sema/Overload.h 
b/clang/include/clang/Sema/Overload.h
index c716a25bb673b8..8b7480636c36e7 100644
--- a/clang/include/clang/Sema/Overload.h
+++ b/clang/include/clang/Sema/Overload.h
@@ -925,6 +925,8 @@ class Sema;
 
 bool TookAddressOfOverload : 1;
 
+bool HasMatchedPackOnParmToNonPackOnArg : 1;
+
 /// True if the candidate was found using ADL.
 CallExpr::ADLCallKind IsADLCandidate : 1;
 
@@ -999,8 +1001,9 @@ class Sema;
 friend class OverloadCandidateSet;
 OverloadCandidate()
 : IsSurrogate(false), IgnoreObjectArgument(false),
-  TookAddressOfOverload(false), IsADLCandidate(CallExpr::NotADL),
-  RewriteKind(CRK_None) {}
+  TookAddressOfOverload(false),
+  HasMatchedPackOnParmToNonPackOnArg(false),
+  IsADLCandidate(CallExpr::NotADL), RewriteKind(CRK_None) {}
   };
 
   /// OverloadCandidateSet - A set of overload candidates, used in C++
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index d99a0c7af4b0ca..5f045860acb7b2 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -10132,7 +10132,8 @@ class Sema final : public SemaBase {
   ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
   ConversionSequenceList EarlyConversions = std::nullopt,
   OverloadCandidateParamOrder PO = {},
-  bool AggregateCandidateDeduction = false);
+  bool AggregateCandidateDeduction = false,
+  bool HasMatchedPackOnParmToNonPackOnArg = false);
 
   /// Add all of the function declarations in the given function set to
   /// the overload candidate set.
@@ -10167,7 +10168,8 @@ class Sema final : public SemaBase {
  bool SuppressUserConversions = false,
  bool PartialOverloading = false,
  ConversionSequenceList EarlyConversions = std::nullopt,
- OverloadCandidateParamOrder PO = {});
+ OverloadCandidateParamOrder PO = {},
+ bool HasMatchedPackOnParmToNonPackOnArg = false);
 
   /// Add a C++ member function template as a candidate to the candidate
   /// set, using template argument deduction to produce an appropriate member
@@ -10213,7 +10215,8 @@ class Sema final : public SemaBase {
   CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
   CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
   OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
-  bool AllowExplicit, bool AllowResultConversion = true);
+  bool AllowExplicit, bool AllowResultConversion = true,
+  bool HasMatchedPackOnParmToNonPackOnArg = false);
 
   /// Adds a conversion function template specialization
   /// candidate to the overload set, using template argument deduction
@@ -11637,7 +11640,7 @@ class Sema final : public SemaBase {
 SourceLocation RAngleLoc, unsigned ArgumentPackIndex,
 SmallVectorImpl &SugaredConverted,
 SmallVectorImpl &CanonicalConverted,
-CheckTemplateArgumentKind CTAK,
+CheckTemplateArgumentKind CTAK, bool PartialOrdering,
 bool *MatchedPackOnParmToNonPackOnArg);
 
   /// Check that the given template arguments can be provided to
@@ -11720,7 +11723,8 @@ class Sema final : public SemaBase {
   /// It returns true 

[llvm-branch-commits] [clang] [clang] Implement TTP P0522 pack matching for deduced function template calls. (PR #111457)

2024-10-10 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/111457

>From 6d20ed898e7e96c0e989b37718294a878d87797c Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Sat, 5 Oct 2024 21:56:51 -0300
Subject: [PATCH] [clang] Implement TTP 'reversed' pack matching for deduced
 function template calls.

Clang previously missed implementing P0522 pack matching
for deduced function template calls.
---
 clang/docs/ReleaseNotes.rst  |  4 ++
 clang/include/clang/Sema/Overload.h  | 10 ++-
 clang/include/clang/Sema/Sema.h  | 23 ---
 clang/lib/Sema/SemaLookup.cpp|  1 +
 clang/lib/Sema/SemaOverload.cpp  | 50 +--
 clang/lib/Sema/SemaTemplate.cpp  | 23 +++
 clang/lib/Sema/SemaTemplateDeduction.cpp | 70 +++-
 clang/test/SemaTemplate/cwg2398.cpp  | 81 
 8 files changed, 193 insertions(+), 69 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 153901fb3b1ed7..1324b28d84c3d0 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -151,6 +151,10 @@ C++ Language Changes
 - The builtin type alias ``__builtin_common_type`` has been added to improve 
the
   performance of ``std::common_type``.
 
+- When matching a template to a template template parameter in the context of 
a deduced
+  function template call, clang now implements P0522 pack rules,
+  allowing a non-pack parameter to match a pack argument.
+
 C++2c Feature Support
 ^
 
diff --git a/clang/include/clang/Sema/Overload.h 
b/clang/include/clang/Sema/Overload.h
index c716a25bb673b8..d38278c5041118 100644
--- a/clang/include/clang/Sema/Overload.h
+++ b/clang/include/clang/Sema/Overload.h
@@ -925,6 +925,11 @@ class Sema;
 
 bool TookAddressOfOverload : 1;
 
+/// Have we matched any packs on the parameter side, versus any non-packs 
on
+/// the argument side, in a context where the opposite matching is also
+/// allowed?
+bool HasMatchedPackOnParmToNonPackOnArg : 1;
+
 /// True if the candidate was found using ADL.
 CallExpr::ADLCallKind IsADLCandidate : 1;
 
@@ -999,8 +1004,9 @@ class Sema;
 friend class OverloadCandidateSet;
 OverloadCandidate()
 : IsSurrogate(false), IgnoreObjectArgument(false),
-  TookAddressOfOverload(false), IsADLCandidate(CallExpr::NotADL),
-  RewriteKind(CRK_None) {}
+  TookAddressOfOverload(false),
+  HasMatchedPackOnParmToNonPackOnArg(false),
+  IsADLCandidate(CallExpr::NotADL), RewriteKind(CRK_None) {}
   };
 
   /// OverloadCandidateSet - A set of overload candidates, used in C++
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index d99a0c7af4b0ca..5f045860acb7b2 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -10132,7 +10132,8 @@ class Sema final : public SemaBase {
   ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
   ConversionSequenceList EarlyConversions = std::nullopt,
   OverloadCandidateParamOrder PO = {},
-  bool AggregateCandidateDeduction = false);
+  bool AggregateCandidateDeduction = false,
+  bool HasMatchedPackOnParmToNonPackOnArg = false);
 
   /// Add all of the function declarations in the given function set to
   /// the overload candidate set.
@@ -10167,7 +10168,8 @@ class Sema final : public SemaBase {
  bool SuppressUserConversions = false,
  bool PartialOverloading = false,
  ConversionSequenceList EarlyConversions = std::nullopt,
- OverloadCandidateParamOrder PO = {});
+ OverloadCandidateParamOrder PO = {},
+ bool HasMatchedPackOnParmToNonPackOnArg = false);
 
   /// Add a C++ member function template as a candidate to the candidate
   /// set, using template argument deduction to produce an appropriate member
@@ -10213,7 +10215,8 @@ class Sema final : public SemaBase {
   CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
   CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
   OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
-  bool AllowExplicit, bool AllowResultConversion = true);
+  bool AllowExplicit, bool AllowResultConversion = true,
+  bool HasMatchedPackOnParmToNonPackOnArg = false);
 
   /// Adds a conversion function template specialization
   /// candidate to the overload set, using template argument deduction
@@ -11637,7 +11640,7 @@ class Sema final : public SemaBase {
 SourceLocation RAngleLoc, unsigned ArgumentPackIndex,
 SmallVectorImpl &SugaredConverted,
 SmallVectorImpl &CanonicalConverted,
-CheckTemplateArgumentKind CTAK,
+CheckTemplateArgumentKind CTAK, bool PartialOrdering,
 bool *MatchedP

[llvm-branch-commits] [clang] [clang] Implement TTP P0522 pack matching for deduced function template calls. (PR #111457)

2024-10-10 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/111457

>From e48304b91b42f4aeb1940d34b906242e6e46c8a3 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Sat, 5 Oct 2024 21:56:51 -0300
Subject: [PATCH] [clang] Implement TTP 'reversed' pack matching for deduced
 function template calls.

Clang previously missed implementing P0522 pack matching
for deduced function template calls.
---
 clang/include/clang/Sema/Overload.h  | 10 ++-
 clang/include/clang/Sema/Sema.h  | 23 ---
 clang/lib/Sema/SemaLookup.cpp|  1 +
 clang/lib/Sema/SemaOverload.cpp  | 50 +--
 clang/lib/Sema/SemaTemplate.cpp  | 23 +++
 clang/lib/Sema/SemaTemplateDeduction.cpp | 70 +++-
 clang/test/SemaTemplate/cwg2398.cpp  | 81 
 7 files changed, 189 insertions(+), 69 deletions(-)

diff --git a/clang/include/clang/Sema/Overload.h 
b/clang/include/clang/Sema/Overload.h
index c716a25bb673b8..d38278c5041118 100644
--- a/clang/include/clang/Sema/Overload.h
+++ b/clang/include/clang/Sema/Overload.h
@@ -925,6 +925,11 @@ class Sema;
 
 bool TookAddressOfOverload : 1;
 
+/// Have we matched any packs on the parameter side, versus any non-packs 
on
+/// the argument side, in a context where the opposite matching is also
+/// allowed?
+bool HasMatchedPackOnParmToNonPackOnArg : 1;
+
 /// True if the candidate was found using ADL.
 CallExpr::ADLCallKind IsADLCandidate : 1;
 
@@ -999,8 +1004,9 @@ class Sema;
 friend class OverloadCandidateSet;
 OverloadCandidate()
 : IsSurrogate(false), IgnoreObjectArgument(false),
-  TookAddressOfOverload(false), IsADLCandidate(CallExpr::NotADL),
-  RewriteKind(CRK_None) {}
+  TookAddressOfOverload(false),
+  HasMatchedPackOnParmToNonPackOnArg(false),
+  IsADLCandidate(CallExpr::NotADL), RewriteKind(CRK_None) {}
   };
 
   /// OverloadCandidateSet - A set of overload candidates, used in C++
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index d99a0c7af4b0ca..5f045860acb7b2 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -10132,7 +10132,8 @@ class Sema final : public SemaBase {
   ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
   ConversionSequenceList EarlyConversions = std::nullopt,
   OverloadCandidateParamOrder PO = {},
-  bool AggregateCandidateDeduction = false);
+  bool AggregateCandidateDeduction = false,
+  bool HasMatchedPackOnParmToNonPackOnArg = false);
 
   /// Add all of the function declarations in the given function set to
   /// the overload candidate set.
@@ -10167,7 +10168,8 @@ class Sema final : public SemaBase {
  bool SuppressUserConversions = false,
  bool PartialOverloading = false,
  ConversionSequenceList EarlyConversions = std::nullopt,
- OverloadCandidateParamOrder PO = {});
+ OverloadCandidateParamOrder PO = {},
+ bool HasMatchedPackOnParmToNonPackOnArg = false);
 
   /// Add a C++ member function template as a candidate to the candidate
   /// set, using template argument deduction to produce an appropriate member
@@ -10213,7 +10215,8 @@ class Sema final : public SemaBase {
   CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
   CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
   OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
-  bool AllowExplicit, bool AllowResultConversion = true);
+  bool AllowExplicit, bool AllowResultConversion = true,
+  bool HasMatchedPackOnParmToNonPackOnArg = false);
 
   /// Adds a conversion function template specialization
   /// candidate to the overload set, using template argument deduction
@@ -11637,7 +11640,7 @@ class Sema final : public SemaBase {
 SourceLocation RAngleLoc, unsigned ArgumentPackIndex,
 SmallVectorImpl &SugaredConverted,
 SmallVectorImpl &CanonicalConverted,
-CheckTemplateArgumentKind CTAK,
+CheckTemplateArgumentKind CTAK, bool PartialOrdering,
 bool *MatchedPackOnParmToNonPackOnArg);
 
   /// Check that the given template arguments can be provided to
@@ -11720,7 +11723,8 @@ class Sema final : public SemaBase {
   /// It returns true if an error occurred, and false otherwise.
   bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
  TemplateParameterList *Params,
- TemplateArgumentLoc &Arg, bool IsDeduced,
+ TemplateArgumentLoc &Arg,
+ bool PartialOrdering,
  bool *MatchedPackOnParmToNonPackOnArg);
 
   void NoteTemplate

[llvm-branch-commits] [clang] [clang] Implement TTP P0522 pack matching for deduced function template calls. (PR #111457)

2024-10-10 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/111457

>From 118ca96aeeb8871a932ed48dd72ea03efa7364e4 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Sat, 5 Oct 2024 21:56:51 -0300
Subject: [PATCH] [clang] Implement TTP 'reversed' pack matching for deduced
 function template calls.

Clang previously missed implementing P0522 pack matching
for deduced function template calls.
---
 clang/include/clang/Sema/Overload.h  | 10 ++-
 clang/include/clang/Sema/Sema.h  | 23 ---
 clang/lib/Sema/SemaLookup.cpp|  1 +
 clang/lib/Sema/SemaOverload.cpp  | 50 +--
 clang/lib/Sema/SemaTemplate.cpp  | 23 +++
 clang/lib/Sema/SemaTemplateDeduction.cpp | 70 +++-
 clang/test/SemaTemplate/cwg2398.cpp  | 81 
 7 files changed, 189 insertions(+), 69 deletions(-)

diff --git a/clang/include/clang/Sema/Overload.h 
b/clang/include/clang/Sema/Overload.h
index c716a25bb673b8..d38278c5041118 100644
--- a/clang/include/clang/Sema/Overload.h
+++ b/clang/include/clang/Sema/Overload.h
@@ -925,6 +925,11 @@ class Sema;
 
 bool TookAddressOfOverload : 1;
 
+/// Have we matched any packs on the parameter side, versus any non-packs 
on
+/// the argument side, in a context where the opposite matching is also
+/// allowed?
+bool HasMatchedPackOnParmToNonPackOnArg : 1;
+
 /// True if the candidate was found using ADL.
 CallExpr::ADLCallKind IsADLCandidate : 1;
 
@@ -999,8 +1004,9 @@ class Sema;
 friend class OverloadCandidateSet;
 OverloadCandidate()
 : IsSurrogate(false), IgnoreObjectArgument(false),
-  TookAddressOfOverload(false), IsADLCandidate(CallExpr::NotADL),
-  RewriteKind(CRK_None) {}
+  TookAddressOfOverload(false),
+  HasMatchedPackOnParmToNonPackOnArg(false),
+  IsADLCandidate(CallExpr::NotADL), RewriteKind(CRK_None) {}
   };
 
   /// OverloadCandidateSet - A set of overload candidates, used in C++
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index d73b7dc2ab62a2..ef010fafb1573e 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -10133,7 +10133,8 @@ class Sema final : public SemaBase {
   ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
   ConversionSequenceList EarlyConversions = std::nullopt,
   OverloadCandidateParamOrder PO = {},
-  bool AggregateCandidateDeduction = false);
+  bool AggregateCandidateDeduction = false,
+  bool HasMatchedPackOnParmToNonPackOnArg = false);
 
   /// Add all of the function declarations in the given function set to
   /// the overload candidate set.
@@ -10168,7 +10169,8 @@ class Sema final : public SemaBase {
  bool SuppressUserConversions = false,
  bool PartialOverloading = false,
  ConversionSequenceList EarlyConversions = std::nullopt,
- OverloadCandidateParamOrder PO = {});
+ OverloadCandidateParamOrder PO = {},
+ bool HasMatchedPackOnParmToNonPackOnArg = false);
 
   /// Add a C++ member function template as a candidate to the candidate
   /// set, using template argument deduction to produce an appropriate member
@@ -10214,7 +10216,8 @@ class Sema final : public SemaBase {
   CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
   CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
   OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
-  bool AllowExplicit, bool AllowResultConversion = true);
+  bool AllowExplicit, bool AllowResultConversion = true,
+  bool HasMatchedPackOnParmToNonPackOnArg = false);
 
   /// Adds a conversion function template specialization
   /// candidate to the overload set, using template argument deduction
@@ -11637,7 +11640,7 @@ class Sema final : public SemaBase {
 SourceLocation RAngleLoc, unsigned ArgumentPackIndex,
 SmallVectorImpl &SugaredConverted,
 SmallVectorImpl &CanonicalConverted,
-CheckTemplateArgumentKind CTAK,
+CheckTemplateArgumentKind CTAK, bool PartialOrdering,
 bool *MatchedPackOnParmToNonPackOnArg);
 
   /// Check that the given template arguments can be provided to
@@ -11720,7 +11723,8 @@ class Sema final : public SemaBase {
   /// It returns true if an error occurred, and false otherwise.
   bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
  TemplateParameterList *Params,
- TemplateArgumentLoc &Arg, bool IsDeduced,
+ TemplateArgumentLoc &Arg,
+ bool PartialOrdering,
  bool *MatchedPackOnParmToNonPackOnArg);
 
   void NoteTemplate

[llvm-branch-commits] [clang] [clang] Implement TTP P0522 pack matching for deduced function template calls. (PR #111457)

2024-10-10 Thread Matheus Izvekov via llvm-branch-commits

mizvekov wrote:

@zmodem FIY this will fix 
https://github.com/llvm/llvm-project/pull/96023#issuecomment-2393228464

https://github.com/llvm/llvm-project/pull/111457
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [lldb] [clang] NFC: rename MatchedPackOnParmToNonPackOnArg to StrictPackMatch (PR #125418)

2025-02-04 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov edited 
https://github.com/llvm/llvm-project/pull/125418
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [lldb] [clang] NFC: rename MatchedPackOnParmToNonPackOnArg to StrictPackMatch (PR #125418)

2025-02-04 Thread Matheus Izvekov via llvm-branch-commits

mizvekov wrote:

All rebased, it's back to being a god-fearing all around NFC PR :)

https://github.com/llvm/llvm-project/pull/125418
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] NFC: rename MatchedPackOnParmToNonPackOnArg to StrictPackMatch (PR #125418)

2025-02-04 Thread Matheus Izvekov via llvm-branch-commits


@@ -1842,19 +1842,19 @@ class ClassTemplateSpecializationDecl : public 
CXXRecordDecl,
   unsigned SpecializationKind : 3;
 
   /// Indicate that we have matched a parameter pack with a non pack
-  /// argument, when the opposite match is also allowed (strict pack match).
+  /// argument, when the opposite match is also allowed.
   /// This needs to be cached as deduction is performed during declaration,
   /// and we need the information to be preserved so that it is consistent
   /// during instantiation.
-  bool MatchedPackOnParmToNonPackOnArg : 1;
+  bool StrictPackMatch : 1;

mizvekov wrote:

Hmm, the short name was one of the big pluses of this patch.

Once the wording is merged, we can quote the paragraph number as well.

Since it's a defined term, I don't think we need that mouthful of a name TBH.

https://github.com/llvm/llvm-project/pull/125418
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] NFC: rename MatchedPackOnParmToNonPackOnArg to StrictPackMatch (PR #125418)

2025-02-04 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/125418

>From f558c5838c48e47b62d3d0a3b5118c96d9ff47ec Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Sun, 2 Feb 2025 13:31:20 -0300
Subject: [PATCH] [clang] NFC: rename MatchedPackOnParmToNonPackOnArg to
 StrictPackMatch

This rename follows the proposed wording in P3310R5, which introduces
the term 'strict pack match' to refer to the same thing.
---
 clang/include/clang/AST/DeclTemplate.h| 12 +++
 clang/include/clang/Sema/Overload.h   |  5 ++-
 clang/include/clang/Sema/Sema.h   | 33 +--
 clang/include/clang/Sema/TemplateDeduction.h  | 10 ++
 clang/lib/AST/ASTImporter.cpp |  8 ++---
 clang/lib/AST/DeclTemplate.cpp| 18 --
 clang/lib/AST/JSONNodeDumper.cpp  |  2 +-
 clang/lib/AST/TextNodeDumper.cpp  |  2 +-
 clang/lib/Sema/SemaOverload.cpp   | 30 +++--
 clang/lib/Sema/SemaTemplate.cpp   | 29 
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 21 ++--
 clang/lib/Sema/SemaTemplateInstantiate.cpp| 16 -
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  |  2 +-
 clang/lib/Sema/SemaType.cpp   |  3 +-
 clang/lib/Serialization/ASTReaderDecl.cpp |  2 +-
 clang/lib/Serialization/ASTWriterDecl.cpp |  2 +-
 16 files changed, 85 insertions(+), 110 deletions(-)

diff --git a/clang/include/clang/AST/DeclTemplate.h 
b/clang/include/clang/AST/DeclTemplate.h
index 03c43765206b18..87406b0e030df1 100644
--- a/clang/include/clang/AST/DeclTemplate.h
+++ b/clang/include/clang/AST/DeclTemplate.h
@@ -1842,11 +1842,11 @@ class ClassTemplateSpecializationDecl : public 
CXXRecordDecl,
   unsigned SpecializationKind : 3;
 
   /// Indicate that we have matched a parameter pack with a non pack
-  /// argument, when the opposite match is also allowed (strict pack match).
+  /// argument, when the opposite match is also allowed.
   /// This needs to be cached as deduction is performed during declaration,
   /// and we need the information to be preserved so that it is consistent
   /// during instantiation.
-  bool MatchedPackOnParmToNonPackOnArg : 1;
+  bool StrictPackMatch : 1;
 
 protected:
   ClassTemplateSpecializationDecl(ASTContext &Context, Kind DK, TagKind TK,
@@ -1854,7 +1854,7 @@ class ClassTemplateSpecializationDecl : public 
CXXRecordDecl,
   SourceLocation IdLoc,
   ClassTemplateDecl *SpecializedTemplate,
   ArrayRef Args,
-  bool MatchedPackOnParmToNonPackOnArg,
+  bool StrictPackMatch,
   ClassTemplateSpecializationDecl *PrevDecl);
 
   ClassTemplateSpecializationDecl(ASTContext &C, Kind DK);
@@ -1867,7 +1867,7 @@ class ClassTemplateSpecializationDecl : public 
CXXRecordDecl,
   Create(ASTContext &Context, TagKind TK, DeclContext *DC,
  SourceLocation StartLoc, SourceLocation IdLoc,
  ClassTemplateDecl *SpecializedTemplate,
- ArrayRef Args, bool MatchedPackOnParmToNonPackOnArg,
+ ArrayRef Args, bool StrictPackMatch,
  ClassTemplateSpecializationDecl *PrevDecl);
   static ClassTemplateSpecializationDecl *CreateDeserialized(ASTContext &C,
  GlobalDeclID ID);
@@ -1938,9 +1938,7 @@ class ClassTemplateSpecializationDecl : public 
CXXRecordDecl,
 SpecializationKind = TSK;
   }
 
-  bool hasMatchedPackOnParmToNonPackOnArg() const {
-return MatchedPackOnParmToNonPackOnArg;
-  }
+  bool hasStrictPackMatch() const { return StrictPackMatch; }
 
   /// Get the point of instantiation (if any), or null if none.
   SourceLocation getPointOfInstantiation() const {
diff --git a/clang/include/clang/Sema/Overload.h 
b/clang/include/clang/Sema/Overload.h
index c7f2422b542dd1..c03ec00d03dc50 100644
--- a/clang/include/clang/Sema/Overload.h
+++ b/clang/include/clang/Sema/Overload.h
@@ -933,7 +933,7 @@ class Sema;
 /// Have we matched any packs on the parameter side, versus any non-packs 
on
 /// the argument side, in a context where the opposite matching is also
 /// allowed?
-bool HasMatchedPackOnParmToNonPackOnArg : 1;
+bool StrictPackMatch : 1;
 
 /// True if the candidate was found using ADL.
 LLVM_PREFERRED_TYPE(CallExpr::ADLCallKind)
@@ -1010,8 +1010,7 @@ class Sema;
 friend class OverloadCandidateSet;
 OverloadCandidate()
 : IsSurrogate(false), IgnoreObjectArgument(false),
-  TookAddressOfOverload(false),
-  HasMatchedPackOnParmToNonPackOnArg(false),
+  TookAddressOfOverload(false), StrictPackMatch(false),
   IsADLCandidate(llvm::to_underlying(CallExpr::NotADL)),
   RewriteKind(CRK_None) {}
   };
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h

[llvm-branch-commits] [clang] release/20.x: [C++20][Modules][Serialization] Delay marking pending incomplete decl chains until the end of `finishPendingActions`. (#121245) (PR #126289)

2025-02-07 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov approved this pull request.


https://github.com/llvm/llvm-project/pull/126289
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] Implement instantiation context note for checking template parameters (PR #126088)

2025-02-06 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov edited 
https://github.com/llvm/llvm-project/pull/126088
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] Implement evaluation context for checking template parameters (PR #126088)

2025-02-06 Thread Matheus Izvekov via llvm-branch-commits

mizvekov wrote:

> (Did you mean `Implement *instantiation* context for checking template 
> parameters`?)

Oops, yes of course :)

https://github.com/llvm/llvm-project/pull/126088
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] Implement instantiation context for checking template parameters (PR #126088)

2025-02-06 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov edited 
https://github.com/llvm/llvm-project/pull/126088
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] Implement instantiation context note for checking template parameters (PR #126088)

2025-02-06 Thread Matheus Izvekov via llvm-branch-commits


@@ -637,6 +641,8 @@ namespace cwg431 { // cwg431: 2.8
 
 namespace cwg432 { // cwg432: 3.0
   template struct A {};
+  // expected-note@-1{{template parameter is declared here}}
+  // since-cxx11-note@-2 {{template parameter is declared here}}

mizvekov wrote:

It's emitted once each by both errors in this section.

https://github.com/llvm/llvm-project/pull/126088
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] NFC: rename MatchedPackOnParmToNonPackOnArg to StrictPackMatch (PR #125418)

2025-02-02 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/125418

This rename follows the proposed wording in P3310R5, which introduces the term 
'strict pack match' to refer to the same thing.

>From 772973a841ad739172a9f23bc1403924eea4cba8 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Sun, 2 Feb 2025 13:31:20 -0300
Subject: [PATCH] [clang] NFC: rename MatchedPackOnParmToNonPackOnArg to
 StrictPackMatch

This rename follows the proposed wording in P3310R5, which introduces
the term 'strict pack match' to refer to the same thing.
---
 clang/include/clang/AST/DeclTemplate.h| 12 +++
 clang/include/clang/Sema/Overload.h   |  5 ++-
 clang/include/clang/Sema/Sema.h   | 33 +--
 clang/include/clang/Sema/TemplateDeduction.h  | 10 ++
 clang/lib/AST/ASTImporter.cpp |  8 ++---
 clang/lib/AST/DeclTemplate.cpp| 18 --
 clang/lib/AST/TextNodeDumper.cpp  |  2 +-
 clang/lib/Sema/SemaOverload.cpp   | 30 +++--
 clang/lib/Sema/SemaTemplate.cpp   | 29 
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 21 ++--
 clang/lib/Sema/SemaTemplateInstantiate.cpp| 16 -
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  |  2 +-
 clang/lib/Sema/SemaType.cpp   |  3 +-
 clang/lib/Serialization/ASTReaderDecl.cpp |  2 +-
 clang/lib/Serialization/ASTWriterDecl.cpp |  2 +-
 15 files changed, 84 insertions(+), 109 deletions(-)

diff --git a/clang/include/clang/AST/DeclTemplate.h 
b/clang/include/clang/AST/DeclTemplate.h
index 03c43765206b18..87406b0e030df1 100644
--- a/clang/include/clang/AST/DeclTemplate.h
+++ b/clang/include/clang/AST/DeclTemplate.h
@@ -1842,11 +1842,11 @@ class ClassTemplateSpecializationDecl : public 
CXXRecordDecl,
   unsigned SpecializationKind : 3;
 
   /// Indicate that we have matched a parameter pack with a non pack
-  /// argument, when the opposite match is also allowed (strict pack match).
+  /// argument, when the opposite match is also allowed.
   /// This needs to be cached as deduction is performed during declaration,
   /// and we need the information to be preserved so that it is consistent
   /// during instantiation.
-  bool MatchedPackOnParmToNonPackOnArg : 1;
+  bool StrictPackMatch : 1;
 
 protected:
   ClassTemplateSpecializationDecl(ASTContext &Context, Kind DK, TagKind TK,
@@ -1854,7 +1854,7 @@ class ClassTemplateSpecializationDecl : public 
CXXRecordDecl,
   SourceLocation IdLoc,
   ClassTemplateDecl *SpecializedTemplate,
   ArrayRef Args,
-  bool MatchedPackOnParmToNonPackOnArg,
+  bool StrictPackMatch,
   ClassTemplateSpecializationDecl *PrevDecl);
 
   ClassTemplateSpecializationDecl(ASTContext &C, Kind DK);
@@ -1867,7 +1867,7 @@ class ClassTemplateSpecializationDecl : public 
CXXRecordDecl,
   Create(ASTContext &Context, TagKind TK, DeclContext *DC,
  SourceLocation StartLoc, SourceLocation IdLoc,
  ClassTemplateDecl *SpecializedTemplate,
- ArrayRef Args, bool MatchedPackOnParmToNonPackOnArg,
+ ArrayRef Args, bool StrictPackMatch,
  ClassTemplateSpecializationDecl *PrevDecl);
   static ClassTemplateSpecializationDecl *CreateDeserialized(ASTContext &C,
  GlobalDeclID ID);
@@ -1938,9 +1938,7 @@ class ClassTemplateSpecializationDecl : public 
CXXRecordDecl,
 SpecializationKind = TSK;
   }
 
-  bool hasMatchedPackOnParmToNonPackOnArg() const {
-return MatchedPackOnParmToNonPackOnArg;
-  }
+  bool hasStrictPackMatch() const { return StrictPackMatch; }
 
   /// Get the point of instantiation (if any), or null if none.
   SourceLocation getPointOfInstantiation() const {
diff --git a/clang/include/clang/Sema/Overload.h 
b/clang/include/clang/Sema/Overload.h
index c7f2422b542dd1..c03ec00d03dc50 100644
--- a/clang/include/clang/Sema/Overload.h
+++ b/clang/include/clang/Sema/Overload.h
@@ -933,7 +933,7 @@ class Sema;
 /// Have we matched any packs on the parameter side, versus any non-packs 
on
 /// the argument side, in a context where the opposite matching is also
 /// allowed?
-bool HasMatchedPackOnParmToNonPackOnArg : 1;
+bool StrictPackMatch : 1;
 
 /// True if the candidate was found using ADL.
 LLVM_PREFERRED_TYPE(CallExpr::ADLCallKind)
@@ -1010,8 +1010,7 @@ class Sema;
 friend class OverloadCandidateSet;
 OverloadCandidate()
 : IsSurrogate(false), IgnoreObjectArgument(false),
-  TookAddressOfOverload(false),
-  HasMatchedPackOnParmToNonPackOnArg(false),
+  TookAddressOfOverload(false), StrictPackMatch(false),
   IsADLCandidate(llvm::to_underlying(CallExpr::NotADL)),
   RewriteKind(CRK_None) {}
   };
diff

[llvm-branch-commits] [clang] [clang] fix template argument conversion (PR #124386)

2025-01-24 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/124386

Converted template arguments need to be converted again, if the corresponding 
template parameter changed, as different conversions might apply in that case.

>From 9b174f4505eaf19e0ccfb1ec905c8206bb575d4b Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Fri, 24 Jan 2025 19:25:38 -0300
Subject: [PATCH] [clang] fix template argument conversion

Converted template arguments need to be converted again, if
the corresponding template parameter changed, as different
conversions might apply in that case.
---
 clang/docs/ReleaseNotes.rst |   3 +
 clang/lib/Sema/SemaTemplate.cpp | 120 +---
 clang/lib/Sema/TreeTransform.h  |   6 +-
 clang/test/SemaTemplate/cwg2398.cpp |   8 --
 4 files changed, 80 insertions(+), 57 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b89d055304f4a6..27574924a14a92 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -993,6 +993,9 @@ Bug Fixes to C++ Support
 - Fix immediate escalation not propagating through inherited constructors.  
(#GH112677)
 - Fixed assertions or false compiler diagnostics in the case of C++ modules for
   lambda functions or inline friend functions defined inside templates 
(#GH122493).
+- Fix template argument checking so that converted template arguments are
+  converted again. This fixes some issues with partial ordering involving
+  template template parameters with non-type template parameters.
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 210df2836eeb07..62c45f15dec54e 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -5199,7 +5199,7 @@ convertTypeTemplateArgumentToTemplate(ASTContext 
&Context, TypeLoc TLoc) {
 }
 
 bool Sema::CheckTemplateArgument(
-NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template,
+NamedDecl *Param, TemplateArgumentLoc &ArgLoc, NamedDecl *Template,
 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
 unsigned ArgumentPackIndex,
 SmallVectorImpl &SugaredConverted,
@@ -5208,9 +5208,10 @@ bool Sema::CheckTemplateArgument(
 bool PartialOrderingTTP, bool *MatchedPackOnParmToNonPackOnArg) {
   // Check template type parameters.
   if (TemplateTypeParmDecl *TTP = dyn_cast(Param))
-return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted,
+return CheckTemplateTypeArgument(TTP, ArgLoc, SugaredConverted,
  CanonicalConverted);
 
+  const TemplateArgument &Arg = ArgLoc.getArgument();
   // Check non-type template parameters.
   if (NonTypeTemplateParmDecl *NTTP =dyn_cast(Param)) 
{
 // Do substitution on the type of the non-type template parameter
@@ -5252,63 +5253,89 @@ bool Sema::CheckTemplateArgument(
 return true;
 }
 
-switch (Arg.getArgument().getKind()) {
-case TemplateArgument::Null:
-  llvm_unreachable("Should never see a NULL template argument here");
-
-case TemplateArgument::Expression: {
-  Expr *E = Arg.getArgument().getAsExpr();
+auto checkExpr = [&](Expr *E) -> Expr * {
   TemplateArgument SugaredResult, CanonicalResult;
   unsigned CurSFINAEErrors = NumSFINAEErrors;
   ExprResult Res =
   CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
 CanonicalResult, PartialOrderingTTP, CTAK);
-  if (Res.isInvalid())
-return true;
   // If the current template argument causes an error, give up now.
-  if (CurSFINAEErrors < NumSFINAEErrors)
-return true;
+  if (Res.isInvalid() || CurSFINAEErrors < NumSFINAEErrors)
+return nullptr;
+  SugaredConverted.push_back(SugaredResult);
+  CanonicalConverted.push_back(CanonicalResult);
+  return Res.get();
+};
+
+switch (Arg.getKind()) {
+case TemplateArgument::Null:
+  llvm_unreachable("Should never see a NULL template argument here");
 
+case TemplateArgument::Expression: {
+  Expr *E = Arg.getAsExpr();
+  Expr *R = checkExpr(E);
+  if (!R)
+return true;
   // If the resulting expression is new, then use it in place of the
   // old expression in the template argument.
-  if (Res.get() != E) {
-TemplateArgument TA(Res.get());
-Arg = TemplateArgumentLoc(TA, Res.get());
+  if (R != E) {
+TemplateArgument TA(R);
+ArgLoc = TemplateArgumentLoc(TA, R);
   }
-
-  SugaredConverted.push_back(SugaredResult);
-  CanonicalConverted.push_back(CanonicalResult);
   break;
 }
 
-case TemplateArgument::Declaration:
-case TemplateArgument::Integral:
+// As for the converted NTTP kinds, they still might need another
+// conversion, as the new corresponding parameter might be different.
+// Ideally, we would always perform substitution sta

[llvm-branch-commits] [clang] [clang] fix template argument conversion (PR #124386)

2025-01-26 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/124386

>From 7b4befe667df321511fc75ea3a4ef8ab3067ced9 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Fri, 24 Jan 2025 19:25:38 -0300
Subject: [PATCH] [clang] fix template argument conversion

Converted template arguments need to be converted again, if
the corresponding template parameter changed, as different
conversions might apply in that case.
---
 clang/docs/ReleaseNotes.rst |   3 +
 clang/lib/Sema/SemaTemplate.cpp | 102 +++-
 clang/lib/Sema/TreeTransform.h  |   6 +-
 clang/test/SemaTemplate/cwg2398.cpp |  20 --
 4 files changed, 63 insertions(+), 68 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b89d055304f4a6..27574924a14a92 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -993,6 +993,9 @@ Bug Fixes to C++ Support
 - Fix immediate escalation not propagating through inherited constructors.  
(#GH112677)
 - Fixed assertions or false compiler diagnostics in the case of C++ modules for
   lambda functions or inline friend functions defined inside templates 
(#GH122493).
+- Fix template argument checking so that converted template arguments are
+  converted again. This fixes some issues with partial ordering involving
+  template template parameters with non-type template parameters.
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 210df2836eeb07..cb9d78734e6bbf 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -5199,7 +5199,7 @@ convertTypeTemplateArgumentToTemplate(ASTContext 
&Context, TypeLoc TLoc) {
 }
 
 bool Sema::CheckTemplateArgument(
-NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template,
+NamedDecl *Param, TemplateArgumentLoc &ArgLoc, NamedDecl *Template,
 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
 unsigned ArgumentPackIndex,
 SmallVectorImpl &SugaredConverted,
@@ -5208,9 +5208,10 @@ bool Sema::CheckTemplateArgument(
 bool PartialOrderingTTP, bool *MatchedPackOnParmToNonPackOnArg) {
   // Check template type parameters.
   if (TemplateTypeParmDecl *TTP = dyn_cast(Param))
-return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted,
+return CheckTemplateTypeArgument(TTP, ArgLoc, SugaredConverted,
  CanonicalConverted);
 
+  const TemplateArgument &Arg = ArgLoc.getArgument();
   // Check non-type template parameters.
   if (NonTypeTemplateParmDecl *NTTP =dyn_cast(Param)) 
{
 // Do substitution on the type of the non-type template parameter
@@ -5252,63 +5253,73 @@ bool Sema::CheckTemplateArgument(
 return true;
 }
 
-switch (Arg.getArgument().getKind()) {
-case TemplateArgument::Null:
-  llvm_unreachable("Should never see a NULL template argument here");
-
-case TemplateArgument::Expression: {
-  Expr *E = Arg.getArgument().getAsExpr();
+auto checkExpr = [&](Expr *E) -> Expr * {
   TemplateArgument SugaredResult, CanonicalResult;
   unsigned CurSFINAEErrors = NumSFINAEErrors;
   ExprResult Res =
   CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
 CanonicalResult, PartialOrderingTTP, CTAK);
-  if (Res.isInvalid())
-return true;
   // If the current template argument causes an error, give up now.
-  if (CurSFINAEErrors < NumSFINAEErrors)
-return true;
+  if (Res.isInvalid() || CurSFINAEErrors < NumSFINAEErrors)
+return nullptr;
+  SugaredConverted.push_back(SugaredResult);
+  CanonicalConverted.push_back(CanonicalResult);
+  return Res.get();
+};
+
+switch (Arg.getKind()) {
+case TemplateArgument::Null:
+  llvm_unreachable("Should never see a NULL template argument here");
 
+case TemplateArgument::Expression: {
+  Expr *E = Arg.getAsExpr();
+  Expr *R = checkExpr(E);
+  if (!R)
+return true;
   // If the resulting expression is new, then use it in place of the
   // old expression in the template argument.
-  if (Res.get() != E) {
-TemplateArgument TA(Res.get());
-Arg = TemplateArgumentLoc(TA, Res.get());
+  if (R != E) {
+TemplateArgument TA(R);
+ArgLoc = TemplateArgumentLoc(TA, R);
   }
-
-  SugaredConverted.push_back(SugaredResult);
-  CanonicalConverted.push_back(CanonicalResult);
   break;
 }
 
-case TemplateArgument::Declaration:
+// As for the converted NTTP kinds, they still might need another
+// conversion, as the new corresponding parameter might be different.
+// Ideally, we would always perform substitution starting with sugared 
types
+// and never need these, as we would still have expressions. Since these 
are
+// needed so rarely, it's probably a better tradeoff to just convert them
+

[llvm-branch-commits] [clang] [clang] fix nondeduced mismatch with nullptr template arguments (PR #124498)

2025-01-26 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/124498

In deduction, when comparing template arguments of value kind, we should check 
if the value matches. Values of different types can still match. For example, 
`short(0)` matches `int(0)`.

Values of nullptr kind always match each other, since there is only one such 
possible value. Similarly to integrals, the type does not matter.

>From e8ded39966b65d36c6d84572626882e3c2594c78 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Mon, 27 Jan 2025 00:04:59 -0300
Subject: [PATCH] [clang] fix nondeduced mismatch with nullptr template
 arguments

In deduction, when comparing template arguments of value kind,
we should check if the value matches. Values of different types can
still match. For example, `short(0)` matches `int(0)`.

Values of nullptr kind always match each other, since there is only
one such possible value. Similarly to integrals, the type does not
matter.
---
 clang/docs/ReleaseNotes.rst  | 1 +
 clang/lib/Sema/SemaTemplateDeduction.cpp | 7 ---
 clang/test/SemaTemplate/cwg2398.cpp  | 4 
 3 files changed, 5 insertions(+), 7 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 27574924a14a92..0556879251f89d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -996,6 +996,7 @@ Bug Fixes to C++ Support
 - Fix template argument checking so that converted template arguments are
   converted again. This fixes some issues with partial ordering involving
   template template parameters with non-type template parameters.
+- Fix nondeduced mismatch with nullptr template arguments.
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index 2b96692727a7c8..1e1fce10e7c017 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -2541,10 +2541,9 @@ DeduceTemplateArguments(Sema &S, TemplateParameterList 
*TemplateParams,
 return TemplateDeductionResult::NonDeducedMismatch;
 
   case TemplateArgument::NullPtr:
-if (A.getKind() == TemplateArgument::NullPtr &&
-S.Context.hasSameType(P.getNullPtrType(), A.getNullPtrType()))
+// 'nullptr' has only one possible value, so it always matches.
+if (A.getKind() == TemplateArgument::NullPtr)
   return TemplateDeductionResult::Success;
-
 Info.FirstArg = P;
 Info.SecondArg = A;
 return TemplateDeductionResult::NonDeducedMismatch;
@@ -2559,6 +2558,8 @@ DeduceTemplateArguments(Sema &S, TemplateParameterList 
*TemplateParams,
 return TemplateDeductionResult::NonDeducedMismatch;
 
   case TemplateArgument::StructuralValue:
+// FIXME: structural equality will also compare types,
+// but they should match iff they have the same value.
 if (A.getKind() == TemplateArgument::StructuralValue &&
 A.structurallyEquals(P))
   return TemplateDeductionResult::Success;
diff --git a/clang/test/SemaTemplate/cwg2398.cpp 
b/clang/test/SemaTemplate/cwg2398.cpp
index 137b94ba2641de..dccb17c48d3256 100644
--- a/clang/test/SemaTemplate/cwg2398.cpp
+++ b/clang/test/SemaTemplate/cwg2398.cpp
@@ -697,15 +697,11 @@ namespace nttp_partial_order {
 template void f(B<&A::m>);
   } // namespace t5
   namespace t6 {
-// FIXME: This should pick the second overload.
 struct A {};
 using nullptr_t = decltype(nullptr);
 template class TT2> void f(TT2);
-// new-note@-1 {{here}}
 templateclass TT1> void f(TT1) {}
-// new-note@-1 {{here}}
 template struct B {};
 template void f(B);
-// new-error@-1 {{ambiguous}}
   } // namespace t6
 } // namespace nttp_partial_order

___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] fix template argument conversion (PR #124386)

2025-01-25 Thread Matheus Izvekov via llvm-branch-commits


@@ -5252,63 +5253,89 @@ bool Sema::CheckTemplateArgument(
 return true;
 }
 
-switch (Arg.getArgument().getKind()) {
-case TemplateArgument::Null:
-  llvm_unreachable("Should never see a NULL template argument here");
-
-case TemplateArgument::Expression: {
-  Expr *E = Arg.getArgument().getAsExpr();
+auto checkExpr = [&](Expr *E) -> Expr * {
   TemplateArgument SugaredResult, CanonicalResult;
   unsigned CurSFINAEErrors = NumSFINAEErrors;
   ExprResult Res =
   CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
 CanonicalResult, PartialOrderingTTP, CTAK);
-  if (Res.isInvalid())
-return true;
   // If the current template argument causes an error, give up now.
-  if (CurSFINAEErrors < NumSFINAEErrors)
-return true;
+  if (Res.isInvalid() || CurSFINAEErrors < NumSFINAEErrors)
+return nullptr;
+  SugaredConverted.push_back(SugaredResult);
+  CanonicalConverted.push_back(CanonicalResult);
+  return Res.get();
+};
+
+switch (Arg.getKind()) {
+case TemplateArgument::Null:
+  llvm_unreachable("Should never see a NULL template argument here");
 
+case TemplateArgument::Expression: {
+  Expr *E = Arg.getAsExpr();
+  Expr *R = checkExpr(E);
+  if (!R)
+return true;
   // If the resulting expression is new, then use it in place of the
   // old expression in the template argument.
-  if (Res.get() != E) {
-TemplateArgument TA(Res.get());
-Arg = TemplateArgumentLoc(TA, Res.get());
+  if (R != E) {
+TemplateArgument TA(R);
+ArgLoc = TemplateArgumentLoc(TA, R);
   }
-
-  SugaredConverted.push_back(SugaredResult);
-  CanonicalConverted.push_back(CanonicalResult);
   break;
 }
 
-case TemplateArgument::Declaration:
-case TemplateArgument::Integral:
+// As for the converted NTTP kinds, they still might need another
+// conversion, as the new corresponding parameter might be different.
+// Ideally, we would always perform substitution starting with sugared 
types
+// and never need these, as we would still have expressions. Since these 
are
+// needed so rarely, it's probably a better tradeoff to just convert them
+// back to expressions.
+case TemplateArgument::Integral: {
+  IntegerLiteral ILE(Context, Arg.getAsIntegral(), Arg.getIntegralType(),
+ SourceLocation());
+  if (!checkExpr(&ILE))

mizvekov wrote:

Documenting on CheckTemplateArgument the fact the input expression might be 
temporary sounds good, will do.

Otherwise I don't think this is a FIXME situation though.

Keeping the expression around is mostly a function of preserving type sugar.

For example, the reason we hit this bug for these partial ordering test cases 
is because when checking for a non-deduced mismatch, we use canonical types 
instead of the sugared type as input to instantiation.
And the reason we do that is because there we can't deal with incomplete 
substitution on type sugar only, it would take some effort to make that work, 
but it is certainly fixable.

But since this is a best effort thing and it's very hard to prove we would 
never drop sugar which would take us here,
we might need to keep handling these cases.

One possible course of action would be to fix all these places which take us 
here, and make the test suite pass.
Once that is done, just mark all these cases unreachable.
Then we deploy that and let users report any missing cases, and keep fixing 
until there is nothing left.
If along the way we hit a case that is too complicated to be worth fixing, we 
give up and re-add these conversions.

https://github.com/llvm/llvm-project/pull/124386
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] fix template argument conversion (PR #124386)

2025-01-25 Thread Matheus Izvekov via llvm-branch-commits


@@ -5252,63 +5253,89 @@ bool Sema::CheckTemplateArgument(
 return true;
 }
 
-switch (Arg.getArgument().getKind()) {
-case TemplateArgument::Null:
-  llvm_unreachable("Should never see a NULL template argument here");
-
-case TemplateArgument::Expression: {
-  Expr *E = Arg.getArgument().getAsExpr();
+auto checkExpr = [&](Expr *E) -> Expr * {
   TemplateArgument SugaredResult, CanonicalResult;
   unsigned CurSFINAEErrors = NumSFINAEErrors;
   ExprResult Res =
   CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
 CanonicalResult, PartialOrderingTTP, CTAK);
-  if (Res.isInvalid())
-return true;
   // If the current template argument causes an error, give up now.
-  if (CurSFINAEErrors < NumSFINAEErrors)
-return true;
+  if (Res.isInvalid() || CurSFINAEErrors < NumSFINAEErrors)
+return nullptr;
+  SugaredConverted.push_back(SugaredResult);
+  CanonicalConverted.push_back(CanonicalResult);
+  return Res.get();
+};
+
+switch (Arg.getKind()) {
+case TemplateArgument::Null:
+  llvm_unreachable("Should never see a NULL template argument here");
 
+case TemplateArgument::Expression: {
+  Expr *E = Arg.getAsExpr();
+  Expr *R = checkExpr(E);
+  if (!R)
+return true;
   // If the resulting expression is new, then use it in place of the
   // old expression in the template argument.
-  if (Res.get() != E) {
-TemplateArgument TA(Res.get());
-Arg = TemplateArgumentLoc(TA, Res.get());
+  if (R != E) {
+TemplateArgument TA(R);
+ArgLoc = TemplateArgumentLoc(TA, R);
   }
-
-  SugaredConverted.push_back(SugaredResult);
-  CanonicalConverted.push_back(CanonicalResult);
   break;
 }
 
-case TemplateArgument::Declaration:
-case TemplateArgument::Integral:
+// As for the converted NTTP kinds, they still might need another
+// conversion, as the new corresponding parameter might be different.
+// Ideally, we would always perform substitution starting with sugared 
types
+// and never need these, as we would still have expressions. Since these 
are
+// needed so rarely, it's probably a better tradeoff to just convert them
+// back to expressions.
+case TemplateArgument::Integral: {
+  IntegerLiteral ILE(Context, Arg.getAsIntegral(), Arg.getIntegralType(),
+ SourceLocation());
+  if (!checkExpr(&ILE))

mizvekov wrote:

One other possibility would be to ditch the current converted template argument 
kinds, and handle canonicalization through expressions.

https://github.com/llvm/llvm-project/pull/124386
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] fix template argument conversion (PR #124386)

2025-01-25 Thread Matheus Izvekov via llvm-branch-commits


@@ -5252,63 +5253,89 @@ bool Sema::CheckTemplateArgument(
 return true;
 }
 
-switch (Arg.getArgument().getKind()) {
-case TemplateArgument::Null:
-  llvm_unreachable("Should never see a NULL template argument here");
-
-case TemplateArgument::Expression: {
-  Expr *E = Arg.getArgument().getAsExpr();
+auto checkExpr = [&](Expr *E) -> Expr * {
   TemplateArgument SugaredResult, CanonicalResult;
   unsigned CurSFINAEErrors = NumSFINAEErrors;
   ExprResult Res =
   CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
 CanonicalResult, PartialOrderingTTP, CTAK);
-  if (Res.isInvalid())
-return true;
   // If the current template argument causes an error, give up now.
-  if (CurSFINAEErrors < NumSFINAEErrors)
-return true;
+  if (Res.isInvalid() || CurSFINAEErrors < NumSFINAEErrors)
+return nullptr;
+  SugaredConverted.push_back(SugaredResult);
+  CanonicalConverted.push_back(CanonicalResult);
+  return Res.get();
+};
+
+switch (Arg.getKind()) {
+case TemplateArgument::Null:
+  llvm_unreachable("Should never see a NULL template argument here");
 
+case TemplateArgument::Expression: {
+  Expr *E = Arg.getAsExpr();
+  Expr *R = checkExpr(E);
+  if (!R)
+return true;
   // If the resulting expression is new, then use it in place of the
   // old expression in the template argument.
-  if (Res.get() != E) {
-TemplateArgument TA(Res.get());
-Arg = TemplateArgumentLoc(TA, Res.get());
+  if (R != E) {
+TemplateArgument TA(R);
+ArgLoc = TemplateArgumentLoc(TA, R);
   }
-
-  SugaredConverted.push_back(SugaredResult);
-  CanonicalConverted.push_back(CanonicalResult);
   break;
 }
 
-case TemplateArgument::Declaration:
-case TemplateArgument::Integral:
+// As for the converted NTTP kinds, they still might need another
+// conversion, as the new corresponding parameter might be different.
+// Ideally, we would always perform substitution starting with sugared 
types
+// and never need these, as we would still have expressions. Since these 
are
+// needed so rarely, it's probably a better tradeoff to just convert them
+// back to expressions.
+case TemplateArgument::Integral: {
+  IntegerLiteral ILE(Context, Arg.getAsIntegral(), Arg.getIntegralType(),
+ SourceLocation());
+  if (!checkExpr(&ILE))
+return true;
+  break;
+}
+case TemplateArgument::Declaration: {
+  DeclRefExpr DRE(Context, Arg.getAsDecl(),
+  /*RefersToEnclosingVariableOrCapture=*/false,
+  Arg.getParamTypeForDecl().getNonReferenceType(),
+  VK_LValue, SourceLocation());
+  if (!checkExpr(&DRE))
+return true;
+  break;
+}
+case TemplateArgument::NullPtr: {
+  CXXNullPtrLiteralExpr NPLE(Arg.getNullPtrType(), SourceLocation());
+  if (!checkExpr(&NPLE))
+return true;
+  break;
+}
 case TemplateArgument::StructuralValue:
-case TemplateArgument::NullPtr:
-  // We've already checked this template argument, so just copy
-  // it to the list of converted arguments.
-  SugaredConverted.push_back(Arg.getArgument());
-  CanonicalConverted.push_back(
-  Context.getCanonicalTemplateArgument(Arg.getArgument()));
+  // FIXME: Is it even possible to reach here?
+  // If this is actually used, this needs to convert the argument again.

mizvekov wrote:

Yes to asserts, that's why I made that comment.

Actually float and enums don't get us here, these are handled as declarations.
Things like "pointer to the end of an object" gets us here, but I can't think 
of a way to get those to come up in the context of injected arguments, or some 
other mechanism known to lose type sugar.

https://github.com/llvm/llvm-project/pull/124386
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] fix template argument conversion (PR #124386)

2025-01-25 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov edited 
https://github.com/llvm/llvm-project/pull/124386
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] fix template argument conversion (PR #124386)

2025-01-25 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov edited 
https://github.com/llvm/llvm-project/pull/124386
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] fix template argument conversion (PR #124386)

2025-01-25 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/124386

>From b46ef4d836d53ace49eada1da0308de8dc43bf0a Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Fri, 24 Jan 2025 19:25:38 -0300
Subject: [PATCH] [clang] fix template argument conversion

Converted template arguments need to be converted again, if
the corresponding template parameter changed, as different
conversions might apply in that case.
---
 clang/docs/ReleaseNotes.rst |   3 +
 clang/include/clang/Sema/Sema.h |   2 +
 clang/lib/Sema/SemaTemplate.cpp | 120 +---
 clang/lib/Sema/TreeTransform.h  |   6 +-
 clang/test/SemaTemplate/cwg2398.cpp |  12 ---
 5 files changed, 82 insertions(+), 61 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b89d055304f4a6..27574924a14a92 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -993,6 +993,9 @@ Bug Fixes to C++ Support
 - Fix immediate escalation not propagating through inherited constructors.  
(#GH112677)
 - Fixed assertions or false compiler diagnostics in the case of C++ modules for
   lambda functions or inline friend functions defined inside templates 
(#GH122493).
+- Fix template argument checking so that converted template arguments are
+  converted again. This fixes some issues with partial ordering involving
+  template template parameters with non-type template parameters.
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 1ea7c62cb36f05..0a7782fe7cc7e7 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -11753,6 +11753,8 @@ class Sema final : public SemaBase {
   /// If an error occurred, it returns ExprError(); otherwise, it
   /// returns the converted template argument. \p ParamType is the
   /// type of the non-type template parameter after it has been instantiated.
+  /// \p Arg is the input template argument expression to be converted.
+  /// this expression may not necessarily outlive the converted result.
   ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
QualType InstantiatedParamType, Expr *Arg,
TemplateArgument &SugaredConverted,
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 210df2836eeb07..62c45f15dec54e 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -5199,7 +5199,7 @@ convertTypeTemplateArgumentToTemplate(ASTContext 
&Context, TypeLoc TLoc) {
 }
 
 bool Sema::CheckTemplateArgument(
-NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template,
+NamedDecl *Param, TemplateArgumentLoc &ArgLoc, NamedDecl *Template,
 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
 unsigned ArgumentPackIndex,
 SmallVectorImpl &SugaredConverted,
@@ -5208,9 +5208,10 @@ bool Sema::CheckTemplateArgument(
 bool PartialOrderingTTP, bool *MatchedPackOnParmToNonPackOnArg) {
   // Check template type parameters.
   if (TemplateTypeParmDecl *TTP = dyn_cast(Param))
-return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted,
+return CheckTemplateTypeArgument(TTP, ArgLoc, SugaredConverted,
  CanonicalConverted);
 
+  const TemplateArgument &Arg = ArgLoc.getArgument();
   // Check non-type template parameters.
   if (NonTypeTemplateParmDecl *NTTP =dyn_cast(Param)) 
{
 // Do substitution on the type of the non-type template parameter
@@ -5252,63 +5253,89 @@ bool Sema::CheckTemplateArgument(
 return true;
 }
 
-switch (Arg.getArgument().getKind()) {
-case TemplateArgument::Null:
-  llvm_unreachable("Should never see a NULL template argument here");
-
-case TemplateArgument::Expression: {
-  Expr *E = Arg.getArgument().getAsExpr();
+auto checkExpr = [&](Expr *E) -> Expr * {
   TemplateArgument SugaredResult, CanonicalResult;
   unsigned CurSFINAEErrors = NumSFINAEErrors;
   ExprResult Res =
   CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
 CanonicalResult, PartialOrderingTTP, CTAK);
-  if (Res.isInvalid())
-return true;
   // If the current template argument causes an error, give up now.
-  if (CurSFINAEErrors < NumSFINAEErrors)
-return true;
+  if (Res.isInvalid() || CurSFINAEErrors < NumSFINAEErrors)
+return nullptr;
+  SugaredConverted.push_back(SugaredResult);
+  CanonicalConverted.push_back(CanonicalResult);
+  return Res.get();
+};
+
+switch (Arg.getKind()) {
+case TemplateArgument::Null:
+  llvm_unreachable("Should never see a NULL template argument here");
 
+case TemplateArgument::Expression: {
+  Expr *E = Arg.getAsExpr();
+  Expr *R = checkExpr(E);
+  if (!R)
+return true;
   // If the resulting expression is

[llvm-branch-commits] [clang] [clang] fix template argument conversion (PR #124386)

2025-01-27 Thread Matheus Izvekov via llvm-branch-commits


@@ -5252,63 +5253,73 @@ bool Sema::CheckTemplateArgument(
 return true;
 }
 
-switch (Arg.getArgument().getKind()) {
-case TemplateArgument::Null:
-  llvm_unreachable("Should never see a NULL template argument here");
-
-case TemplateArgument::Expression: {
-  Expr *E = Arg.getArgument().getAsExpr();
+auto checkExpr = [&](Expr *E) -> Expr * {
   TemplateArgument SugaredResult, CanonicalResult;
   unsigned CurSFINAEErrors = NumSFINAEErrors;
   ExprResult Res =
   CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
 CanonicalResult, PartialOrderingTTP, CTAK);
-  if (Res.isInvalid())
-return true;
   // If the current template argument causes an error, give up now.
-  if (CurSFINAEErrors < NumSFINAEErrors)
-return true;
+  if (Res.isInvalid() || CurSFINAEErrors < NumSFINAEErrors)
+return nullptr;
+  SugaredConverted.push_back(SugaredResult);
+  CanonicalConverted.push_back(CanonicalResult);
+  return Res.get();
+};
+
+switch (Arg.getKind()) {
+case TemplateArgument::Null:
+  llvm_unreachable("Should never see a NULL template argument here");
 
+case TemplateArgument::Expression: {
+  Expr *E = Arg.getAsExpr();
+  Expr *R = checkExpr(E);
+  if (!R)
+return true;
   // If the resulting expression is new, then use it in place of the
   // old expression in the template argument.
-  if (Res.get() != E) {
-TemplateArgument TA(Res.get());
-Arg = TemplateArgumentLoc(TA, Res.get());
+  if (R != E) {
+TemplateArgument TA(R);
+ArgLoc = TemplateArgumentLoc(TA, R);
   }
-
-  SugaredConverted.push_back(SugaredResult);
-  CanonicalConverted.push_back(CanonicalResult);
   break;
 }
 
-case TemplateArgument::Declaration:
+// As for the converted NTTP kinds, they still might need another
+// conversion, as the new corresponding parameter might be different.
+// Ideally, we would always perform substitution starting with sugared 
types
+// and never need these, as we would still have expressions. Since these 
are
+// needed so rarely, it's probably a better tradeoff to just convert them
+// back to expressions.
 case TemplateArgument::Integral:
-case TemplateArgument::StructuralValue:
+case TemplateArgument::Declaration:
 case TemplateArgument::NullPtr:
-  // We've already checked this template argument, so just copy
-  // it to the list of converted arguments.
-  SugaredConverted.push_back(Arg.getArgument());
-  CanonicalConverted.push_back(
-  Context.getCanonicalTemplateArgument(Arg.getArgument()));
+case TemplateArgument::StructuralValue: {
+  // FIXME: StructuralValue is untested here.
+  ExprResult R =
+  BuildExpressionFromNonTypeTemplateArgument(Arg, SourceLocation());

mizvekov wrote:

This is used elsewhere to similar effect, and yes it may produce ASTContext 
nodes which are unreachable, which is something we are in general not very good 
at avoiding.

We may rework that function in the future so it can produce a temporary 
expression. The previous solution in the patch was better in that effect, but 
would end up duplicating `BuildExpressionFromNonTypeTemplateArgument` in part.

https://github.com/llvm/llvm-project/pull/124386
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] NFC: cleanup check template argument (PR #124668)

2025-01-27 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/124668

None

>From 4387c95a4bd6ccfc74e95683da0829fde41560c1 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Mon, 27 Jan 2025 19:18:27 -0300
Subject: [PATCH] [clang] NFC: cleanup check template argument

---
 clang/include/clang/Sema/Sema.h   |  70 +++--
 clang/lib/Sema/SemaLookup.cpp |   6 +-
 clang/lib/Sema/SemaTemplate.cpp   | 277 +-
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 208 +++--
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  |  47 +--
 5 files changed, 307 insertions(+), 301 deletions(-)

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 1ea7c62cb36f05..ef097f24fb3f52 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -11650,6 +11650,33 @@ class Sema final : public SemaBase {
 CTAK_DeducedFromArrayBound
   };
 
+  struct CheckTemplateArgumentInfo {
+explicit CheckTemplateArgumentInfo(bool PartialOrdering = false,
+   bool MatchingTTP = false)
+: PartialOrdering(PartialOrdering), MatchingTTP(MatchingTTP) {}
+CheckTemplateArgumentInfo(const CheckTemplateArgumentInfo &) = delete;
+CheckTemplateArgumentInfo &
+operator=(const CheckTemplateArgumentInfo &) = delete;
+
+/// The checked, converted argument will be added to the
+/// end of these vectors.
+SmallVector SugaredConverted, CanonicalConverted;
+
+/// The check is being performed in the context of partial ordering.
+bool PartialOrdering;
+
+/// If true, assume these template arguments are
+/// the injected template arguments for a template template parameter.
+/// This will relax the requirement that all its possible uses are valid:
+/// TTP checking is loose, and assumes that invalid uses will be diagnosed
+/// during instantiation.
+bool MatchingTTP;
+
+/// Is set to true when, in the context of TTP matching, a pack parameter
+/// matches non-pack arguments.
+bool MatchedPackOnParmToNonPackOnArg;
+  };
+
   /// Check that the given template argument corresponds to the given
   /// template parameter.
   ///
@@ -11669,22 +11696,16 @@ class Sema final : public SemaBase {
   /// \param ArgumentPackIndex The index into the argument pack where this
   /// argument will be placed. Only valid if the parameter is a parameter pack.
   ///
-  /// \param Converted The checked, converted argument will be added to the
-  /// end of this small vector.
-  ///
   /// \param CTAK Describes how we arrived at this particular template 
argument:
   /// explicitly written, deduced, etc.
   ///
   /// \returns true on error, false otherwise.
-  bool
-  CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg,
-NamedDecl *Template, SourceLocation TemplateLoc,
-SourceLocation RAngleLoc, unsigned ArgumentPackIndex,
-SmallVectorImpl &SugaredConverted,
-SmallVectorImpl &CanonicalConverted,
-CheckTemplateArgumentKind CTAK, bool PartialOrdering,
-bool PartialOrderingTTP,
-bool *MatchedPackOnParmToNonPackOnArg);
+  bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg,
+ NamedDecl *Template, SourceLocation TemplateLoc,
+ SourceLocation RAngleLoc,
+ unsigned ArgumentPackIndex,
+ CheckTemplateArgumentInfo &CTAI,
+ CheckTemplateArgumentKind CTAK);
 
   /// Check that the given template arguments can be provided to
   /// the given template, converting the arguments along the way.
@@ -11717,22 +11738,15 @@ class Sema final : public SemaBase {
   /// \param DefaultArgs any default arguments from template specialization
   /// deduction.
   ///
-  /// \param PartialOrderingTTP If true, assume these template arguments are
-  /// the injected template arguments for a template template parameter.
-  /// This will relax the requirement that all its possible uses are valid:
-  /// TTP checking is loose, and assumes that invalid uses will be diagnosed
-  /// during instantiation.
-  ///
   /// \returns true if an error occurred, false otherwise.
-  bool CheckTemplateArgumentList(
-  TemplateDecl *Template, SourceLocation TemplateLoc,
-  TemplateArgumentListInfo &TemplateArgs,
-  const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
-  SmallVectorImpl &SugaredConverted,
-  SmallVectorImpl &CanonicalConverted,
-  bool UpdateArgsWithConversions = true,
-  bool *ConstraintsNotSatisfied = nullptr, bool PartialOrderingTTP = false,
-  bool *MatchedPackOnParmToNonPackOnArg = nullptr);
+  bool CheckTemplateArgumentList(TemplateDecl *Template,
+ SourceLocati

[llvm-branch-commits] [clang] [clang] NFC: cleanup check template argument (PR #124668)

2025-01-28 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/124668

>From db745bb131582139f29d471636cebeb78f25fb1c Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Mon, 27 Jan 2025 19:18:27 -0300
Subject: [PATCH] [clang] NFC: cleanup check template argument

---
 clang/include/clang/Sema/Sema.h   |  70 +++--
 clang/lib/Sema/SemaLookup.cpp |   6 +-
 clang/lib/Sema/SemaTemplate.cpp   | 277 +-
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 208 +++--
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  |  47 +--
 5 files changed, 307 insertions(+), 301 deletions(-)

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 8a6dd4f6820bc7..6bffe5241e1694 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -11651,6 +11651,33 @@ class Sema final : public SemaBase {
 CTAK_DeducedFromArrayBound
   };
 
+  struct CheckTemplateArgumentInfo {
+explicit CheckTemplateArgumentInfo(bool PartialOrdering = false,
+   bool MatchingTTP = false)
+: PartialOrdering(PartialOrdering), MatchingTTP(MatchingTTP) {}
+CheckTemplateArgumentInfo(const CheckTemplateArgumentInfo &) = delete;
+CheckTemplateArgumentInfo &
+operator=(const CheckTemplateArgumentInfo &) = delete;
+
+/// The checked, converted argument will be added to the
+/// end of these vectors.
+SmallVector SugaredConverted, CanonicalConverted;
+
+/// The check is being performed in the context of partial ordering.
+bool PartialOrdering;
+
+/// If true, assume these template arguments are
+/// the injected template arguments for a template template parameter.
+/// This will relax the requirement that all its possible uses are valid:
+/// TTP checking is loose, and assumes that invalid uses will be diagnosed
+/// during instantiation.
+bool MatchingTTP;
+
+/// Is set to true when, in the context of TTP matching, a pack parameter
+/// matches non-pack arguments.
+bool MatchedPackOnParmToNonPackOnArg;
+  };
+
   /// Check that the given template argument corresponds to the given
   /// template parameter.
   ///
@@ -11670,22 +11697,16 @@ class Sema final : public SemaBase {
   /// \param ArgumentPackIndex The index into the argument pack where this
   /// argument will be placed. Only valid if the parameter is a parameter pack.
   ///
-  /// \param Converted The checked, converted argument will be added to the
-  /// end of this small vector.
-  ///
   /// \param CTAK Describes how we arrived at this particular template 
argument:
   /// explicitly written, deduced, etc.
   ///
   /// \returns true on error, false otherwise.
-  bool
-  CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg,
-NamedDecl *Template, SourceLocation TemplateLoc,
-SourceLocation RAngleLoc, unsigned ArgumentPackIndex,
-SmallVectorImpl &SugaredConverted,
-SmallVectorImpl &CanonicalConverted,
-CheckTemplateArgumentKind CTAK, bool PartialOrdering,
-bool PartialOrderingTTP,
-bool *MatchedPackOnParmToNonPackOnArg);
+  bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg,
+ NamedDecl *Template, SourceLocation TemplateLoc,
+ SourceLocation RAngleLoc,
+ unsigned ArgumentPackIndex,
+ CheckTemplateArgumentInfo &CTAI,
+ CheckTemplateArgumentKind CTAK);
 
   /// Check that the given template arguments can be provided to
   /// the given template, converting the arguments along the way.
@@ -11718,22 +11739,15 @@ class Sema final : public SemaBase {
   /// \param DefaultArgs any default arguments from template specialization
   /// deduction.
   ///
-  /// \param PartialOrderingTTP If true, assume these template arguments are
-  /// the injected template arguments for a template template parameter.
-  /// This will relax the requirement that all its possible uses are valid:
-  /// TTP checking is loose, and assumes that invalid uses will be diagnosed
-  /// during instantiation.
-  ///
   /// \returns true if an error occurred, false otherwise.
-  bool CheckTemplateArgumentList(
-  TemplateDecl *Template, SourceLocation TemplateLoc,
-  TemplateArgumentListInfo &TemplateArgs,
-  const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
-  SmallVectorImpl &SugaredConverted,
-  SmallVectorImpl &CanonicalConverted,
-  bool UpdateArgsWithConversions = true,
-  bool *ConstraintsNotSatisfied = nullptr, bool PartialOrderingTTP = false,
-  bool *MatchedPackOnParmToNonPackOnArg = nullptr);
+  bool CheckTemplateArgumentList(TemplateDecl *Template,
+ SourceLocation Tem

[llvm-branch-commits] [clang] [clang] fix template argument conversion (PR #124386)

2025-01-25 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov edited 
https://github.com/llvm/llvm-project/pull/124386
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang] fix template argument conversion (PR #124386)

2025-01-25 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/124386

>From 0f821a22157df87237529a1bde777e82072fe473 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Fri, 24 Jan 2025 19:25:38 -0300
Subject: [PATCH] [clang] fix template argument conversion

Converted template arguments need to be converted again, if
the corresponding template parameter changed, as different
conversions might apply in that case.
---
 clang/docs/ReleaseNotes.rst |   3 +
 clang/lib/Sema/SemaTemplate.cpp | 120 +---
 clang/lib/Sema/TreeTransform.h  |   6 +-
 clang/test/SemaTemplate/cwg2398.cpp |  12 ---
 4 files changed, 80 insertions(+), 61 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b89d055304f4a6..27574924a14a92 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -993,6 +993,9 @@ Bug Fixes to C++ Support
 - Fix immediate escalation not propagating through inherited constructors.  
(#GH112677)
 - Fixed assertions or false compiler diagnostics in the case of C++ modules for
   lambda functions or inline friend functions defined inside templates 
(#GH122493).
+- Fix template argument checking so that converted template arguments are
+  converted again. This fixes some issues with partial ordering involving
+  template template parameters with non-type template parameters.
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 210df2836eeb07..62c45f15dec54e 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -5199,7 +5199,7 @@ convertTypeTemplateArgumentToTemplate(ASTContext 
&Context, TypeLoc TLoc) {
 }
 
 bool Sema::CheckTemplateArgument(
-NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template,
+NamedDecl *Param, TemplateArgumentLoc &ArgLoc, NamedDecl *Template,
 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
 unsigned ArgumentPackIndex,
 SmallVectorImpl &SugaredConverted,
@@ -5208,9 +5208,10 @@ bool Sema::CheckTemplateArgument(
 bool PartialOrderingTTP, bool *MatchedPackOnParmToNonPackOnArg) {
   // Check template type parameters.
   if (TemplateTypeParmDecl *TTP = dyn_cast(Param))
-return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted,
+return CheckTemplateTypeArgument(TTP, ArgLoc, SugaredConverted,
  CanonicalConverted);
 
+  const TemplateArgument &Arg = ArgLoc.getArgument();
   // Check non-type template parameters.
   if (NonTypeTemplateParmDecl *NTTP =dyn_cast(Param)) 
{
 // Do substitution on the type of the non-type template parameter
@@ -5252,63 +5253,89 @@ bool Sema::CheckTemplateArgument(
 return true;
 }
 
-switch (Arg.getArgument().getKind()) {
-case TemplateArgument::Null:
-  llvm_unreachable("Should never see a NULL template argument here");
-
-case TemplateArgument::Expression: {
-  Expr *E = Arg.getArgument().getAsExpr();
+auto checkExpr = [&](Expr *E) -> Expr * {
   TemplateArgument SugaredResult, CanonicalResult;
   unsigned CurSFINAEErrors = NumSFINAEErrors;
   ExprResult Res =
   CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
 CanonicalResult, PartialOrderingTTP, CTAK);
-  if (Res.isInvalid())
-return true;
   // If the current template argument causes an error, give up now.
-  if (CurSFINAEErrors < NumSFINAEErrors)
-return true;
+  if (Res.isInvalid() || CurSFINAEErrors < NumSFINAEErrors)
+return nullptr;
+  SugaredConverted.push_back(SugaredResult);
+  CanonicalConverted.push_back(CanonicalResult);
+  return Res.get();
+};
+
+switch (Arg.getKind()) {
+case TemplateArgument::Null:
+  llvm_unreachable("Should never see a NULL template argument here");
 
+case TemplateArgument::Expression: {
+  Expr *E = Arg.getAsExpr();
+  Expr *R = checkExpr(E);
+  if (!R)
+return true;
   // If the resulting expression is new, then use it in place of the
   // old expression in the template argument.
-  if (Res.get() != E) {
-TemplateArgument TA(Res.get());
-Arg = TemplateArgumentLoc(TA, Res.get());
+  if (R != E) {
+TemplateArgument TA(R);
+ArgLoc = TemplateArgumentLoc(TA, R);
   }
-
-  SugaredConverted.push_back(SugaredResult);
-  CanonicalConverted.push_back(CanonicalResult);
   break;
 }
 
-case TemplateArgument::Declaration:
-case TemplateArgument::Integral:
+// As for the converted NTTP kinds, they still might need another
+// conversion, as the new corresponding parameter might be different.
+// Ideally, we would always perform substitution starting with sugared 
types
+// and never need these, as we would still have expressions. Since these 
are
+// needed so rarely, it's probably a better 

[llvm-branch-commits] [clang] [clang] fix template argument conversion (PR #124386)

2025-01-25 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/124386

>From 4f4e65818c2fd85814efc63f779026853820ad76 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Fri, 24 Jan 2025 19:25:38 -0300
Subject: [PATCH] [clang] fix template argument conversion

Converted template arguments need to be converted again, if
the corresponding template parameter changed, as different
conversions might apply in that case.
---
 clang/docs/ReleaseNotes.rst |   3 +
 clang/include/clang/AST/Expr.h  |  10 ++
 clang/include/clang/Sema/Sema.h |   2 +
 clang/lib/AST/TemplateBase.cpp  |  12 +--
 clang/lib/Sema/SemaTemplate.cpp | 145 +++-
 clang/lib/Sema/TreeTransform.h  |   6 +-
 clang/test/SemaTemplate/cwg2398.cpp |  20 
 7 files changed, 122 insertions(+), 76 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b89d055304f4a6..27574924a14a92 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -993,6 +993,9 @@ Bug Fixes to C++ Support
 - Fix immediate escalation not propagating through inherited constructors.  
(#GH112677)
 - Fixed assertions or false compiler diagnostics in the case of C++ modules for
   lambda functions or inline friend functions defined inside templates 
(#GH122493).
+- Fix template argument checking so that converted template arguments are
+  converted again. This fixes some issues with partial ordering involving
+  template template parameters with non-type template parameters.
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index 708c8656decbe0..919025bec4d6da 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -2262,6 +2262,16 @@ class UnaryOperator final
   }
 
 public:
+  enum OnStack_t { OnStack };
+  UnaryOperator(OnStack_t _, const ASTContext &Ctx, Expr *input, Opcode opc,
+QualType type, ExprValueKind VK, ExprObjectKind OK,
+SourceLocation l, bool CanOverflow,
+FPOptionsOverride FPFeatures)
+  : UnaryOperator(Ctx, input, opc, type, VK, OK, l, CanOverflow,
+  FPFeatures) {
+assert(!FPFeatures.requiresTrailingStorage());
+  }
+
   static UnaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures);
 
   static UnaryOperator *Create(const ASTContext &C, Expr *input, Opcode opc,
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 1ea7c62cb36f05..0a7782fe7cc7e7 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -11753,6 +11753,8 @@ class Sema final : public SemaBase {
   /// If an error occurred, it returns ExprError(); otherwise, it
   /// returns the converted template argument. \p ParamType is the
   /// type of the non-type template parameter after it has been instantiated.
+  /// \p Arg is the input template argument expression to be converted.
+  /// this expression may not necessarily outlive the converted result.
   ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
QualType InstantiatedParamType, Expr *Arg,
TemplateArgument &SugaredConverted,
diff --git a/clang/lib/AST/TemplateBase.cpp b/clang/lib/AST/TemplateBase.cpp
index 3625b6e435a556..0eef8f305fcb39 100644
--- a/clang/lib/AST/TemplateBase.cpp
+++ b/clang/lib/AST/TemplateBase.cpp
@@ -515,19 +515,17 @@ void TemplateArgument::print(const PrintingPolicy 
&Policy, raw_ostream &Out,
   }
 
   case Declaration: {
-NamedDecl *ND = getAsDecl();
+ValueDecl *VD = getAsDecl();
 if (getParamTypeForDecl()->isRecordType()) {
-  if (auto *TPO = dyn_cast(ND)) {
+  if (auto *TPO = dyn_cast(VD)) {
 TPO->getType().getUnqualifiedType().print(Out, Policy);
 TPO->printAsInit(Out, Policy);
 break;
   }
 }
-if (auto *VD = dyn_cast(ND)) {
-  if (needsAmpersandOnTemplateArg(getParamTypeForDecl(), VD->getType()))
-Out << "&";
-}
-ND->printQualifiedName(Out);
+if (needsAmpersandOnTemplateArg(getParamTypeForDecl(), VD->getType()))
+  Out << "&";
+VD->printQualifiedName(Out);
 break;
   }
 
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 210df2836eeb07..7abe0ed4f1c133 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -5199,7 +5199,7 @@ convertTypeTemplateArgumentToTemplate(ASTContext 
&Context, TypeLoc TLoc) {
 }
 
 bool Sema::CheckTemplateArgument(
-NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template,
+NamedDecl *Param, TemplateArgumentLoc &ArgLoc, NamedDecl *Template,
 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
 unsigned ArgumentPackIndex,
 SmallVectorImpl &SugaredConverted,
@@ -5208,9 +5208,10 @@ bool Sema::CheckTemplateArgument(
 bool PartialOrderingTTP, bool *MatchedP

[llvm-branch-commits] [clang] [clang] fix template argument conversion (PR #124386)

2025-01-25 Thread Matheus Izvekov via llvm-branch-commits

mizvekov wrote:

I just pushed changes to fix pointer NTTP test cases.

https://github.com/llvm/llvm-project/pull/124386
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [clang-tools-extra] [lldb] [clang] Template Specialization Resugaring - TypeDecl (PR #132441)

2025-03-21 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/132441

>From 4571fada1ea055a845bf5c4eb3d1a20904f768c6 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Mon, 30 May 2022 01:46:31 +0200
Subject: [PATCH] [clang] Template Specialization Resugaring - TypeDecl

This is the introductory patch for a larger work which
intends to solve the long standing C++ issue with losing
type sugar when acessing template specializations.

The well known example here is specializing a template
with `std::string`, but getting diagnostics related to
`std::basic_string` instead.

This implements a transform which, upon member access,
propagates type sugar from the naming context into the
accessed entity.

It also implements a single use of this transform,
resugaring access to TypeDecls.

For more details and discussion see:
https://discourse.llvm.org/t/rfc-improving-diagnostics-with-template-specialization-resugaring/64294

This is ready for review, although maybe not finished and
there is some more stuff that could be done either here
or in follow ups.

* Its worth exploring if a global resugaring cache is
  worthwhile, besides the current operational cache.
  A global cache would be more expensive to index, so there
  is a tradeoff, and maybe should be used of the whole
  result of the operation, while keeping the existing
  cache for sub-results.
* It would be ideal if the transform could live in ASTContext
  instead of Sema. There are a few dependencies that would
  have to be tackled.
  * Template arguments deduced for partial specializations.
  * Some kinds of type adjustments currently require Sema.

Differential Revision: https://reviews.llvm.org/D127695
---
 .../readability/QualifiedAutoCheck.cpp|   2 +-
 clang/include/clang/AST/ASTContext.h  |  13 +-
 clang/include/clang/AST/Type.h|  11 +-
 clang/include/clang/Sema/Sema.h   |   8 +-
 clang/lib/AST/ASTContext.cpp  |  17 +-
 clang/lib/Sema/SemaCXXScopeSpec.cpp   |   5 +-
 clang/lib/Sema/SemaCoroutine.cpp  |   1 +
 clang/lib/Sema/SemaDecl.cpp   |   9 +-
 clang/lib/Sema/SemaDeclCXX.cpp|   2 +-
 clang/lib/Sema/SemaTemplate.cpp   | 722 +-
 clang/lib/Sema/SemaTemplateDeduction.cpp  |   6 +-
 clang/lib/Sema/SemaType.cpp   |  10 +-
 ...openmp-begin-declare-variant_reference.cpp |   8 +-
 clang/test/AST/ast-dump-template-name.cpp |   7 +-
 clang/test/CXX/temp/temp.param/p15-cxx0x.cpp  |   4 +-
 clang/test/Sema/Resugar/resugar-types.cpp | 209 +
 .../iterator/TestIteratorFromStdModule.py |   6 +-
 17 files changed, 989 insertions(+), 51 deletions(-)
 create mode 100644 clang/test/Sema/Resugar/resugar-types.cpp

diff --git a/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp
index e843c593a92cc..679fbd75d2479 100644
--- a/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp
@@ -126,7 +126,7 @@ void QualifiedAutoCheck::registerMatchers(MatchFinder 
*Finder) {
   auto UnlessFunctionType = 
unless(hasUnqualifiedDesugaredType(functionType()));
   auto IsAutoDeducedToPointer = [](const auto &...InnerMatchers) {
 return autoType(hasDeducedType(
-hasUnqualifiedDesugaredType(pointerType(pointee(InnerMatchers...);
+hasCanonicalType(pointerType(pointee(InnerMatchers...);
   };
 
   Finder->addMatcher(
diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index ef596f99262be..23d789d8466d3 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -1319,8 +1319,6 @@ class ASTContext : public RefCountedBase {
 
   QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
 
-  QualType getPipeType(QualType T, bool ReadOnly) const;
-
 public:
   /// Return the uniqued reference to the type for an address space
   /// qualified type with the specified type and address space.
@@ -1500,6 +1498,9 @@ class ASTContext : public RefCountedBase {
   /// blocks.
   QualType getBlockDescriptorType() const;
 
+  // Return a pipe type for the specified type.
+  QualType getPipeType(QualType T, bool ReadOnly) const;
+
   /// Return a read_only pipe type for the specified type.
   QualType getReadPipeType(QualType T) const;
 
@@ -1901,10 +1902,10 @@ class ASTContext : public RefCountedBase {
   /// C++11 decltype.
   QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
 
-  QualType getPackIndexingType(QualType Pattern, Expr *IndexExpr,
-   bool FullySubstituted = false,
-   ArrayRef Expansions = {},
-   int Index = -1) const;
+  QualType getPackIndexingType(
+  QualType Pattern, Expr *IndexExpr, bool FullySubstituted = false,
+  ArrayRef Expans

[llvm-branch-commits] [clang] [clang] resugar decltype of DeclRefExpr (PR #132447)

2025-03-21 Thread Matheus Izvekov via llvm-branch-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/132447

>From 29cc63d882332f4c476388a8817def7de564ad4b Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Fri, 14 Mar 2025 19:41:38 -0300
Subject: [PATCH] [clang] resugar decltype of DeclRefExpr

This keeps around the resugared DeclType for DeclRefExpr,
which is otherwise partially lost as the expression type
removes top level references.

This helps 'decltype' resugaring work without any loss
of information.
---
 clang/include/clang/AST/Expr.h| 32 +++--
 clang/include/clang/AST/Stmt.h|  2 +
 clang/include/clang/Sema/Sema.h   | 20 +++---
 clang/lib/AST/ASTImporter.cpp |  3 +-
 clang/lib/AST/Expr.cpp| 82 +++
 clang/lib/CodeGen/CGExpr.cpp  |  4 +-
 clang/lib/Sema/SemaChecking.cpp   |  3 +-
 clang/lib/Sema/SemaDeclCXX.cpp| 19 +++---
 clang/lib/Sema/SemaExpr.cpp   | 81 +++---
 clang/lib/Sema/SemaOpenMP.cpp | 11 ++-
 clang/lib/Sema/SemaOverload.cpp   | 25 ---
 clang/lib/Sema/SemaSYCL.cpp   |  2 +-
 clang/lib/Sema/SemaTemplate.cpp   | 13 
 clang/lib/Sema/SemaType.cpp   |  9 ++-
 clang/lib/Sema/TreeTransform.h|  5 +-
 clang/lib/Serialization/ASTReaderStmt.cpp |  8 ++-
 clang/lib/Serialization/ASTWriterStmt.cpp |  6 +-
 clang/test/Sema/Resugar/resugar-expr.cpp  |  6 +-
 18 files changed, 201 insertions(+), 130 deletions(-)

diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index 2ba787ac6df55..e92f6696027f9 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -1266,7 +1266,7 @@ class DeclRefExpr final
 : public Expr,
   private llvm::TrailingObjects {
+TemplateArgumentLoc, QualType> {
   friend class ASTStmtReader;
   friend class ASTStmtWriter;
   friend TrailingObjects;
@@ -1292,17 +1292,27 @@ class DeclRefExpr final
 return hasTemplateKWAndArgsInfo();
   }
 
+  size_t numTrailingObjects(OverloadToken) const {
+return getNumTemplateArgs();
+  }
+
+  size_t numTrailingObjects(OverloadToken) const {
+return HasResugaredDeclType();
+  }
+
   /// Test whether there is a distinct FoundDecl attached to the end of
   /// this DRE.
   bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
 
+  static bool needsDeclTypeStorage(ValueDecl *VD, QualType DeclType);
+
   DeclRefExpr(const ASTContext &Ctx, NestedNameSpecifierLoc QualifierLoc,
   SourceLocation TemplateKWLoc, ValueDecl *D,
   bool RefersToEnclosingVariableOrCapture,
   const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
   const TemplateArgumentListInfo *TemplateArgs,
   const TemplateArgumentList *ConvertedArgs, QualType T,
-  ExprValueKind VK, NonOdrUseReason NOUR);
+  ExprValueKind VK, QualType DeclType, NonOdrUseReason NOUR);
 
   /// Construct an empty declaration reference expression.
   explicit DeclRefExpr(EmptyShell Empty) : Expr(DeclRefExprClass, Empty) {}
@@ -1318,7 +1328,8 @@ class DeclRefExpr final
   Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
  SourceLocation TemplateKWLoc, ValueDecl *D,
  bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
- QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
+ QualType T, ExprValueKind VK, QualType DeclType = QualType(),
+ NamedDecl *FoundD = nullptr,
  const TemplateArgumentListInfo *TemplateArgs = nullptr,
  const TemplateArgumentList *ConvertedArgs = nullptr,
  NonOdrUseReason NOUR = NOUR_None);
@@ -1328,7 +1339,7 @@ class DeclRefExpr final
  SourceLocation TemplateKWLoc, ValueDecl *D,
  bool RefersToEnclosingVariableOrCapture,
  const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
- NamedDecl *FoundD = nullptr,
+ QualType DeclType = QualType(), NamedDecl *FoundD = nullptr,
  const TemplateArgumentListInfo *TemplateArgs = nullptr,
  const TemplateArgumentList *ConvertedArgs = nullptr,
  NonOdrUseReason NOUR = NOUR_None);
@@ -1337,11 +1348,22 @@ class DeclRefExpr final
   static DeclRefExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
   bool HasFoundDecl,
   bool HasTemplateKWAndArgsInfo,
-  unsigned NumTemplateArgs);
+  unsigned NumTemplateArgs,
+  bool HasResugaredDeclType);
 
   ValueDecl *getDecl() { return D; }
   const ValueDecl *getDecl() const { return D; }
   void setDecl(ValueDecl *NewD);
+  void recomputeDependency();
+
+  bool HasResugaredDeclType() const {
+return DeclRefExprBits.HasResugaredDeclType;
+  }
+  QualType getDeclTyp

  1   2   3   >