[clang] [webkit.RefCntblBaseVirtualDtor] Allow CRTP classes without a virtual destructor. (PR #92837)

2024-05-26 Thread Ryosuke Niwa via cfe-commits


@@ -11,16 +11,116 @@
 #include "PtrTypesSemantics.h"
 #include "clang/AST/CXXInheritance.h"
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/AST/StmtVisitor.h"
 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
+#include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/SetVector.h"
 #include 
 
 using namespace clang;
 using namespace ento;
 
 namespace {
+
+class DerefFuncDeleteExprVisitor
+: public ConstStmtVisitor {
+  // Returns true if any of child statements return true.
+  bool VisitChildren(const Stmt *S) {
+for (const Stmt *Child : S->children()) {
+  if (Child && Visit(Child))
+return true;
+}
+return false;
+  }
+
+  bool VisitBody(const Stmt *Body) {
+if (!Body)
+  return false;
+
+auto [It, IsNew] = VisitedBody.insert(Body);
+if (!IsNew) // This body is recursive
+  return false;
+
+return Visit(Body);
+  }
+
+public:
+  DerefFuncDeleteExprVisitor(const TemplateArgumentList &ArgList,
+ const CXXRecordDecl *ClassDecl)
+  : ArgList(&ArgList), ClassDecl(ClassDecl) {}
+
+  DerefFuncDeleteExprVisitor(const CXXRecordDecl *ClassDecl)
+  : ClassDecl(ClassDecl) {}
+
+  std::optional HasSpecializedDelete(CXXMethodDecl *Decl) {
+if (auto *Body = Decl->getBody())
+  return VisitBody(Body);
+if (auto *Tmpl = Decl->getTemplateInstantiationPattern())

rniwa wrote:

Oh oops, sorry about that.

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


[clang] [Clang] Rewrite SourceLocExpr in default args (PR #93383)

2024-05-26 Thread via cfe-commits

https://github.com/cor3ntin updated 
https://github.com/llvm/llvm-project/pull/93383

>From ce5f58180635968c1525b9a3d267f91c495f3058 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Sat, 25 May 2024 20:49:22 +0200
Subject: [PATCH 1/2] [Clang] Rewrite SourceLocExpr in default args

In order for their dependency to be computed correctly,
SourceLocExpr should refer to the context in which they are used.

Fixes #92680
---
 clang/docs/ReleaseNotes.rst|  2 ++
 clang/lib/Sema/SemaExpr.cpp|  9 +
 clang/test/SemaCXX/source_location.cpp | 17 +
 3 files changed, 28 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7bcdee96e213e..3f2c3c1e5a65d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -771,6 +771,8 @@ Bug Fixes to C++ Support
   Fixes (#GH87210), (GH89541).
 - Clang no longer tries to check if an expression is immediate-escalating in 
an unevaluated context.
   Fixes (#GH91308).
+- Fix a crash caused by a regression in the handling of ``source_location``
+  in dependent contexts. Fixes (#GH92680).
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index ff9c5ead36dcf..ef3162ca989c4 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -5506,6 +5506,15 @@ struct EnsureImmediateInvocationInDefaultArgs
   // cause it to incorrectly point it to the outermost class
   // in the case of nested struct initialization.
   ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }
+
+  // Rewrite to source location to refer to the context in which they are used
+  ExprResult TransformSourceLocExpr(SourceLocExpr *E) {
+if (E->getParentContext() == SemaRef.CurContext)
+  return E;
+return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getType(),
+ E->getBeginLoc(), E->getEndLoc(),
+ SemaRef.CurContext);
+  }
 };
 
 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
diff --git a/clang/test/SemaCXX/source_location.cpp 
b/clang/test/SemaCXX/source_location.cpp
index 63157cfacdd98..6b3610d703e71 100644
--- a/clang/test/SemaCXX/source_location.cpp
+++ b/clang/test/SemaCXX/source_location.cpp
@@ -912,3 +912,20 @@ auto g() {
 }
 
 }
+
+namespace GH92680 {
+
+struct IntConstuctible {
+  IntConstuctible(std::source_location = std::source_location::current());
+};
+
+template 
+auto construct_at(IntConstuctible) -> decltype(IntConstuctible()) {
+  return {};
+}
+
+void test() {
+  construct_at({});
+}
+
+}

>From ec59077109616b62a1421aab034caa6cb6148fe4 Mon Sep 17 00:00:00 2001
From: cor3ntin 
Date: Sun, 26 May 2024 09:18:00 +0200
Subject: [PATCH 2/2] Update clang/lib/Sema/SemaExpr.cpp

Co-authored-by: Timm Baeder 
---
 clang/lib/Sema/SemaExpr.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index ef3162ca989c4..410f80ae864a1 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -5507,7 +5507,7 @@ struct EnsureImmediateInvocationInDefaultArgs
   // in the case of nested struct initialization.
   ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }
 
-  // Rewrite to source location to refer to the context in which they are used
+  // Rewrite to source location to refer to the context in which they are used.
   ExprResult TransformSourceLocExpr(SourceLocExpr *E) {
 if (E->getParentContext() == SemaRef.CurContext)
   return E;

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


[clang] 70d6e7c - [Clang] Rewrite SourceLocExpr in default args (#93383)

2024-05-26 Thread via cfe-commits

Author: cor3ntin
Date: 2024-05-26T09:18:33+02:00
New Revision: 70d6e7c09fd1a79ca5c2c2deeb72e6b0e1e80a52

URL: 
https://github.com/llvm/llvm-project/commit/70d6e7c09fd1a79ca5c2c2deeb72e6b0e1e80a52
DIFF: 
https://github.com/llvm/llvm-project/commit/70d6e7c09fd1a79ca5c2c2deeb72e6b0e1e80a52.diff

LOG: [Clang] Rewrite SourceLocExpr in default args (#93383)

In order for their dependency to be computed correctly, SourceLocExpr
should refer to the context in which they are used.

Fixes #92680

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaExpr.cpp
clang/test/SemaCXX/source_location.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index d023f53754cb3..825e91876ffce 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -794,6 +794,8 @@ Bug Fixes to C++ Support
   Fixes (#GH87210), (GH89541).
 - Clang no longer tries to check if an expression is immediate-escalating in 
an unevaluated context.
   Fixes (#GH91308).
+- Fix a crash caused by a regression in the handling of ``source_location``
+  in dependent contexts. Fixes (#GH92680).
 
 Bug Fixes to AST Handling
 ^

diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index ff9c5ead36dcf..410f80ae864a1 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -5506,6 +5506,15 @@ struct EnsureImmediateInvocationInDefaultArgs
   // cause it to incorrectly point it to the outermost class
   // in the case of nested struct initialization.
   ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }
+
+  // Rewrite to source location to refer to the context in which they are used.
+  ExprResult TransformSourceLocExpr(SourceLocExpr *E) {
+if (E->getParentContext() == SemaRef.CurContext)
+  return E;
+return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getType(),
+ E->getBeginLoc(), E->getEndLoc(),
+ SemaRef.CurContext);
+  }
 };
 
 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,

diff  --git a/clang/test/SemaCXX/source_location.cpp 
b/clang/test/SemaCXX/source_location.cpp
index 63157cfacdd98..6b3610d703e71 100644
--- a/clang/test/SemaCXX/source_location.cpp
+++ b/clang/test/SemaCXX/source_location.cpp
@@ -912,3 +912,20 @@ auto g() {
 }
 
 }
+
+namespace GH92680 {
+
+struct IntConstuctible {
+  IntConstuctible(std::source_location = std::source_location::current());
+};
+
+template 
+auto construct_at(IntConstuctible) -> decltype(IntConstuctible()) {
+  return {};
+}
+
+void test() {
+  construct_at({});
+}
+
+}



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


[clang] [Clang] Rewrite SourceLocExpr in default args (PR #93383)

2024-05-26 Thread via cfe-commits

https://github.com/cor3ntin closed 
https://github.com/llvm/llvm-project/pull/93383
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-format] Add LeftWithLastLine to AlignEscapedNewlines option (PR #93402)

2024-05-26 Thread Owen Pan via cfe-commits

https://github.com/owenca created 
https://github.com/llvm/llvm-project/pull/93402

Closes #92999.

>From fc9097e064e2d64832acc611b2a8d50d332119d6 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sun, 26 May 2024 00:23:35 -0700
Subject: [PATCH] [clang-format] Add LeftWithLastLine to AlignEscapedNewlines
 option

Closes #92999.
---
 clang/docs/ClangFormatStyleOptions.rst | 12 +++--
 clang/docs/ReleaseNotes.rst|  3 ++-
 clang/include/clang/Format/Format.h| 12 ++---
 clang/lib/Format/Format.cpp|  1 +
 clang/lib/Format/WhitespaceManager.cpp | 29 ++
 clang/unittests/Format/ConfigParseTest.cpp |  2 ++
 clang/unittests/Format/FormatTest.cpp  | 20 +++
 7 files changed, 62 insertions(+), 17 deletions(-)

diff --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 6d092219877f9..1a7d0e6a05e31 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -1421,13 +1421,21 @@ the configuration (without a prefix: ``Auto``).
 
 .. code-block:: c++
 
-  true:
   #define A   \
 int ; \
 int b;\
 int dd;
 
-  false:
+  * ``ENAS_LeftWithLastLine`` (in configuration: ``LeftWithLastLine``)
+Align escaped newlines as far left as possible, using the last line of
+the preprocessor directive as the reference if it's the longest.
+
+.. code-block:: c++
+
+  #define A \
+int ;   \
+int b;  \
+int dd;
 
   * ``ENAS_Right`` (in configuration: ``Right``)
 Align escaped newlines in the right-most column.
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 81e9d0423f96a..56bf78d3298de 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -902,9 +902,10 @@ clang-format
   ``BreakTemplateDeclarations``.
 - ``AlwaysBreakAfterReturnType`` is deprecated and renamed to
   ``BreakAfterReturnType``.
-- Handles Java ``switch`` expressions.
+- Handles Java switch expressions.
 - Adds ``AllowShortCaseExpressionOnASingleLine`` option.
 - Adds ``AlignCaseArrows`` suboption to 
``AlignConsecutiveShortCaseStatements``.
+- Adds ``LeftWithLastLine`` suboption to ``AlignEscapedNewlines``.
 
 libclang
 
diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 274b45d1bc586..eb6647038403d 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -480,15 +480,21 @@ struct FormatStyle {
 ENAS_DontAlign,
 /// Align escaped newlines as far left as possible.
 /// \code
-///   true:
 ///   #define A   \
 /// int ; \
 /// int b;\
 /// int dd;
-///
-///   false:
 /// \endcode
 ENAS_Left,
+/// Align escaped newlines as far left as possible, using the last line of
+/// the preprocessor directive as the reference if it's the longest.
+/// \code
+///   #define A \
+/// int ;   \
+/// int b;  \
+/// int dd;
+/// \endcode
+ENAS_LeftWithLastLine,
 /// Align escaped newlines in the right-most column.
 /// \code
 ///   #define A
  \
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 9cba0c2614eef..c015e03fa15e7 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -308,6 +308,7 @@ struct 
ScalarEnumerationTraits {
   FormatStyle::EscapedNewlineAlignmentStyle &Value) {
 IO.enumCase(Value, "DontAlign", FormatStyle::ENAS_DontAlign);
 IO.enumCase(Value, "Left", FormatStyle::ENAS_Left);
+IO.enumCase(Value, "LeftWithLastLine", FormatStyle::ENAS_LeftWithLastLine);
 IO.enumCase(Value, "Right", FormatStyle::ENAS_Right);
 
 // For backward compatibility.
diff --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index ed06d6098a9f2..50531aee9d597 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -1245,22 +1245,29 @@ void WhitespaceManager::alignTrailingComments(unsigned 
Start, unsigned End,
 }
 
 void WhitespaceManager::alignEscapedNewlines() {
-  if (Style.AlignEscapedNewlines == FormatStyle::ENAS_DontAlign)
+  const auto Align = Style.AlignEscapedNewlines;
+  if (Align == FormatStyle::ENAS_DontAlign)
 return;
 
-  bool AlignLeft = Style.AlignEscapedNewlines == FormatStyle::ENAS_Left;
-  unsigned MaxEndOfLine = AlignLeft ? 0 : Style.ColumnLimit;
+  const bool WithLastLine = Align == FormatStyle::ENAS_LeftWithLastLine;
+  const bool AlignLeft = Align == FormatStyle::ENAS_Left || WithLastLine;
+  const auto MaxColumn = Style.ColumnLimit;
+  unsigned MaxEndOfLine = AlignLeft ? 0 : MaxColumn;
   unsigned StartOfMacro = 0;
   for (unsigned i = 1, e = C

[clang] [clang-format] Add LeftWithLastLine to AlignEscapedNewlines option (PR #93402)

2024-05-26 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Owen Pan (owenca)


Changes

Closes #92999.

---
Full diff: https://github.com/llvm/llvm-project/pull/93402.diff


7 Files Affected:

- (modified) clang/docs/ClangFormatStyleOptions.rst (+10-2) 
- (modified) clang/docs/ReleaseNotes.rst (+2-1) 
- (modified) clang/include/clang/Format/Format.h (+9-3) 
- (modified) clang/lib/Format/Format.cpp (+1) 
- (modified) clang/lib/Format/WhitespaceManager.cpp (+18-11) 
- (modified) clang/unittests/Format/ConfigParseTest.cpp (+2) 
- (modified) clang/unittests/Format/FormatTest.cpp (+20) 


``diff
diff --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 6d092219877f9..1a7d0e6a05e31 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -1421,13 +1421,21 @@ the configuration (without a prefix: ``Auto``).
 
 .. code-block:: c++
 
-  true:
   #define A   \
 int ; \
 int b;\
 int dd;
 
-  false:
+  * ``ENAS_LeftWithLastLine`` (in configuration: ``LeftWithLastLine``)
+Align escaped newlines as far left as possible, using the last line of
+the preprocessor directive as the reference if it's the longest.
+
+.. code-block:: c++
+
+  #define A \
+int ;   \
+int b;  \
+int dd;
 
   * ``ENAS_Right`` (in configuration: ``Right``)
 Align escaped newlines in the right-most column.
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 81e9d0423f96a..56bf78d3298de 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -902,9 +902,10 @@ clang-format
   ``BreakTemplateDeclarations``.
 - ``AlwaysBreakAfterReturnType`` is deprecated and renamed to
   ``BreakAfterReturnType``.
-- Handles Java ``switch`` expressions.
+- Handles Java switch expressions.
 - Adds ``AllowShortCaseExpressionOnASingleLine`` option.
 - Adds ``AlignCaseArrows`` suboption to 
``AlignConsecutiveShortCaseStatements``.
+- Adds ``LeftWithLastLine`` suboption to ``AlignEscapedNewlines``.
 
 libclang
 
diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 274b45d1bc586..eb6647038403d 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -480,15 +480,21 @@ struct FormatStyle {
 ENAS_DontAlign,
 /// Align escaped newlines as far left as possible.
 /// \code
-///   true:
 ///   #define A   \
 /// int ; \
 /// int b;\
 /// int dd;
-///
-///   false:
 /// \endcode
 ENAS_Left,
+/// Align escaped newlines as far left as possible, using the last line of
+/// the preprocessor directive as the reference if it's the longest.
+/// \code
+///   #define A \
+/// int ;   \
+/// int b;  \
+/// int dd;
+/// \endcode
+ENAS_LeftWithLastLine,
 /// Align escaped newlines in the right-most column.
 /// \code
 ///   #define A
  \
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 9cba0c2614eef..c015e03fa15e7 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -308,6 +308,7 @@ struct 
ScalarEnumerationTraits {
   FormatStyle::EscapedNewlineAlignmentStyle &Value) {
 IO.enumCase(Value, "DontAlign", FormatStyle::ENAS_DontAlign);
 IO.enumCase(Value, "Left", FormatStyle::ENAS_Left);
+IO.enumCase(Value, "LeftWithLastLine", FormatStyle::ENAS_LeftWithLastLine);
 IO.enumCase(Value, "Right", FormatStyle::ENAS_Right);
 
 // For backward compatibility.
diff --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index ed06d6098a9f2..50531aee9d597 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -1245,22 +1245,29 @@ void WhitespaceManager::alignTrailingComments(unsigned 
Start, unsigned End,
 }
 
 void WhitespaceManager::alignEscapedNewlines() {
-  if (Style.AlignEscapedNewlines == FormatStyle::ENAS_DontAlign)
+  const auto Align = Style.AlignEscapedNewlines;
+  if (Align == FormatStyle::ENAS_DontAlign)
 return;
 
-  bool AlignLeft = Style.AlignEscapedNewlines == FormatStyle::ENAS_Left;
-  unsigned MaxEndOfLine = AlignLeft ? 0 : Style.ColumnLimit;
+  const bool WithLastLine = Align == FormatStyle::ENAS_LeftWithLastLine;
+  const bool AlignLeft = Align == FormatStyle::ENAS_Left || WithLastLine;
+  const auto MaxColumn = Style.ColumnLimit;
+  unsigned MaxEndOfLine = AlignLeft ? 0 : MaxColumn;
   unsigned StartOfMacro = 0;
   for (unsigned i = 1, e = Changes.size(); i < e; ++i) {
 Change &C = Changes[i];
-if (C.NewlinesBefore > 0) {
-  if (C.ContinuesPPDirective) {
-MaxEndOfLine = std::max(C.PreviousEndOfTokenColumn + 2, 

[clang] [clang-format] Add LeftWithLastLine to AlignEscapedNewlines option (PR #93402)

2024-05-26 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Owen Pan (owenca)


Changes

Closes #92999.

---
Full diff: https://github.com/llvm/llvm-project/pull/93402.diff


7 Files Affected:

- (modified) clang/docs/ClangFormatStyleOptions.rst (+10-2) 
- (modified) clang/docs/ReleaseNotes.rst (+2-1) 
- (modified) clang/include/clang/Format/Format.h (+9-3) 
- (modified) clang/lib/Format/Format.cpp (+1) 
- (modified) clang/lib/Format/WhitespaceManager.cpp (+18-11) 
- (modified) clang/unittests/Format/ConfigParseTest.cpp (+2) 
- (modified) clang/unittests/Format/FormatTest.cpp (+20) 


``diff
diff --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 6d092219877f9..1a7d0e6a05e31 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -1421,13 +1421,21 @@ the configuration (without a prefix: ``Auto``).
 
 .. code-block:: c++
 
-  true:
   #define A   \
 int ; \
 int b;\
 int dd;
 
-  false:
+  * ``ENAS_LeftWithLastLine`` (in configuration: ``LeftWithLastLine``)
+Align escaped newlines as far left as possible, using the last line of
+the preprocessor directive as the reference if it's the longest.
+
+.. code-block:: c++
+
+  #define A \
+int ;   \
+int b;  \
+int dd;
 
   * ``ENAS_Right`` (in configuration: ``Right``)
 Align escaped newlines in the right-most column.
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 81e9d0423f96a..56bf78d3298de 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -902,9 +902,10 @@ clang-format
   ``BreakTemplateDeclarations``.
 - ``AlwaysBreakAfterReturnType`` is deprecated and renamed to
   ``BreakAfterReturnType``.
-- Handles Java ``switch`` expressions.
+- Handles Java switch expressions.
 - Adds ``AllowShortCaseExpressionOnASingleLine`` option.
 - Adds ``AlignCaseArrows`` suboption to 
``AlignConsecutiveShortCaseStatements``.
+- Adds ``LeftWithLastLine`` suboption to ``AlignEscapedNewlines``.
 
 libclang
 
diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 274b45d1bc586..eb6647038403d 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -480,15 +480,21 @@ struct FormatStyle {
 ENAS_DontAlign,
 /// Align escaped newlines as far left as possible.
 /// \code
-///   true:
 ///   #define A   \
 /// int ; \
 /// int b;\
 /// int dd;
-///
-///   false:
 /// \endcode
 ENAS_Left,
+/// Align escaped newlines as far left as possible, using the last line of
+/// the preprocessor directive as the reference if it's the longest.
+/// \code
+///   #define A \
+/// int ;   \
+/// int b;  \
+/// int dd;
+/// \endcode
+ENAS_LeftWithLastLine,
 /// Align escaped newlines in the right-most column.
 /// \code
 ///   #define A
  \
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 9cba0c2614eef..c015e03fa15e7 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -308,6 +308,7 @@ struct 
ScalarEnumerationTraits {
   FormatStyle::EscapedNewlineAlignmentStyle &Value) {
 IO.enumCase(Value, "DontAlign", FormatStyle::ENAS_DontAlign);
 IO.enumCase(Value, "Left", FormatStyle::ENAS_Left);
+IO.enumCase(Value, "LeftWithLastLine", FormatStyle::ENAS_LeftWithLastLine);
 IO.enumCase(Value, "Right", FormatStyle::ENAS_Right);
 
 // For backward compatibility.
diff --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index ed06d6098a9f2..50531aee9d597 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -1245,22 +1245,29 @@ void WhitespaceManager::alignTrailingComments(unsigned 
Start, unsigned End,
 }
 
 void WhitespaceManager::alignEscapedNewlines() {
-  if (Style.AlignEscapedNewlines == FormatStyle::ENAS_DontAlign)
+  const auto Align = Style.AlignEscapedNewlines;
+  if (Align == FormatStyle::ENAS_DontAlign)
 return;
 
-  bool AlignLeft = Style.AlignEscapedNewlines == FormatStyle::ENAS_Left;
-  unsigned MaxEndOfLine = AlignLeft ? 0 : Style.ColumnLimit;
+  const bool WithLastLine = Align == FormatStyle::ENAS_LeftWithLastLine;
+  const bool AlignLeft = Align == FormatStyle::ENAS_Left || WithLastLine;
+  const auto MaxColumn = Style.ColumnLimit;
+  unsigned MaxEndOfLine = AlignLeft ? 0 : MaxColumn;
   unsigned StartOfMacro = 0;
   for (unsigned i = 1, e = Changes.size(); i < e; ++i) {
 Change &C = Changes[i];
-if (C.NewlinesBefore > 0) {
-  if (C.ContinuesPPDirective) {
-MaxEndOfLine = std::max(C.PreviousEndOfTokenColum

[clang] Fix the warning in RefCntblBaseVirtualDtorChecker.cpp:61 (PR #93403)

2024-05-26 Thread Ryosuke Niwa via cfe-commits

https://github.com/rniwa created https://github.com/llvm/llvm-project/pull/93403

None

>From 4f5b6ac39e709bddf7f1ced314ebb1984a1942de Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Sun, 26 May 2024 00:34:15 -0700
Subject: [PATCH] Fix the warning in RefCntblBaseVirtualDtorChecker.cpp:61

---
 .../Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp  | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
index 26879f2f87c8b..9df108e28ecdb 100644
--- 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
+++ 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
@@ -58,7 +58,7 @@ class DerefFuncDeleteExprVisitor
   std::optional HasSpecializedDelete(CXXMethodDecl *Decl) {
 if (auto *Body = Decl->getBody())
   return VisitBody(Body);
-if (auto *Tmpl = Decl->getTemplateInstantiationPattern())
+if (Decl->getTemplateInstantiationPattern())
   return std::nullopt; // Indeterminate. There was no concrete instance.
 return false;
   }

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


[clang] [webkit.RefCntblBaseVirtualDtor] Allow CRTP classes without a virtual destructor. (PR #92837)

2024-05-26 Thread Ryosuke Niwa via cfe-commits


@@ -11,16 +11,116 @@
 #include "PtrTypesSemantics.h"
 #include "clang/AST/CXXInheritance.h"
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/AST/StmtVisitor.h"
 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
+#include "llvm/ADT/DenseSet.h"
+#include "llvm/ADT/SetVector.h"
 #include 
 
 using namespace clang;
 using namespace ento;
 
 namespace {
+
+class DerefFuncDeleteExprVisitor
+: public ConstStmtVisitor {
+  // Returns true if any of child statements return true.
+  bool VisitChildren(const Stmt *S) {
+for (const Stmt *Child : S->children()) {
+  if (Child && Visit(Child))
+return true;
+}
+return false;
+  }
+
+  bool VisitBody(const Stmt *Body) {
+if (!Body)
+  return false;
+
+auto [It, IsNew] = VisitedBody.insert(Body);
+if (!IsNew) // This body is recursive
+  return false;
+
+return Visit(Body);
+  }
+
+public:
+  DerefFuncDeleteExprVisitor(const TemplateArgumentList &ArgList,
+ const CXXRecordDecl *ClassDecl)
+  : ArgList(&ArgList), ClassDecl(ClassDecl) {}
+
+  DerefFuncDeleteExprVisitor(const CXXRecordDecl *ClassDecl)
+  : ClassDecl(ClassDecl) {}
+
+  std::optional HasSpecializedDelete(CXXMethodDecl *Decl) {
+if (auto *Body = Decl->getBody())
+  return VisitBody(Body);
+if (auto *Tmpl = Decl->getTemplateInstantiationPattern())

rniwa wrote:

Here's a PR to fix it: https://github.com/llvm/llvm-project/pull/93403

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


[clang] Fix the warning in RefCntblBaseVirtualDtorChecker.cpp:61 (PR #93403)

2024-05-26 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-static-analyzer-1

Author: Ryosuke Niwa (rniwa)


Changes



---
Full diff: https://github.com/llvm/llvm-project/pull/93403.diff


1 Files Affected:

- (modified) 
clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp 
(+1-1) 


``diff
diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
index 26879f2f87c8b..9df108e28ecdb 100644
--- 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
+++ 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
@@ -58,7 +58,7 @@ class DerefFuncDeleteExprVisitor
   std::optional HasSpecializedDelete(CXXMethodDecl *Decl) {
 if (auto *Body = Decl->getBody())
   return VisitBody(Body);
-if (auto *Tmpl = Decl->getTemplateInstantiationPattern())
+if (Decl->getTemplateInstantiationPattern())
   return std::nullopt; // Indeterminate. There was no concrete instance.
 return false;
   }

``




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


[clang] Fix the warning in RefCntblBaseVirtualDtorChecker.cpp:61 (PR #93403)

2024-05-26 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Ryosuke Niwa (rniwa)


Changes



---
Full diff: https://github.com/llvm/llvm-project/pull/93403.diff


1 Files Affected:

- (modified) 
clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp 
(+1-1) 


``diff
diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
index 26879f2f87c8b..9df108e28ecdb 100644
--- 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
+++ 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
@@ -58,7 +58,7 @@ class DerefFuncDeleteExprVisitor
   std::optional HasSpecializedDelete(CXXMethodDecl *Decl) {
 if (auto *Body = Decl->getBody())
   return VisitBody(Body);
-if (auto *Tmpl = Decl->getTemplateInstantiationPattern())
+if (Decl->getTemplateInstantiationPattern())
   return std::nullopt; // Indeterminate. There was no concrete instance.
 return false;
   }

``




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


[clang] [clang][CodeComplete] Recurse into the subexpression of deref operator in getApproximateType (PR #93404)

2024-05-26 Thread Younan Zhang via cfe-commits

https://github.com/zyn0217 created 
https://github.com/llvm/llvm-project/pull/93404

The issue with the previous implementation bc31be7 was that getApproximateType 
could potentially return a null QualType for a dereferencing operator, which is 
not what its caller wants.

>From 7639cb738dfb876c7abdf7337fad3aa80e912736 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Sun, 26 May 2024 15:52:31 +0800
Subject: [PATCH] [clang][CodeComplete] Recurse into the subexpression of deref
 operator in getApproximateType

The issue with the previous implementation bc31be7 was that
getApproximateType could potentially return a null QualType for a
dereferencing operator, which is not what its caller wants.
---
 clang/lib/Sema/SemaCodeComplete.cpp | 12 ++--
 clang/test/CodeCompletion/member-access.cpp | 16 
 2 files changed, 26 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaCodeComplete.cpp 
b/clang/lib/Sema/SemaCodeComplete.cpp
index 328641ed94881..73ed99e099869 100644
--- a/clang/lib/Sema/SemaCodeComplete.cpp
+++ b/clang/lib/Sema/SemaCodeComplete.cpp
@@ -5680,8 +5680,16 @@ QualType getApproximateType(const Expr *E) {
 }
   }
   if (const auto *UO = llvm::dyn_cast(E)) {
-if (UO->getOpcode() == UnaryOperatorKind::UO_Deref)
-  return UO->getSubExpr()->getType()->getPointeeType();
+if (UO->getOpcode() == UnaryOperatorKind::UO_Deref) {
+  // We recurse into the subexpression because it could be of dependent
+  // type.
+  QualType SubType = getApproximateType(UO->getSubExpr());
+  if (auto Pointee = SubType->getPointeeType(); !Pointee.isNull())
+return Pointee;
+  // Our caller expects a non-null result, even though the SubType is
+  // supposed to have a pointee.
+  return SubType;
+}
   }
   return Unresolved;
 }
diff --git a/clang/test/CodeCompletion/member-access.cpp 
b/clang/test/CodeCompletion/member-access.cpp
index 9f8c21c0bca6d..912f269db6c1a 100644
--- a/clang/test/CodeCompletion/member-access.cpp
+++ b/clang/test/CodeCompletion/member-access.cpp
@@ -367,4 +367,20 @@ class A {
 // CHECK-DEREF-THIS: [#void#]function()
   }
 };
+
+template 
+struct RepeatedField {
+  void Add();
+};
+
+template 
+RepeatedField* MutableRepeatedField() {}
+
+template 
+void Foo() {
+  auto& C = *MutableRepeatedField();
+  C.
+}
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:382:5 %s -o - | 
FileCheck -check-prefix=CHECK-DEREF-DEPENDENT %s
+// CHECK-DEREF-DEPENDENT: [#void#]Add()
 }

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


[clang] [clang][CodeComplete] Recurse into the subexpression of deref operator in getApproximateType (PR #93404)

2024-05-26 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tools-extra

Author: Younan Zhang (zyn0217)


Changes

The issue with the previous implementation bc31be7 was that getApproximateType 
could potentially return a null QualType for a dereferencing operator, which is 
not what its caller wants.

---
Full diff: https://github.com/llvm/llvm-project/pull/93404.diff


2 Files Affected:

- (modified) clang/lib/Sema/SemaCodeComplete.cpp (+10-2) 
- (modified) clang/test/CodeCompletion/member-access.cpp (+16) 


``diff
diff --git a/clang/lib/Sema/SemaCodeComplete.cpp 
b/clang/lib/Sema/SemaCodeComplete.cpp
index 328641ed94881..73ed99e099869 100644
--- a/clang/lib/Sema/SemaCodeComplete.cpp
+++ b/clang/lib/Sema/SemaCodeComplete.cpp
@@ -5680,8 +5680,16 @@ QualType getApproximateType(const Expr *E) {
 }
   }
   if (const auto *UO = llvm::dyn_cast(E)) {
-if (UO->getOpcode() == UnaryOperatorKind::UO_Deref)
-  return UO->getSubExpr()->getType()->getPointeeType();
+if (UO->getOpcode() == UnaryOperatorKind::UO_Deref) {
+  // We recurse into the subexpression because it could be of dependent
+  // type.
+  QualType SubType = getApproximateType(UO->getSubExpr());
+  if (auto Pointee = SubType->getPointeeType(); !Pointee.isNull())
+return Pointee;
+  // Our caller expects a non-null result, even though the SubType is
+  // supposed to have a pointee.
+  return SubType;
+}
   }
   return Unresolved;
 }
diff --git a/clang/test/CodeCompletion/member-access.cpp 
b/clang/test/CodeCompletion/member-access.cpp
index 9f8c21c0bca6d..912f269db6c1a 100644
--- a/clang/test/CodeCompletion/member-access.cpp
+++ b/clang/test/CodeCompletion/member-access.cpp
@@ -367,4 +367,20 @@ class A {
 // CHECK-DEREF-THIS: [#void#]function()
   }
 };
+
+template 
+struct RepeatedField {
+  void Add();
+};
+
+template 
+RepeatedField* MutableRepeatedField() {}
+
+template 
+void Foo() {
+  auto& C = *MutableRepeatedField();
+  C.
+}
+// RUN: %clang_cc1 -fsyntax-only -code-completion-at=%s:382:5 %s -o - | 
FileCheck -check-prefix=CHECK-DEREF-DEPENDENT %s
+// CHECK-DEREF-DEPENDENT: [#void#]Add()
 }

``




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


[clang] [clang][driver] add pointer qualifier to auto type (PR #91874)

2024-05-26 Thread Mohammed Keyvanzadeh via cfe-commits

VoltrexKeyva wrote:

Pinging again after another week of no reviews.

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


[clang] 5220b7b - [clang][Interp] Handle objc strings

2024-05-26 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-05-26T10:50:44+02:00
New Revision: 5220b7bea8b01f46e9f7326b9c9a7e550e8451d1

URL: 
https://github.com/llvm/llvm-project/commit/5220b7bea8b01f46e9f7326b9c9a7e550e8451d1
DIFF: 
https://github.com/llvm/llvm-project/commit/5220b7bea8b01f46e9f7326b9c9a7e550e8451d1.diff

LOG: [clang][Interp] Handle objc strings

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/lib/AST/Interp/ByteCodeExprGen.h
clang/lib/AST/Interp/Context.cpp
clang/test/AST/Interp/objc.mm

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 6607727b5246f..f00421d0c2ea9 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1637,6 +1637,12 @@ bool ByteCodeExprGen::VisitStringLiteral(const 
StringLiteral *E) {
   return true;
 }
 
+template 
+bool ByteCodeExprGen::VisitObjCStringLiteral(
+const ObjCStringLiteral *E) {
+  return this->delegate(E->getString());
+}
+
 template 
 bool ByteCodeExprGen::VisitSYCLUniqueStableNameExpr(
 const SYCLUniqueStableNameExpr *E) {

diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index a2e283c866332..c648b0e4be704 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -90,6 +90,7 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E);
   bool VisitAbstractConditionalOperator(const AbstractConditionalOperator *E);
   bool VisitStringLiteral(const StringLiteral *E);
+  bool VisitObjCStringLiteral(const ObjCStringLiteral *E);
   bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E);
   bool VisitCharacterLiteral(const CharacterLiteral *E);
   bool VisitCompoundAssignOperator(const CompoundAssignOperator *E);

diff  --git a/clang/lib/AST/Interp/Context.cpp 
b/clang/lib/AST/Interp/Context.cpp
index d51a57e5e92ea..4ecfa0f9bfd75 100644
--- a/clang/lib/AST/Interp/Context.cpp
+++ b/clang/lib/AST/Interp/Context.cpp
@@ -164,7 +164,8 @@ std::optional Context::classify(QualType T) const 
{
   T->isFunctionType() || 
T->isSpecificBuiltinType(BuiltinType::BoundMember))
 return PT_FnPtr;
 
-  if (T->isReferenceType() || T->isPointerType())
+  if (T->isReferenceType() || T->isPointerType() ||
+  T->isObjCObjectPointerType())
 return PT_Ptr;
 
   if (const auto *AT = T->getAs())

diff  --git a/clang/test/AST/Interp/objc.mm b/clang/test/AST/Interp/objc.mm
index 44b74d193b66a..e48fa3c0ac709 100644
--- a/clang/test/AST/Interp/objc.mm
+++ b/clang/test/AST/Interp/objc.mm
@@ -6,3 +6,7 @@ @interface A {
   static_assert(a, ""); // both-error {{static assertion expression is not an 
integral constant expression}}
 }
 @end
+
+@interface NSString
+@end
+constexpr NSString *t0 = @"abc";



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


[clang] d0bb917 - [clang][Interp] Handle ObjCBoxedExprs

2024-05-26 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-05-26T10:50:45+02:00
New Revision: d0bb91739022e1f15b1ec9a6fd7fc92cd0f95444

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

LOG: [clang][Interp] Handle ObjCBoxedExprs

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/lib/AST/Interp/ByteCodeExprGen.h
clang/test/AST/Interp/objc.mm

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index f00421d0c2ea9..7aa2105942ecb 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -2649,6 +2649,14 @@ bool ByteCodeExprGen::VisitShuffleVectorExpr(
   return true;
 }
 
+template 
+bool ByteCodeExprGen::VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
+  if (!E->isExpressibleAsConstantInitializer())
+return this->emitInvalid(E);
+
+  return this->delegate(E->getSubExpr());
+}
+
 template  bool ByteCodeExprGen::discard(const Expr *E) 
{
   OptionScope Scope(this, /*NewDiscardResult=*/true,
  /*NewInitializing=*/false);

diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index c648b0e4be704..44c495240289f 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -127,6 +127,7 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   bool VisitAddrLabelExpr(const AddrLabelExpr *E);
   bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
   bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
+  bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E);
 
 protected:
   bool visitExpr(const Expr *E) override;

diff  --git a/clang/test/AST/Interp/objc.mm b/clang/test/AST/Interp/objc.mm
index e48fa3c0ac709..6402c8ae098fd 100644
--- a/clang/test/AST/Interp/objc.mm
+++ b/clang/test/AST/Interp/objc.mm
@@ -10,3 +10,4 @@ @interface A {
 @interface NSString
 @end
 constexpr NSString *t0 = @"abc";
+constexpr NSString *t1 = @("abc");



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


[clang] [clang][Sema] Don't emit 'declared here' note for builtin functions with no decl in source (PR #93394)

2024-05-26 Thread Youngsuk Kim via cfe-commits

https://github.com/JOE1994 updated 
https://github.com/llvm/llvm-project/pull/93394

>From 00c93043fca8f8a1f20634ea1b281c60926bd571 Mon Sep 17 00:00:00 2001
From: Youngsuk Kim 
Date: Sat, 25 May 2024 20:42:43 -0500
Subject: [PATCH 1/2] [clang][Sema] Don't emit 'declared here' note for builtin
 functions with no decl in source

Fixes #93369
---
 clang/lib/Sema/SemaLookup.cpp   | 10 ++
 clang/test/SemaCXX/invalid-if-constexpr.cpp |  2 +-
 2 files changed, 11 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaLookup.cpp b/clang/lib/Sema/SemaLookup.cpp
index ef0a655b631ab..348f9e5b8f530 100644
--- a/clang/lib/Sema/SemaLookup.cpp
+++ b/clang/lib/Sema/SemaLookup.cpp
@@ -5897,6 +5897,16 @@ void Sema::diagnoseTypo(const TypoCorrection &Correction,
 
   NamedDecl *ChosenDecl =
   Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
+
+  // For builtin functions which aren't declared anywhere in source,
+  // don't emit the "declared here" note.
+  if (auto *FD = dyn_cast_or_null(ChosenDecl);
+  FD && FD->getBuiltinID() &&
+  PrevNote.getDiagID() == diag::note_previous_decl &&
+  Correction.getCorrectionRange().getBegin() == FD->getBeginLoc()) {
+ChosenDecl = nullptr;
+  }
+
   if (PrevNote.getDiagID() && ChosenDecl)
 Diag(ChosenDecl->getLocation(), PrevNote)
   << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
diff --git a/clang/test/SemaCXX/invalid-if-constexpr.cpp 
b/clang/test/SemaCXX/invalid-if-constexpr.cpp
index 7643c47488f05..16d422880e8a9 100644
--- a/clang/test/SemaCXX/invalid-if-constexpr.cpp
+++ b/clang/test/SemaCXX/invalid-if-constexpr.cpp
@@ -5,7 +5,7 @@ void similar() { // expected-note {{'similar' declared here}}
   if constexpr (similer<>) {} // expected-error {{use of undeclared identifier 
'similer'; did you mean 'similar'?}}
 }
 void a() { if constexpr (__adl_swap<>) {}} // expected-error{{use of 
undeclared identifier '__adl_swap'; did you mean '__sync_swap'?}} \
-   // expected-note {{'__sync_swap' 
declared here}}
+   // not-expected-note 
{{'__sync_swap' declared here}}
 
 int AA() { return true;} // expected-note {{'AA' declared here}}
 

>From 42bbff26459b71e9d77c4d907703930e12db8958 Mon Sep 17 00:00:00 2001
From: Youngsuk Kim 
Date: Sun, 26 May 2024 05:53:03 -0400
Subject: [PATCH 2/2] Use dyn_cast_if_present

Co-authored-by: Timm Baeder 
---
 clang/lib/Sema/SemaLookup.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaLookup.cpp b/clang/lib/Sema/SemaLookup.cpp
index 348f9e5b8f530..be6ea20a956a3 100644
--- a/clang/lib/Sema/SemaLookup.cpp
+++ b/clang/lib/Sema/SemaLookup.cpp
@@ -5900,7 +5900,7 @@ void Sema::diagnoseTypo(const TypoCorrection &Correction,
 
   // For builtin functions which aren't declared anywhere in source,
   // don't emit the "declared here" note.
-  if (auto *FD = dyn_cast_or_null(ChosenDecl);
+  if (const auto *FD = dyn_cast_if_present(ChosenDecl);
   FD && FD->getBuiltinID() &&
   PrevNote.getDiagID() == diag::note_previous_decl &&
   Correction.getCorrectionRange().getBegin() == FD->getBeginLoc()) {

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


[clang] Fix the warning in RefCntblBaseVirtualDtorChecker.cpp:61 (PR #93403)

2024-05-26 Thread NAKAMURA Takumi via cfe-commits

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

Thanks!

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


[clang] [analyzer] Refine invalidation caused by `fread` (PR #93408)

2024-05-26 Thread Balazs Benics via cfe-commits

https://github.com/steakhal created 
https://github.com/llvm/llvm-project/pull/93408

This change enables more accurate modeling of the write effects of `fread`. In 
particular, instead of invalidating the whole buffer, in a best-effort basis, 
we would try to invalidate the actually accesses elements of the buffer. This 
preserves the previous value of the buffer of the unaffected slots. As a 
result, diagnose more uninitialized buffer uses for example.

Currently, this refined invalidation only triggers for `fread` if and only if 
the `count` parameter and the buffer pointer's index component are concrete or 
perfectly-constrained symbols.
Additionally, if the `fread` would read more than 64 elements, the whole buffer 
is invalidated as before. This is to have safeguards against performance issues.

Refer to the comments of the assertions in the following example to see the 
changes in the diagnostics:

```c++
void demo() {
  FILE *fp = fopen("/home/test", "rb+");
  if (!fp) return;
  int buffer[10]; // uninitialized
  int read_items = fread(buffer+1, sizeof(int), 5, fp);
  if (5 == read_items) {
int v1 = buffer[1]; // Unknown value but not garbage.
clang_analyzer_isTainted(v1); // expected-warning {{YES}} <-- Would be "NO" 
without this patch.
clang_analyzer_dump(v1); // expected-warning {{conj_}} <-- Not a "derived" 
symbol, so it's directly invalidated now.
int v0 = buffer[0]; // expected-warning {{Assigned value is garbage or 
undefined}} <-- Had no report here before.
(void)(v1 + v0);
  } else {
// If 'fread' had an error.
int v0 = buffer[0]; // expected-warning {{Assigned value is garbage or 
undefined}} <-- Had no report here before.
(void)v0;
  }
  fclose(fp);
}
```

[CPP-3247](https://sonarsource.atlassian.net/browse/CPP-3247)

Patch by Marco Borgeaud (marco-antognini-sonarsource)

>From f9e841ddaa865d529c806b2d115d5ddbc7109243 Mon Sep 17 00:00:00 2001
From: Balazs Benics 
Date: Sun, 26 May 2024 11:40:01 +0200
Subject: [PATCH] [analyzer] Refine invalidation caused by `fread`

This change enables more accurate modeling of the write effects of `fread`.
In particular, instead of invalidating the whole buffer, in a best-effort
basis, we would try to invalidate the actually accesses elements of the buffer.
This preserves the previous value of the buffer of the unaffected slots.
As a result, diagnose more uninitialized buffer uses for example.

Currently, this refined invalidation only triggers for `fread` if and
only if the `count` parameter and the buffer pointer's index component
are concrete or perfectly-constrained symbols.
Additionally, if the `fread` would read more than 64 elements, the whole
buffer is invalidated as before. This is to have safeguards against
performance issues.

Refer to the comments of the assertions in the following example to see
the changes in the diagnostics:

```c++
void demo() {
  FILE *fp = fopen("/home/test", "rb+");
  if (!fp) return;
  int buffer[10]; // uninitialized
  int read_items = fread(buffer+1, sizeof(int), 5, fp);
  if (5 == read_items) {
int v1 = buffer[1]; // Unknown value but not garbage.
clang_analyzer_isTainted(v1); // expected-warning {{YES}} <-- Would be "NO" 
without this patch.
clang_analyzer_dump(v1); // expected-warning {{conj_}} <-- Not a "derived" 
symbol, so it's directly invalidated now.
int v0 = buffer[0]; // expected-warning {{Assigned value is garbage or 
undefined}} <-- Had no report here before.
(void)(v1 + v0);
  } else {
// If 'fread' had an error.
int v0 = buffer[0]; // expected-warning {{Assigned value is garbage or 
undefined}} <-- Had no report here before.
(void)v0;
  }
  fclose(fp);
}
```

[CPP-3247](https://sonarsource.atlassian.net/browse/CPP-3247)

Patch by Marco Borgeaud (marco-antognini-sonarsource)
---
 .../StaticAnalyzer/Checkers/StreamChecker.cpp |  88 -
 clang/test/Analysis/fread.cpp | 328 ++
 2 files changed, 405 insertions(+), 11 deletions(-)
 create mode 100644 clang/test/Analysis/fread.cpp

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index d4e020f7a72a0..7b42c4f72b322 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -717,18 +717,71 @@ const ExplodedNode 
*StreamChecker::getAcquisitionSite(const ExplodedNode *N,
   return nullptr;
 }
 
+/// Invalidate only the requested elements instead of the whole buffer.
+/// This is basically a refinement of the more generic 'escapeArgs' or
+/// the plain old 'invalidateRegions'.
+/// This only works if the \p StartIndex and \p Count are concrete or
+/// perfectly-constrained.
+static ProgramStateRef
+escapeByStartIndexAndCount(ProgramStateRef State, CheckerContext &C,
+   const CallEvent &Call, const MemRegion *Buffer,
+   QualType ElemType, SVal StartIndex, SVal Count) {
+  if (!ll

[clang] [analyzer] Refine invalidation caused by `fread` (PR #93408)

2024-05-26 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-static-analyzer-1

Author: Balazs Benics (steakhal)


Changes

This change enables more accurate modeling of the write effects of `fread`. In 
particular, instead of invalidating the whole buffer, in a best-effort basis, 
we would try to invalidate the actually accesses elements of the buffer. This 
preserves the previous value of the buffer of the unaffected slots. As a 
result, diagnose more uninitialized buffer uses for example.

Currently, this refined invalidation only triggers for `fread` if and only if 
the `count` parameter and the buffer pointer's index component are concrete or 
perfectly-constrained symbols.
Additionally, if the `fread` would read more than 64 elements, the whole buffer 
is invalidated as before. This is to have safeguards against performance issues.

Refer to the comments of the assertions in the following example to see the 
changes in the diagnostics:

```c++
void demo() {
  FILE *fp = fopen("/home/test", "rb+");
  if (!fp) return;
  int buffer[10]; // uninitialized
  int read_items = fread(buffer+1, sizeof(int), 5, fp);
  if (5 == read_items) {
int v1 = buffer[1]; // Unknown value but not garbage.
clang_analyzer_isTainted(v1); // expected-warning {{YES}} <-- Would be 
"NO" without this patch.
clang_analyzer_dump(v1); // expected-warning {{conj_}} <-- Not a 
"derived" symbol, so it's directly invalidated now.
int v0 = buffer[0]; // expected-warning {{Assigned value is garbage or 
undefined}} <-- Had no report here before.
(void)(v1 + v0);
  } else {
// If 'fread' had an error.
int v0 = buffer[0]; // expected-warning {{Assigned value is garbage or 
undefined}} <-- Had no report here before.
(void)v0;
  }
  fclose(fp);
}
```

[CPP-3247](https://sonarsource.atlassian.net/browse/CPP-3247)

Patch by Marco Borgeaud (marco-antognini-sonarsource)

---
Full diff: https://github.com/llvm/llvm-project/pull/93408.diff


2 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp (+77-11) 
- (added) clang/test/Analysis/fread.cpp (+328) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index d4e020f7a72a0..7b42c4f72b322 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -717,18 +717,71 @@ const ExplodedNode 
*StreamChecker::getAcquisitionSite(const ExplodedNode *N,
   return nullptr;
 }
 
+/// Invalidate only the requested elements instead of the whole buffer.
+/// This is basically a refinement of the more generic 'escapeArgs' or
+/// the plain old 'invalidateRegions'.
+/// This only works if the \p StartIndex and \p Count are concrete or
+/// perfectly-constrained.
+static ProgramStateRef
+escapeByStartIndexAndCount(ProgramStateRef State, CheckerContext &C,
+   const CallEvent &Call, const MemRegion *Buffer,
+   QualType ElemType, SVal StartIndex, SVal Count) {
+  if (!llvm::isa_and_nonnull(Buffer))
+return State;
+
+  auto UnboxAsInt = [&C, &State](SVal V) -> std::optional {
+auto &SVB = C.getSValBuilder();
+if (const llvm::APSInt *Int = SVB.getKnownValue(State, V))
+  return Int->tryExtValue();
+return std::nullopt;
+  };
+
+  auto StartIndexVal = UnboxAsInt(StartIndex);
+  auto CountVal = UnboxAsInt(Count);
+
+  // FIXME: Maybe we could make this more generic, and expose this by the
+  // 'invalidateRegions' API. After doing so, it might make sense to make this
+  // limit configurable.
+  constexpr int MaxInvalidatedElementsLimit = 64;
+  if (!StartIndexVal || !CountVal || *CountVal > MaxInvalidatedElementsLimit) {
+return State->invalidateRegions({loc::MemRegionVal{Buffer}},
+Call.getOriginExpr(), C.blockCount(),
+C.getLocationContext(),
+/*CausesPointerEscape=*/false);
+  }
+
+  constexpr auto DoNotInvalidateSuperRegion =
+  RegionAndSymbolInvalidationTraits::InvalidationKinds::
+  TK_DoNotInvalidateSuperRegion;
+
+  auto &RegionManager = Buffer->getMemRegionManager();
+  SmallVector EscapingVals;
+  EscapingVals.reserve(*CountVal);
+
+  RegionAndSymbolInvalidationTraits ITraits;
+  for (auto Idx : llvm::seq(*StartIndexVal, *StartIndexVal + *CountVal)) {
+NonLoc Index = C.getSValBuilder().makeArrayIndex(Idx);
+const auto *Element = RegionManager.getElementRegion(
+ElemType, Index, cast(Buffer), C.getASTContext());
+EscapingVals.push_back(loc::MemRegionVal(Element));
+ITraits.setTrait(Element, DoNotInvalidateSuperRegion);
+  }
+  return State->invalidateRegions(EscapingVals, Call.getOriginExpr(),
+  C.blockCount(), C.getLocationContext(),
+  /*CausesPointerEscape=*/false,
+  /*InvalidatedSymbols=*/nullptr, &Call,
+ 

[clang] [clang][Sema] Don't emit 'declared here' note for builtin functions with no decl in source (PR #93394)

2024-05-26 Thread Timm Baeder via cfe-commits

tbaederr wrote:

Would be nice if you could add new explicit tests for this.

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


[clang] [clang][Sema] Don't emit 'declared here' note for builtin functions with no decl in source (PR #93394)

2024-05-26 Thread Timm Baeder via cfe-commits


@@ -5,7 +5,7 @@ void similar() { // expected-note {{'similar' declared here}}
   if constexpr (similer<>) {} // expected-error {{use of undeclared identifier 
'similer'; did you mean 'similar'?}}
 }
 void a() { if constexpr (__adl_swap<>) {}} // expected-error{{use of 
undeclared identifier '__adl_swap'; did you mean '__sync_swap'?}} \
-   // expected-note {{'__sync_swap' 
declared here}}
+   // not-expected-note 
{{'__sync_swap' declared here}}

tbaederr wrote:

I don't think the `not-` prefix actually does anything with `-verify`, does it?

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


[clang] [analyzer] Refine invalidation caused by `fread` (PR #93408)

2024-05-26 Thread Balazs Benics via cfe-commits

https://github.com/steakhal edited 
https://github.com/llvm/llvm-project/pull/93408
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][analyzer] PutenvStackArrayChecker: No warning from 'main' (PR #93299)

2024-05-26 Thread Balazs Benics via cfe-commits

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

LGTM

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


[clang] [analyzer] Adding taint analysis capability to unix.Malloc checker (PR #92420)

2024-05-26 Thread Balazs Benics via cfe-commits

https://github.com/steakhal commented:

The patch makes sense to me.
Have you considered applying the same heuristic to C++ array new allocations?

I'll port this patch downstream to see how this would behave on the Juliet C++ 
benchmark or on some real-world code.

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


[clang] [analyzer] Adding taint analysis capability to unix.Malloc checker (PR #92420)

2024-05-26 Thread Balazs Benics via cfe-commits

steakhal wrote:

> I'll port this patch downstream to see how this would behave on the Juliet 
> C++ benchmark or on some real-world code.

Ah nvm. llvm/main diverged quite a bit since 18.1.6. I can't just pick this 
one. Given this, I won't backport and test this PR.

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


[clang] Remove dangling conversion to `optional &` (PR #93385)

2024-05-26 Thread via cfe-commits

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

LGTM.

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


[clang] [lldb] [clang][Modules] Move `ASTSourceDescriptor` into its own file (PR #67930)

2024-05-26 Thread via cfe-commits

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

LGTM

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


[clang] [Clang][Sema] Use correct TemplateName when transforming TemplateSpecializationType (PR #93411)

2024-05-26 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky created 
https://github.com/llvm/llvm-project/pull/93411

Consider the following testcase:
```cpp
namespace PR12884_original {
  template  struct A {
struct B { ##1
  template  struct X {};
  typedef int arg;
};
struct C {
  typedef B::X x; 
};
  };

  template <> struct A::B { ##2
template  struct X {};
static const int arg = 0;
  };

  A::C::x a;
}
```
It will crash when compiling with `clang(assertions trunk)`. The reason is that 
we lookup `X`(`B::X`) in `##1` when instantiating `typedef B::X x; ` during instantiating `A::C::x`. This is incorrect because we 
should lookup `X` in `##2` when we see the declaration `A::C::x a;`. Since 
clang parse `A::B` to an `ElaboratedType`(`typename` is not required 
while compiling with `-std=c++20`)  while `typename A::B` turns to be a 
`DependentTemplateSpecializationType`, we should rebuild the `TemplateName` 
with transformed `Qualifier`(whose type is `NestedNameSpecifier`) to make sure 
the lookup context is correct.
This patch also attempts to fix #91677 which crashes with the same reason.

>From ee56373184dff3fd721709ca07a1770957eace29 Mon Sep 17 00:00:00 2001
From: Qizhi Hu <836744...@qq.com>
Date: Sat, 25 May 2024 16:30:27 +0800
Subject: [PATCH 1/2] [Clang][Sema] Use correct TemplateName when transforming
 TemplateSpecializationType

---
 clang/lib/Sema/TreeTransform.h | 43 +-
 1 file changed, 42 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index dee335b526991..7e8b080a347e8 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -29,8 +29,10 @@
 #include "clang/AST/StmtObjC.h"
 #include "clang/AST/StmtOpenACC.h"
 #include "clang/AST/StmtOpenMP.h"
+#include "clang/AST/TypeLoc.h"
 #include "clang/Basic/DiagnosticParse.h"
 #include "clang/Basic/OpenMPKinds.h"
+#include "clang/Sema/DeclSpec.h"
 #include "clang/Sema/Designator.h"
 #include "clang/Sema/EnterExpressionEvaluationContext.h"
 #include "clang/Sema/Lookup.h"
@@ -7216,7 +7218,46 @@ 
TreeTransform::TransformElaboratedType(TypeLocBuilder &TLB,
   return QualType();
   }
 
-  QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
+  QualType NamedT;
+  if (0 && SemaRef.getLangOpts().CPlusPlus20 && QualifierLoc && 
isa(TL.getNamedTypeLoc().getType())) {
+const TemplateSpecializationType *TST = 
TL.getNamedTypeLoc().getType()->getAs();
+TemplateSpecializationTypeLoc SpecTL =
+TL.getNamedTypeLoc().castAs();
+// TemplateArgumentListInfo NewTemplateArgs;
+// NewTemplateArgs.setLAngleLoc(SpecTL.getLAngleLoc());
+// NewTemplateArgs.setRAngleLoc(SpecTL.getRAngleLoc());
+
+// typedef TemplateArgumentLocContainerIterator<
+// TemplateSpecializationTypeLoc> ArgIterator;
+// if (getDerived().TransformTemplateArguments(ArgIterator(SpecTL, 0),
+// ArgIterator(SpecTL, 
SpecTL.getNumArgs()),
+// NewTemplateArgs))
+//   return QualType();
+
+CXXScopeSpec SS;
+SS.Adopt(QualifierLoc);
+TemplateName InstName = getDerived().RebuildTemplateName(
+SS, TL.getTemplateKeywordLoc(), 
*TST->getTemplateName().getAsTemplateDecl()->getIdentifier(), 
TL.getNamedTypeLoc().getBeginLoc(), QualType(), nullptr,
+false);
+
+if (InstName.isNull())
+  return QualType();
+
+// If it's still dependent, make a dependent specialization.
+// if (InstName.getAsDependentTemplateName())
+//   return SemaRef.Context.getDependentTemplateSpecializationType(
+//   Keyword, QualifierLoc.getNestedNameSpecifier(), Name,
+//   Args.arguments());
+
+// Otherwise, make an elaborated type wrapping a non-dependent
+// specialization.
+// NamedT = getDerived().RebuildTemplateSpecializationType(InstName, 
TL.getNamedTypeLoc().getBeginLoc(), NewTemplateArgs);
+NamedT = TransformTemplateSpecializationType(TLB, SpecTL, InstName);
+  } else {
+NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
+
+  }
+
   if (NamedT.isNull())
 return QualType();
 

>From cb29d45c174f4fd267c273c4386a2010941a63ac Mon Sep 17 00:00:00 2001
From: Qizhi Hu <836744...@qq.com>
Date: Sun, 26 May 2024 19:35:17 +0800
Subject: [PATCH 2/2] [Clang][Sema] Use correct TemplateName when transforming
 TemplateSpecializationType

---
 clang/lib/Sema/TreeTransform.h| 54 ++-
 clang/test/SemaCXX/PR91677.cpp| 31 +++
 .../SemaTemplate/typename-specifier-3.cpp |  7 +--
 3 files changed, 52 insertions(+), 40 deletions(-)
 create mode 100644 clang/test/SemaCXX/PR91677.cpp

diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 7e8b080a347e8..6ef2eec09ec02 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -29,10 +29,8 @@
 #include "clang/AST/StmtObjC.h

[clang] [Clang][Sema] Use correct TemplateName when transforming TemplateSpecializationType (PR #93411)

2024-05-26 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Qizhi Hu (jcsxky)


Changes

Consider the following testcase:
```cpp
namespace PR12884_original {
  template  struct A {
struct B { ##1
  template  struct X {};
  typedef int arg;
};
struct C {
  typedef B::X x; 
};
  };

  template <> struct A::B { ##2
template  struct X {};
static const int arg = 0;
  };

  A::C::x a;
}
```
It will crash when compiling with `clang(assertions trunk)`. The reason is that 
we lookup `X`(`B::X`) in `##1` when instantiating `typedef 
B::X x; ` during instantiating `A::C::x`. 
This is incorrect because we should lookup `X` in `##2` when we see the 
declaration `A::C::x a;`. Since clang parse `A::B` 
to an `ElaboratedType`(`typename` is not required while compiling with 
`-std=c++20`)  while `typename A::B` turns to be a 
`DependentTemplateSpecializationType`, we should rebuild the `TemplateName` 
with transformed `Qualifier`(whose type is `NestedNameSpecifier`) to make sure 
the lookup context is correct.
This patch also attempts to fix #91677 which crashes with the same 
reason.

---
Full diff: https://github.com/llvm/llvm-project/pull/93411.diff


3 Files Affected:

- (modified) clang/lib/Sema/TreeTransform.h (+24-3) 
- (added) clang/test/SemaCXX/PR91677.cpp (+31) 
- (modified) clang/test/SemaTemplate/typename-specifier-3.cpp (+4-3) 


``diff
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index dee335b526991..6ef2eec09ec02 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -7216,9 +7216,30 @@ 
TreeTransform::TransformElaboratedType(TypeLocBuilder &TLB,
   return QualType();
   }
 
-  QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
-  if (NamedT.isNull())
-return QualType();
+  QualType NamedT;
+  if (SemaRef.getLangOpts().CPlusPlus20 && QualifierLoc &&
+  isa(TL.getNamedTypeLoc().getType())) {
+TemplateSpecializationTypeLoc SpecTL =
+TL.getNamedTypeLoc().castAs();
+const TemplateSpecializationType *TST =
+SpecTL.getType()->castAs();
+CXXScopeSpec SS;
+SS.Adopt(QualifierLoc);
+if (TemplateDecl *TD = TST->getTemplateName().getAsTemplateDecl()) {
+  TemplateName InstName = getDerived().RebuildTemplateName(
+  SS, TL.getTemplateKeywordLoc(), *TD->getIdentifier(),
+  TL.getNamedTypeLoc().getBeginLoc(), /*ObjectType=*/QualType(),
+  /*FirstQualifierInScope=*/nullptr, /*AllowInjectedClassName=*/false);
+  if (InstName.isNull())
+return QualType();
+  NamedT = TransformTemplateSpecializationType(TLB, SpecTL, InstName);
+}
+  }
+  if (NamedT.isNull()) {
+NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
+if (NamedT.isNull())
+  return QualType();
+  }
 
   // C++0x [dcl.type.elab]p2:
   //   If the identifier resolves to a typedef-name or the simple-template-id
diff --git a/clang/test/SemaCXX/PR91677.cpp b/clang/test/SemaCXX/PR91677.cpp
new file mode 100644
index 0..ef2999f959506
--- /dev/null
+++ b/clang/test/SemaCXX/PR91677.cpp
@@ -0,0 +1,31 @@
+// RUN: %clang_cc1 -verify -std=c++20 -fsyntax-only %s
+// expected-no-diagnostics
+
+template  struct t1 {
+  template 
+  struct t2 {};
+};
+
+template 
+t1::template t2 f1();
+
+void f2() {
+  f1();
+}
+
+namespace N {
+  template  struct A {
+struct B {
+  template  struct X {};
+  typedef int arg;
+};
+struct C {
+  typedef B::template X x;
+};
+  };
+
+  template <> struct A::B {
+template  struct X {};
+static const int arg = 0;
+  };
+}
diff --git a/clang/test/SemaTemplate/typename-specifier-3.cpp 
b/clang/test/SemaTemplate/typename-specifier-3.cpp
index 714830f0032d2..a62a1fc5ab39c 100644
--- a/clang/test/SemaTemplate/typename-specifier-3.cpp
+++ b/clang/test/SemaTemplate/typename-specifier-3.cpp
@@ -28,16 +28,17 @@ namespace PR12884_original {
   typedef int arg;
 };
 struct C {
-  typedef B::X x; // precxx17-warning{{missing 'typename' 
prior to dependent type name B::X; implicit 'typename' is a C++20 extension}}
+  typedef B::X x; // precxx17-warning{{missing 'typename' 
prior to dependent type name B::X; implicit 'typename' is a C++20 extension}} \
+   cxx17-error{{typename specifier refers 
to non-type member 'arg' in 'PR12884_original::A::B'}}
 };
   };
 
   template <> struct A::B {
 template  struct X {};
-static const int arg = 0;
+static const int arg = 0; // cxx17-note{{referenced member 'arg' is 
declared here}}
   };
 
-  A::C::x a;
+  A::C::x a; // cxx17-note{{in instantiation of member class 
'PR12884_original::A::C' requested here}}
 }
 namespace PR12884_half_fixed {
   template  struct A {

``




https://github.com/llvm/llvm-project/pull/93411
__

[clang] [Clang][Sema] Use correct TemplateName when transforming TemplateSpecializationType (PR #93411)

2024-05-26 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky updated 
https://github.com/llvm/llvm-project/pull/93411

>From f5f0b14945a70e3e4fd92d5e5cbdb428334fe2b8 Mon Sep 17 00:00:00 2001
From: Qizhi Hu <836744...@qq.com>
Date: Sat, 25 May 2024 16:30:27 +0800
Subject: [PATCH 1/2] [Clang][Sema] Use correct TemplateName when transforming
 TemplateSpecializationType

---
 clang/lib/Sema/TreeTransform.h | 43 +-
 1 file changed, 42 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index dee335b526991..7e8b080a347e8 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -29,8 +29,10 @@
 #include "clang/AST/StmtObjC.h"
 #include "clang/AST/StmtOpenACC.h"
 #include "clang/AST/StmtOpenMP.h"
+#include "clang/AST/TypeLoc.h"
 #include "clang/Basic/DiagnosticParse.h"
 #include "clang/Basic/OpenMPKinds.h"
+#include "clang/Sema/DeclSpec.h"
 #include "clang/Sema/Designator.h"
 #include "clang/Sema/EnterExpressionEvaluationContext.h"
 #include "clang/Sema/Lookup.h"
@@ -7216,7 +7218,46 @@ 
TreeTransform::TransformElaboratedType(TypeLocBuilder &TLB,
   return QualType();
   }
 
-  QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
+  QualType NamedT;
+  if (0 && SemaRef.getLangOpts().CPlusPlus20 && QualifierLoc && 
isa(TL.getNamedTypeLoc().getType())) {
+const TemplateSpecializationType *TST = 
TL.getNamedTypeLoc().getType()->getAs();
+TemplateSpecializationTypeLoc SpecTL =
+TL.getNamedTypeLoc().castAs();
+// TemplateArgumentListInfo NewTemplateArgs;
+// NewTemplateArgs.setLAngleLoc(SpecTL.getLAngleLoc());
+// NewTemplateArgs.setRAngleLoc(SpecTL.getRAngleLoc());
+
+// typedef TemplateArgumentLocContainerIterator<
+// TemplateSpecializationTypeLoc> ArgIterator;
+// if (getDerived().TransformTemplateArguments(ArgIterator(SpecTL, 0),
+// ArgIterator(SpecTL, 
SpecTL.getNumArgs()),
+// NewTemplateArgs))
+//   return QualType();
+
+CXXScopeSpec SS;
+SS.Adopt(QualifierLoc);
+TemplateName InstName = getDerived().RebuildTemplateName(
+SS, TL.getTemplateKeywordLoc(), 
*TST->getTemplateName().getAsTemplateDecl()->getIdentifier(), 
TL.getNamedTypeLoc().getBeginLoc(), QualType(), nullptr,
+false);
+
+if (InstName.isNull())
+  return QualType();
+
+// If it's still dependent, make a dependent specialization.
+// if (InstName.getAsDependentTemplateName())
+//   return SemaRef.Context.getDependentTemplateSpecializationType(
+//   Keyword, QualifierLoc.getNestedNameSpecifier(), Name,
+//   Args.arguments());
+
+// Otherwise, make an elaborated type wrapping a non-dependent
+// specialization.
+// NamedT = getDerived().RebuildTemplateSpecializationType(InstName, 
TL.getNamedTypeLoc().getBeginLoc(), NewTemplateArgs);
+NamedT = TransformTemplateSpecializationType(TLB, SpecTL, InstName);
+  } else {
+NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
+
+  }
+
   if (NamedT.isNull())
 return QualType();
 

>From e60cdac25c4ea2e85894e51dfd5268544cadd27d Mon Sep 17 00:00:00 2001
From: Qizhi Hu <836744...@qq.com>
Date: Sun, 26 May 2024 19:35:17 +0800
Subject: [PATCH 2/2] [Clang][Sema] Use correct TemplateName when transforming
 TemplateSpecializationType

---
 clang/lib/Sema/TreeTransform.h| 54 ++-
 clang/test/SemaCXX/PR91677.cpp| 31 +++
 .../SemaTemplate/typename-specifier-3.cpp |  7 +--
 3 files changed, 52 insertions(+), 40 deletions(-)
 create mode 100644 clang/test/SemaCXX/PR91677.cpp

diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 7e8b080a347e8..6ef2eec09ec02 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -29,10 +29,8 @@
 #include "clang/AST/StmtObjC.h"
 #include "clang/AST/StmtOpenACC.h"
 #include "clang/AST/StmtOpenMP.h"
-#include "clang/AST/TypeLoc.h"
 #include "clang/Basic/DiagnosticParse.h"
 #include "clang/Basic/OpenMPKinds.h"
-#include "clang/Sema/DeclSpec.h"
 #include "clang/Sema/Designator.h"
 #include "clang/Sema/EnterExpressionEvaluationContext.h"
 #include "clang/Sema/Lookup.h"
@@ -7219,48 +7217,30 @@ 
TreeTransform::TransformElaboratedType(TypeLocBuilder &TLB,
   }
 
   QualType NamedT;
-  if (0 && SemaRef.getLangOpts().CPlusPlus20 && QualifierLoc && 
isa(TL.getNamedTypeLoc().getType())) {
-const TemplateSpecializationType *TST = 
TL.getNamedTypeLoc().getType()->getAs();
+  if (SemaRef.getLangOpts().CPlusPlus20 && QualifierLoc &&
+  isa(TL.getNamedTypeLoc().getType())) {
 TemplateSpecializationTypeLoc SpecTL =
 TL.getNamedTypeLoc().castAs();
-// TemplateArgumentListInfo NewTemplateArgs;
-// NewTemplateArgs.setLAngleLoc(SpecTL.getLAngleLoc());
-// NewTemplateArgs.setRAngleLoc(SpecTL.getRAngleLoc());
-
-// typedef T

[clang] [Clang][Sema] Use correct TemplateName when transforming TemplateSpecializationType (PR #93411)

2024-05-26 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky updated 
https://github.com/llvm/llvm-project/pull/93411

>From f5f0b14945a70e3e4fd92d5e5cbdb428334fe2b8 Mon Sep 17 00:00:00 2001
From: Qizhi Hu <836744...@qq.com>
Date: Sat, 25 May 2024 16:30:27 +0800
Subject: [PATCH 1/2] [Clang][Sema] Use correct TemplateName when transforming
 TemplateSpecializationType

---
 clang/lib/Sema/TreeTransform.h | 43 +-
 1 file changed, 42 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index dee335b526991..7e8b080a347e8 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -29,8 +29,10 @@
 #include "clang/AST/StmtObjC.h"
 #include "clang/AST/StmtOpenACC.h"
 #include "clang/AST/StmtOpenMP.h"
+#include "clang/AST/TypeLoc.h"
 #include "clang/Basic/DiagnosticParse.h"
 #include "clang/Basic/OpenMPKinds.h"
+#include "clang/Sema/DeclSpec.h"
 #include "clang/Sema/Designator.h"
 #include "clang/Sema/EnterExpressionEvaluationContext.h"
 #include "clang/Sema/Lookup.h"
@@ -7216,7 +7218,46 @@ 
TreeTransform::TransformElaboratedType(TypeLocBuilder &TLB,
   return QualType();
   }
 
-  QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
+  QualType NamedT;
+  if (0 && SemaRef.getLangOpts().CPlusPlus20 && QualifierLoc && 
isa(TL.getNamedTypeLoc().getType())) {
+const TemplateSpecializationType *TST = 
TL.getNamedTypeLoc().getType()->getAs();
+TemplateSpecializationTypeLoc SpecTL =
+TL.getNamedTypeLoc().castAs();
+// TemplateArgumentListInfo NewTemplateArgs;
+// NewTemplateArgs.setLAngleLoc(SpecTL.getLAngleLoc());
+// NewTemplateArgs.setRAngleLoc(SpecTL.getRAngleLoc());
+
+// typedef TemplateArgumentLocContainerIterator<
+// TemplateSpecializationTypeLoc> ArgIterator;
+// if (getDerived().TransformTemplateArguments(ArgIterator(SpecTL, 0),
+// ArgIterator(SpecTL, 
SpecTL.getNumArgs()),
+// NewTemplateArgs))
+//   return QualType();
+
+CXXScopeSpec SS;
+SS.Adopt(QualifierLoc);
+TemplateName InstName = getDerived().RebuildTemplateName(
+SS, TL.getTemplateKeywordLoc(), 
*TST->getTemplateName().getAsTemplateDecl()->getIdentifier(), 
TL.getNamedTypeLoc().getBeginLoc(), QualType(), nullptr,
+false);
+
+if (InstName.isNull())
+  return QualType();
+
+// If it's still dependent, make a dependent specialization.
+// if (InstName.getAsDependentTemplateName())
+//   return SemaRef.Context.getDependentTemplateSpecializationType(
+//   Keyword, QualifierLoc.getNestedNameSpecifier(), Name,
+//   Args.arguments());
+
+// Otherwise, make an elaborated type wrapping a non-dependent
+// specialization.
+// NamedT = getDerived().RebuildTemplateSpecializationType(InstName, 
TL.getNamedTypeLoc().getBeginLoc(), NewTemplateArgs);
+NamedT = TransformTemplateSpecializationType(TLB, SpecTL, InstName);
+  } else {
+NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
+
+  }
+
   if (NamedT.isNull())
 return QualType();
 

>From 3ebed0fecd90101b57082909348a60070c689d12 Mon Sep 17 00:00:00 2001
From: Qizhi Hu <836744...@qq.com>
Date: Sun, 26 May 2024 19:35:17 +0800
Subject: [PATCH 2/2] [Clang][Sema] Use correct TemplateName when transforming
 TemplateSpecializationType

---
 clang/lib/Sema/TreeTransform.h| 54 ++-
 clang/test/SemaCXX/PR91677.cpp| 14 +
 .../SemaTemplate/typename-specifier-3.cpp |  7 +--
 3 files changed, 35 insertions(+), 40 deletions(-)
 create mode 100644 clang/test/SemaCXX/PR91677.cpp

diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 7e8b080a347e8..6ef2eec09ec02 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -29,10 +29,8 @@
 #include "clang/AST/StmtObjC.h"
 #include "clang/AST/StmtOpenACC.h"
 #include "clang/AST/StmtOpenMP.h"
-#include "clang/AST/TypeLoc.h"
 #include "clang/Basic/DiagnosticParse.h"
 #include "clang/Basic/OpenMPKinds.h"
-#include "clang/Sema/DeclSpec.h"
 #include "clang/Sema/Designator.h"
 #include "clang/Sema/EnterExpressionEvaluationContext.h"
 #include "clang/Sema/Lookup.h"
@@ -7219,48 +7217,30 @@ 
TreeTransform::TransformElaboratedType(TypeLocBuilder &TLB,
   }
 
   QualType NamedT;
-  if (0 && SemaRef.getLangOpts().CPlusPlus20 && QualifierLoc && 
isa(TL.getNamedTypeLoc().getType())) {
-const TemplateSpecializationType *TST = 
TL.getNamedTypeLoc().getType()->getAs();
+  if (SemaRef.getLangOpts().CPlusPlus20 && QualifierLoc &&
+  isa(TL.getNamedTypeLoc().getType())) {
 TemplateSpecializationTypeLoc SpecTL =
 TL.getNamedTypeLoc().castAs();
-// TemplateArgumentListInfo NewTemplateArgs;
-// NewTemplateArgs.setLAngleLoc(SpecTL.getLAngleLoc());
-// NewTemplateArgs.setRAngleLoc(SpecTL.getRAngleLoc());
-
-// typedef Templat

[clang] [clang] In Sema use new parentEvaluationContext function (PR #93338)

2024-05-26 Thread Oleksandr T. via cfe-commits

https://github.com/a-tarasyuk updated 
https://github.com/llvm/llvm-project/pull/93338

>From 43050fe6f93436b43b4aa336013a91eed1d6d23a Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Fri, 24 May 2024 22:46:53 +0300
Subject: [PATCH 1/3] fix(93284): replace direct access to ExprEvalContexts
 with parentEvaluationContext

---
 clang/include/clang/Sema/Sema.h |  5 ++---
 clang/lib/Sema/SemaExpr.cpp | 15 +++
 2 files changed, 9 insertions(+), 11 deletions(-)

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 5247379181808..1214a262076e0 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -6289,10 +6289,9 @@ class Sema final : public SemaBase {
   /// flag from previous context.
   void keepInLifetimeExtendingContext() {
 if (ExprEvalContexts.size() > 2 &&
-ExprEvalContexts[ExprEvalContexts.size() - 2]
-.InLifetimeExtendingContext) {
+parentEvaluationContext().InLifetimeExtendingContext) {
   auto &LastRecord = ExprEvalContexts.back();
-  auto &PrevRecord = ExprEvalContexts[ExprEvalContexts.size() - 2];
+  auto &PrevRecord = parentEvaluationContext();
   LastRecord.InLifetimeExtendingContext =
   PrevRecord.InLifetimeExtendingContext;
 }
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index ff9c5ead36dcf..0236db1f37b1a 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -17223,8 +17223,7 @@ ExprResult Sema::TransformToPotentiallyEvaluated(Expr 
*E) {
 TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
   assert(isUnevaluatedContext() &&
  "Should only transform unevaluated expressions");
-  ExprEvalContexts.back().Context =
-  ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
+  ExprEvalContexts.back().Context = parentEvaluationContext().Context;
   if (isUnevaluatedContext())
 return TInfo;
   return TransformToPE(*this).TransformType(TInfo);
@@ -17241,14 +17240,13 @@ Sema::PushExpressionEvaluationContext(
   // discarded statements or immediate context are themselves
   // a discarded statement or an immediate context, respectively.
   ExprEvalContexts.back().InDiscardedStatement =
-  ExprEvalContexts[ExprEvalContexts.size() - 2]
-  .isDiscardedStatementContext();
+  parentEvaluationContext().isDiscardedStatementContext();
 
   // C++23 [expr.const]/p15
   // An expression or conversion is in an immediate function context if [...]
   // it is a subexpression of a manifestly constant-evaluated expression or
   // conversion.
-  const auto &Prev = ExprEvalContexts[ExprEvalContexts.size() - 2];
+  const auto &Prev = parentEvaluationContext();
   ExprEvalContexts.back().InImmediateFunctionContext =
   Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
 
@@ -17693,12 +17691,13 @@ void Sema::PopExpressionEvaluationContext() {
 
   // Append the collected materialized temporaries into previous context before
   // exit if the previous also is a lifetime extending context.
-  auto &PrevRecord = ExprEvalContexts[ExprEvalContexts.size() - 2];
+  auto &PrevRecord = parentEvaluationContext();
   if (getLangOpts().CPlusPlus23 && Rec.InLifetimeExtendingContext &&
   PrevRecord.InLifetimeExtendingContext &&
   !Rec.ForRangeLifetimeExtendTemps.empty()) {
-PrevRecord.ForRangeLifetimeExtendTemps.append(
-Rec.ForRangeLifetimeExtendTemps);
+const_cast &>(
+PrevRecord.ForRangeLifetimeExtendTemps)
+.append(Rec.ForRangeLifetimeExtendTemps);
   }
 
   WarnOnPendingNoDerefs(Rec);

>From 91fae0115214e9beddb1a0ea74c08d41fc9e4fbb Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Sat, 25 May 2024 23:07:13 +0300
Subject: [PATCH 2/3] add non-const overload for parentEvaluationContext

---
 clang/include/clang/Sema/Sema.h | 6 ++
 clang/lib/Sema/SemaExpr.cpp | 5 ++---
 2 files changed, 8 insertions(+), 3 deletions(-)

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 1214a262076e0..2fe885e5429ca 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -5153,6 +5153,12 @@ class Sema final : public SemaBase {
 return ExprEvalContexts.back();
   };
 
+  ExpressionEvaluationContextRecord &parentEvaluationContext() {
+assert(ExprEvalContexts.size() >= 2 &&
+   "Must be in an expression evaluation context");
+return ExprEvalContexts[ExprEvalContexts.size() - 2];
+  };
+
   const ExpressionEvaluationContextRecord &parentEvaluationContext() const {
 assert(ExprEvalContexts.size() >= 2 &&
"Must be in an expression evaluation context");
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 0236db1f37b1a..01924f95054cb 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -17695,9 +17695,8 @@ void Sema::PopExpressionEvaluationContext() {
   if (getLangOpts().CPlusPlus23 && Rec.InLifetime

[clang] [clang] In Sema use new parentEvaluationContext function (PR #93338)

2024-05-26 Thread Vlad Serebrennikov via cfe-commits

https://github.com/Endilll commented:

LGTM

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


[clang-tools-extra] [clang-tidy] new check misc-use-internal-linkage (PR #90830)

2024-05-26 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 updated 
https://github.com/llvm/llvm-project/pull/90830

>From 24cbbd0c87ab2a06381d210da1dff5f966b72773 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Thu, 2 May 2024 15:44:45 +0800
Subject: [PATCH 1/7] reformat

---
 .../clang-tidy/readability/CMakeLists.txt |  1 +
 .../readability/ReadabilityTidyModule.cpp |  3 +
 .../UnnecessaryExternalLinkageCheck.cpp   | 82 +++
 .../UnnecessaryExternalLinkageCheck.h | 33 
 clang-tools-extra/docs/ReleaseNotes.rst   |  5 ++
 .../docs/clang-tidy/checks/list.rst   |  1 +
 .../unnecessary-external-linkage.rst  | 26 ++
 .../readability/Inputs/mark-static-var/func.h |  3 +
 .../readability/Inputs/mark-static-var/var.h  |  3 +
 .../unnecessary-external-linkage-func.cpp | 30 +++
 .../unnecessary-external-linkage-var.cpp  | 40 +
 11 files changed, 227 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/readability/unnecessary-external-linkage.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/mark-static-var/func.h
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/mark-static-var/var.h
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/readability/unnecessary-external-linkage-func.cpp
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/readability/unnecessary-external-linkage-var.cpp

diff --git a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
index 41065fc8e8785..8f58d9f24ba49 100644
--- a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
@@ -23,6 +23,7 @@ add_clang_library(clangTidyReadabilityModule
   IdentifierLengthCheck.cpp
   IdentifierNamingCheck.cpp
   ImplicitBoolConversionCheck.cpp
+  UnnecessaryExternalLinkageCheck.cpp
   RedundantInlineSpecifierCheck.cpp
   InconsistentDeclarationParameterNameCheck.cpp
   IsolateDeclarationCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp 
b/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp
index d61c0ba39658e..d389287e8f490 100644
--- a/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp
@@ -58,6 +58,7 @@
 #include "StringCompareCheck.h"
 #include "SuspiciousCallArgumentCheck.h"
 #include "UniqueptrDeleteReleaseCheck.h"
+#include "UnnecessaryExternalLinkageCheck.h"
 #include "UppercaseLiteralSuffixCheck.h"
 #include "UseAnyOfAllOfCheck.h"
 #include "UseStdMinMaxCheck.h"
@@ -106,6 +107,8 @@ class ReadabilityModule : public ClangTidyModule {
 "readability-identifier-naming");
 CheckFactories.registerCheck(
 "readability-implicit-bool-conversion");
+CheckFactories.registerCheck(
+"readability-unnecessary-external-linkage");
 CheckFactories.registerCheck(
 "readability-math-missing-parentheses");
 CheckFactories.registerCheck(
diff --git 
a/clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp
new file mode 100644
index 0..4970d3339ef05
--- /dev/null
+++ 
b/clang-tools-extra/clang-tidy/readability/UnnecessaryExternalLinkageCheck.cpp
@@ -0,0 +1,82 @@
+//===--- UnnecessaryExternalLinkageCheck.cpp - clang-tidy
+//-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UnnecessaryExternalLinkageCheck.h"
+#include "clang/AST/Decl.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersMacros.h"
+#include "clang/Basic/Specifiers.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+namespace {
+
+AST_POLYMORPHIC_MATCHER(isFirstDecl,
+AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
+VarDecl)) {
+  return Node.isFirstDecl();
+}
+
+AST_MATCHER(Decl, isInMainFile) {
+  for (const Decl *D : Node.redecls())
+if (!Finder->getASTContext().getSourceManager().isInMainFile(
+D->getLocation()))
+  return false;
+  return true;
+}
+
+AST_POLYMORPHIC_MATCHER(isExternStorageClass,
+AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl,
+   

[clang] [clang-tools-extra] [Clang] Unify interface for accessing template arguments as written for class/variable template specializations (PR #81642)

2024-05-26 Thread Kim Gräsman via cfe-commits

kimgr wrote:

@sdkrystian It looks like this PR broke IWYU with respect to this assumption:
> Moreover, we don't ever need the type as written -- in almost all cases, we 
> only want the template arguments (e.g. in tooling use-cases).

As I understand it, IWYU did use the type as written to do resugaring of 
template types, here: 
https://github.com/include-what-you-use/include-what-you-use/blob/master/iwyu_ast_util.cc#L935

Do you have any tips for how to implement that on top of the new model? 
Manually type-switch all TemplateArgument kinds and map to a Type, possibly via 
Expr?

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


[clang] [clang] In Sema use new parentEvaluationContext function (PR #93338)

2024-05-26 Thread via cfe-commits

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


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


[clang] a4a4366 - [clang] In Sema use new parentEvaluationContext function (#93338)

2024-05-26 Thread via cfe-commits

Author: Oleksandr T
Date: 2024-05-26T15:46:08+02:00
New Revision: a4a436672a2c179274e07aeb68e9acd6f483a653

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

LOG: [clang] In Sema use new parentEvaluationContext function (#93338)

Fixes #93284

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaExpr.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 5247379181808..ec083f7cc09b7 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -5153,12 +5153,16 @@ class Sema final : public SemaBase {
 return ExprEvalContexts.back();
   };
 
-  const ExpressionEvaluationContextRecord &parentEvaluationContext() const {
+  ExpressionEvaluationContextRecord &parentEvaluationContext() {
 assert(ExprEvalContexts.size() >= 2 &&
"Must be in an expression evaluation context");
 return ExprEvalContexts[ExprEvalContexts.size() - 2];
   };
 
+  const ExpressionEvaluationContextRecord &parentEvaluationContext() const {
+return const_cast(this)->parentEvaluationContext();
+  };
+
   bool isBoundsAttrContext() const {
 return ExprEvalContexts.back().ExprContext ==
ExpressionEvaluationContextRecord::ExpressionKind::
@@ -6289,10 +6293,9 @@ class Sema final : public SemaBase {
   /// flag from previous context.
   void keepInLifetimeExtendingContext() {
 if (ExprEvalContexts.size() > 2 &&
-ExprEvalContexts[ExprEvalContexts.size() - 2]
-.InLifetimeExtendingContext) {
+parentEvaluationContext().InLifetimeExtendingContext) {
   auto &LastRecord = ExprEvalContexts.back();
-  auto &PrevRecord = ExprEvalContexts[ExprEvalContexts.size() - 2];
+  auto &PrevRecord = parentEvaluationContext();
   LastRecord.InLifetimeExtendingContext =
   PrevRecord.InLifetimeExtendingContext;
 }

diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 410f80ae864a1..ded4f59833ac0 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -17232,8 +17232,7 @@ ExprResult Sema::TransformToPotentiallyEvaluated(Expr 
*E) {
 TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
   assert(isUnevaluatedContext() &&
  "Should only transform unevaluated expressions");
-  ExprEvalContexts.back().Context =
-  ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
+  ExprEvalContexts.back().Context = parentEvaluationContext().Context;
   if (isUnevaluatedContext())
 return TInfo;
   return TransformToPE(*this).TransformType(TInfo);
@@ -17250,14 +17249,13 @@ Sema::PushExpressionEvaluationContext(
   // discarded statements or immediate context are themselves
   // a discarded statement or an immediate context, respectively.
   ExprEvalContexts.back().InDiscardedStatement =
-  ExprEvalContexts[ExprEvalContexts.size() - 2]
-  .isDiscardedStatementContext();
+  parentEvaluationContext().isDiscardedStatementContext();
 
   // C++23 [expr.const]/p15
   // An expression or conversion is in an immediate function context if [...]
   // it is a subexpression of a manifestly constant-evaluated expression or
   // conversion.
-  const auto &Prev = ExprEvalContexts[ExprEvalContexts.size() - 2];
+  const auto &Prev = parentEvaluationContext();
   ExprEvalContexts.back().InImmediateFunctionContext =
   Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
 
@@ -17702,7 +17700,7 @@ void Sema::PopExpressionEvaluationContext() {
 
   // Append the collected materialized temporaries into previous context before
   // exit if the previous also is a lifetime extending context.
-  auto &PrevRecord = ExprEvalContexts[ExprEvalContexts.size() - 2];
+  auto &PrevRecord = parentEvaluationContext();
   if (getLangOpts().CPlusPlus23 && Rec.InLifetimeExtendingContext &&
   PrevRecord.InLifetimeExtendingContext &&
   !Rec.ForRangeLifetimeExtendTemps.empty()) {



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


[clang] [clang] In Sema use new parentEvaluationContext function (PR #93338)

2024-05-26 Thread via cfe-commits

https://github.com/cor3ntin closed 
https://github.com/llvm/llvm-project/pull/93338
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [compiler-rt] [XRay] Add support for instrumentation of DSOs on x86_64 (PR #90959)

2024-05-26 Thread Tomer Shafir via cfe-commits

tomershafir wrote:

@sebastiankreutzer hey, were you able to reach the maintainers of llvm-xray and 
probe them about its dev status? If yes, can you pls share how to reach them 
and what did they say?

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


[clang] [clang][Sema] Don't emit 'declared here' note for builtin functions with no decl in source (PR #93394)

2024-05-26 Thread Youngsuk Kim via cfe-commits

https://github.com/JOE1994 updated 
https://github.com/llvm/llvm-project/pull/93394

>From 00c93043fca8f8a1f20634ea1b281c60926bd571 Mon Sep 17 00:00:00 2001
From: Youngsuk Kim 
Date: Sat, 25 May 2024 20:42:43 -0500
Subject: [PATCH 1/3] [clang][Sema] Don't emit 'declared here' note for builtin
 functions with no decl in source

Fixes #93369
---
 clang/lib/Sema/SemaLookup.cpp   | 10 ++
 clang/test/SemaCXX/invalid-if-constexpr.cpp |  2 +-
 2 files changed, 11 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaLookup.cpp b/clang/lib/Sema/SemaLookup.cpp
index ef0a655b631ab..348f9e5b8f530 100644
--- a/clang/lib/Sema/SemaLookup.cpp
+++ b/clang/lib/Sema/SemaLookup.cpp
@@ -5897,6 +5897,16 @@ void Sema::diagnoseTypo(const TypoCorrection &Correction,
 
   NamedDecl *ChosenDecl =
   Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
+
+  // For builtin functions which aren't declared anywhere in source,
+  // don't emit the "declared here" note.
+  if (auto *FD = dyn_cast_or_null(ChosenDecl);
+  FD && FD->getBuiltinID() &&
+  PrevNote.getDiagID() == diag::note_previous_decl &&
+  Correction.getCorrectionRange().getBegin() == FD->getBeginLoc()) {
+ChosenDecl = nullptr;
+  }
+
   if (PrevNote.getDiagID() && ChosenDecl)
 Diag(ChosenDecl->getLocation(), PrevNote)
   << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
diff --git a/clang/test/SemaCXX/invalid-if-constexpr.cpp 
b/clang/test/SemaCXX/invalid-if-constexpr.cpp
index 7643c47488f05..16d422880e8a9 100644
--- a/clang/test/SemaCXX/invalid-if-constexpr.cpp
+++ b/clang/test/SemaCXX/invalid-if-constexpr.cpp
@@ -5,7 +5,7 @@ void similar() { // expected-note {{'similar' declared here}}
   if constexpr (similer<>) {} // expected-error {{use of undeclared identifier 
'similer'; did you mean 'similar'?}}
 }
 void a() { if constexpr (__adl_swap<>) {}} // expected-error{{use of 
undeclared identifier '__adl_swap'; did you mean '__sync_swap'?}} \
-   // expected-note {{'__sync_swap' 
declared here}}
+   // not-expected-note 
{{'__sync_swap' declared here}}
 
 int AA() { return true;} // expected-note {{'AA' declared here}}
 

>From 42bbff26459b71e9d77c4d907703930e12db8958 Mon Sep 17 00:00:00 2001
From: Youngsuk Kim 
Date: Sun, 26 May 2024 05:53:03 -0400
Subject: [PATCH 2/3] Use dyn_cast_if_present

Co-authored-by: Timm Baeder 
---
 clang/lib/Sema/SemaLookup.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaLookup.cpp b/clang/lib/Sema/SemaLookup.cpp
index 348f9e5b8f530..be6ea20a956a3 100644
--- a/clang/lib/Sema/SemaLookup.cpp
+++ b/clang/lib/Sema/SemaLookup.cpp
@@ -5900,7 +5900,7 @@ void Sema::diagnoseTypo(const TypoCorrection &Correction,
 
   // For builtin functions which aren't declared anywhere in source,
   // don't emit the "declared here" note.
-  if (auto *FD = dyn_cast_or_null(ChosenDecl);
+  if (const auto *FD = dyn_cast_if_present(ChosenDecl);
   FD && FD->getBuiltinID() &&
   PrevNote.getDiagID() == diag::note_previous_decl &&
   Correction.getCorrectionRange().getBegin() == FD->getBeginLoc()) {

>From e4f190be4f59dec78c8a184d9603ac8856da3900 Mon Sep 17 00:00:00 2001
From: Youngsuk Kim 
Date: Sun, 26 May 2024 10:28:02 -0500
Subject: [PATCH 3/3] Add dedicated test

---
 clang/test/SemaCXX/invalid-if-constexpr.cpp | 1 -
 clang/test/SemaCXX/typo-correction-builtin-func.cpp | 8 
 2 files changed, 8 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/SemaCXX/typo-correction-builtin-func.cpp

diff --git a/clang/test/SemaCXX/invalid-if-constexpr.cpp 
b/clang/test/SemaCXX/invalid-if-constexpr.cpp
index 16d422880e8a9..1fe0bc3415c84 100644
--- a/clang/test/SemaCXX/invalid-if-constexpr.cpp
+++ b/clang/test/SemaCXX/invalid-if-constexpr.cpp
@@ -5,7 +5,6 @@ void similar() { // expected-note {{'similar' declared here}}
   if constexpr (similer<>) {} // expected-error {{use of undeclared identifier 
'similer'; did you mean 'similar'?}}
 }
 void a() { if constexpr (__adl_swap<>) {}} // expected-error{{use of 
undeclared identifier '__adl_swap'; did you mean '__sync_swap'?}} \
-   // not-expected-note 
{{'__sync_swap' declared here}}
 
 int AA() { return true;} // expected-note {{'AA' declared here}}
 
diff --git a/clang/test/SemaCXX/typo-correction-builtin-func.cpp 
b/clang/test/SemaCXX/typo-correction-builtin-func.cpp
new file mode 100644
index 0..8d369034d1be3
--- /dev/null
+++ b/clang/test/SemaCXX/typo-correction-builtin-func.cpp
@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+// Test that clang does not emit 'declared here' note for builtin functions 
that don't have a declaration in source.
+
+void t0() {
+  constexpr float A = __builtin_isinfinity(); // expected-error {{use of 
undeclared identifier '__builtin_isinfinity'; did you mean 
'__builtin_isfinite'?}}
+

[clang] [clang][Sema] Don't emit 'declared here' note for builtin functions with no decl in source (PR #93394)

2024-05-26 Thread Youngsuk Kim via cfe-commits


@@ -5,7 +5,7 @@ void similar() { // expected-note {{'similar' declared here}}
   if constexpr (similer<>) {} // expected-error {{use of undeclared identifier 
'similer'; did you mean 'similar'?}}
 }
 void a() { if constexpr (__adl_swap<>) {}} // expected-error{{use of 
undeclared identifier '__adl_swap'; did you mean '__sync_swap'?}} \
-   // expected-note {{'__sync_swap' 
declared here}}
+   // not-expected-note 
{{'__sync_swap' declared here}}

JOE1994 wrote:

You are right!

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


[clang] [Clang][Sema] Use correct TemplateName when transforming TemplateSpecializationType (PR #93411)

2024-05-26 Thread Younan Zhang via cfe-commits


@@ -7216,9 +7216,30 @@ 
TreeTransform::TransformElaboratedType(TypeLocBuilder &TLB,
   return QualType();
   }
 
-  QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
-  if (NamedT.isNull())
-return QualType();
+  QualType NamedT;
+  if (SemaRef.getLangOpts().CPlusPlus20 && QualifierLoc &&
+  isa(TL.getNamedTypeLoc().getType())) {
+TemplateSpecializationTypeLoc SpecTL =
+TL.getNamedTypeLoc().castAs();
+const TemplateSpecializationType *TST =
+SpecTL.getType()->castAs();

zyn0217 wrote:

```c++
if (QualType QT = TL.getNamedTypeLoc().getType(); ... && isa<...>(QT)) {
  auto SpecTL = ...;
  auto *TST = QT.getTypePtr();
}
```

Probably looks better.

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


[clang] [Clang][Sema] Use correct TemplateName when transforming TemplateSpecializationType (PR #93411)

2024-05-26 Thread Younan Zhang via cfe-commits


@@ -28,16 +28,17 @@ namespace PR12884_original {
   typedef int arg;
 };
 struct C {
-  typedef B::X x; // precxx17-warning{{missing 'typename' 
prior to dependent type name B::X; implicit 'typename' is a C++20 extension}}

zyn0217 wrote:

A drive-by comment: The test `PR12884_original` is still crashing on trunk but 
it slips through our testing probably because we somehow stop after errors 
above - if we move the whole namespace to the top, then we'd immediately run 
into an assert saying `Unable to find instantiation of declaration!`.

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


[clang] [Clang][Sema] Use correct TemplateName when transforming TemplateSpecializationType (PR #93411)

2024-05-26 Thread Younan Zhang via cfe-commits


@@ -7216,9 +7216,30 @@ 
TreeTransform::TransformElaboratedType(TypeLocBuilder &TLB,
   return QualType();
   }
 
-  QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
-  if (NamedT.isNull())
-return QualType();
+  QualType NamedT;
+  if (SemaRef.getLangOpts().CPlusPlus20 && QualifierLoc &&
+  isa(TL.getNamedTypeLoc().getType())) {
+TemplateSpecializationTypeLoc SpecTL =
+TL.getNamedTypeLoc().castAs();
+const TemplateSpecializationType *TST =
+SpecTL.getType()->castAs();
+CXXScopeSpec SS;
+SS.Adopt(QualifierLoc);
+if (TemplateDecl *TD = TST->getTemplateName().getAsTemplateDecl()) {
+  TemplateName InstName = getDerived().RebuildTemplateName(
+  SS, TL.getTemplateKeywordLoc(), *TD->getIdentifier(),
+  TL.getNamedTypeLoc().getBeginLoc(), /*ObjectType=*/QualType(),
+  /*FirstQualifierInScope=*/nullptr, /*AllowInjectedClassName=*/false);
+  if (InstName.isNull())
+return QualType();
+  NamedT = TransformTemplateSpecializationType(TLB, SpecTL, InstName);

zyn0217 wrote:

Did you mean `getDerived().TransformTemplateSpecializationType()`?

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


[clang] [clang-tools-extra] [libcxx] [clang][Modules] Remove unnecessary includes of `Module.h` (PR #93417)

2024-05-26 Thread David Stone via cfe-commits

https://github.com/davidstone created 
https://github.com/llvm/llvm-project/pull/93417

None

>From f4b9852b0c11a9b5087c5fdb7794b5cab7f4d22c Mon Sep 17 00:00:00 2001
From: David Stone 
Date: Sun, 26 May 2024 10:34:09 -0600
Subject: [PATCH] [clang][Modules] Remove unnecessary includes of `Module.h`

---
 .../clangd/unittests/ReplayPeambleTests.cpp   |  10 +-
 .../include/clang/APINotes/APINotesManager.h  |   5 +-
 .../Serialization/SymbolGraphSerializer.h |   1 -
 clang/include/clang/Serialization/ASTWriter.h |  32 ++---
 .../clang/Serialization/ModuleManager.h   |  14 +-
 clang/lib/APINotes/APINotesManager.cpp|   1 +
 clang/lib/AST/ASTDumper.cpp   |  12 +-
 clang/lib/CodeGen/CodeGenModule.h | 126 --
 clang/lib/ExtractAPI/API.cpp  |   1 -
 .../header_exportable_declarations.cpp|   2 -
 10 files changed, 93 insertions(+), 111 deletions(-)

diff --git a/clang-tools-extra/clangd/unittests/ReplayPeambleTests.cpp 
b/clang-tools-extra/clangd/unittests/ReplayPeambleTests.cpp
index 147d9abe69137..32942e6bbfdc8 100644
--- a/clang-tools-extra/clangd/unittests/ReplayPeambleTests.cpp
+++ b/clang-tools-extra/clangd/unittests/ReplayPeambleTests.cpp
@@ -25,7 +25,6 @@
 #include "clang/AST/DeclTemplate.h"
 #include "clang/Basic/FileEntry.h"
 #include "clang/Basic/LLVM.h"
-#include "clang/Basic/Module.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/TokenKinds.h"
@@ -42,7 +41,11 @@
 #include 
 #include 
 
-namespace clang::clangd {
+namespace clang {
+
+class Module;
+
+namespace clangd {
 namespace {
 struct Inclusion {
   Inclusion(const SourceManager &SM, SourceLocation HashLoc,
@@ -170,4 +173,5 @@ TEST(ReplayPreambleTest, IncludesAndSkippedFiles) {
   }
 }
 } // namespace
-} // namespace clang::clangd
+} // namespace clangd
+} // namespace clang
diff --git a/clang/include/clang/APINotes/APINotesManager.h 
b/clang/include/clang/APINotes/APINotesManager.h
index 18375c9e51a17..40c6328319dbd 100644
--- a/clang/include/clang/APINotes/APINotesManager.h
+++ b/clang/include/clang/APINotes/APINotesManager.h
@@ -9,7 +9,6 @@
 #ifndef LLVM_CLANG_APINOTES_APINOTESMANAGER_H
 #define LLVM_CLANG_APINOTES_APINOTESMANAGER_H
 
-#include "clang/Basic/Module.h"
 #include "clang/Basic/SourceLocation.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"
@@ -24,6 +23,7 @@ namespace clang {
 class DirectoryEntry;
 class FileEntry;
 class LangOptions;
+class Module;
 class SourceManager;
 
 namespace api_notes {
@@ -159,7 +159,8 @@ class APINotesManager {
   ArrayRef getCurrentModuleReaders() const {
 bool HasPublic = CurrentModuleReaders[ReaderKind::Public];
 bool HasPrivate = CurrentModuleReaders[ReaderKind::Private];
-assert((!HasPrivate || HasPublic) && "private module requires public 
module");
+assert((!HasPrivate || HasPublic) &&
+   "private module requires public module");
 if (!HasPrivate && !HasPublic)
   return {};
 return ArrayRef(CurrentModuleReaders).slice(0, HasPrivate ? 2 : 1);
diff --git 
a/clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h 
b/clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h
index 27e9167ca1ad0..f8759bf2d8f25 100644
--- a/clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h
+++ b/clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h
@@ -17,7 +17,6 @@
 #ifndef LLVM_CLANG_EXTRACTAPI_SERIALIZATION_SYMBOLGRAPHSERIALIZER_H
 #define LLVM_CLANG_EXTRACTAPI_SERIALIZATION_SYMBOLGRAPHSERIALIZER_H
 
-#include "clang/Basic/Module.h"
 #include "clang/ExtractAPI/API.h"
 #include "clang/ExtractAPI/APIIgnoresList.h"
 #include "clang/ExtractAPI/Serialization/APISetVisitor.h"
diff --git a/clang/include/clang/Serialization/ASTWriter.h 
b/clang/include/clang/Serialization/ASTWriter.h
index 88192e439a3f0..ddd3514b3c2db 100644
--- a/clang/include/clang/Serialization/ASTWriter.h
+++ b/clang/include/clang/Serialization/ASTWriter.h
@@ -18,7 +18,6 @@
 #include "clang/AST/Decl.h"
 #include "clang/AST/Type.h"
 #include "clang/Basic/LLVM.h"
-#include "clang/Basic/Module.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Sema/Sema.h"
 #include "clang/Sema/SemaConsumer.h"
@@ -277,7 +276,8 @@ class ASTWriter : public ASTDeserializationListener,
   std::vector TypeOffsets;
 
   /// The first ID number we can use for our own identifiers.
-  serialization::IdentifierID FirstIdentID = 
serialization::NUM_PREDEF_IDENT_IDS;
+  serialization::IdentifierID FirstIdentID =
+  serialization::NUM_PREDEF_IDENT_IDS;
 
   /// The identifier ID that will be assigned to the next new identifier.
   serialization::IdentifierID NextIdentID = FirstIdentID;
@@ -288,7 +288,8 @@ class ASTWriter : public ASTDeserializationListener,
   /// The ID numbers for identifiers are consecutive (in order of
   /// discovery), starting at 1. An ID of zero refers to a NULL
   /// IdentifierInfo.
-  llvm::MapVec

[clang] [clang-tools-extra] [libcxx] [clang][Modules] Remove unnecessary includes of `Module.h` (PR #93417)

2024-05-26 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang-modules
@llvm/pr-subscribers-clang-codegen

@llvm/pr-subscribers-clangd

Author: David Stone (davidstone)


Changes



---

Patch is 28.19 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/93417.diff


10 Files Affected:

- (modified) clang-tools-extra/clangd/unittests/ReplayPeambleTests.cpp (+7-3) 
- (modified) clang/include/clang/APINotes/APINotesManager.h (+3-2) 
- (modified) 
clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h (-1) 
- (modified) clang/include/clang/Serialization/ASTWriter.h (+16-16) 
- (modified) clang/include/clang/Serialization/ModuleManager.h (+5-9) 
- (modified) clang/lib/APINotes/APINotesManager.cpp (+1) 
- (modified) clang/lib/AST/ASTDumper.cpp (+3-9) 
- (modified) clang/lib/CodeGen/CodeGenModule.h (+58-68) 
- (modified) clang/lib/ExtractAPI/API.cpp (-1) 
- (modified) 
libcxx/test/tools/clang_tidy_checks/header_exportable_declarations.cpp (-2) 


``diff
diff --git a/clang-tools-extra/clangd/unittests/ReplayPeambleTests.cpp 
b/clang-tools-extra/clangd/unittests/ReplayPeambleTests.cpp
index 147d9abe69137..32942e6bbfdc8 100644
--- a/clang-tools-extra/clangd/unittests/ReplayPeambleTests.cpp
+++ b/clang-tools-extra/clangd/unittests/ReplayPeambleTests.cpp
@@ -25,7 +25,6 @@
 #include "clang/AST/DeclTemplate.h"
 #include "clang/Basic/FileEntry.h"
 #include "clang/Basic/LLVM.h"
-#include "clang/Basic/Module.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/TokenKinds.h"
@@ -42,7 +41,11 @@
 #include 
 #include 
 
-namespace clang::clangd {
+namespace clang {
+
+class Module;
+
+namespace clangd {
 namespace {
 struct Inclusion {
   Inclusion(const SourceManager &SM, SourceLocation HashLoc,
@@ -170,4 +173,5 @@ TEST(ReplayPreambleTest, IncludesAndSkippedFiles) {
   }
 }
 } // namespace
-} // namespace clang::clangd
+} // namespace clangd
+} // namespace clang
diff --git a/clang/include/clang/APINotes/APINotesManager.h 
b/clang/include/clang/APINotes/APINotesManager.h
index 18375c9e51a17..40c6328319dbd 100644
--- a/clang/include/clang/APINotes/APINotesManager.h
+++ b/clang/include/clang/APINotes/APINotesManager.h
@@ -9,7 +9,6 @@
 #ifndef LLVM_CLANG_APINOTES_APINOTESMANAGER_H
 #define LLVM_CLANG_APINOTES_APINOTESMANAGER_H
 
-#include "clang/Basic/Module.h"
 #include "clang/Basic/SourceLocation.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"
@@ -24,6 +23,7 @@ namespace clang {
 class DirectoryEntry;
 class FileEntry;
 class LangOptions;
+class Module;
 class SourceManager;
 
 namespace api_notes {
@@ -159,7 +159,8 @@ class APINotesManager {
   ArrayRef getCurrentModuleReaders() const {
 bool HasPublic = CurrentModuleReaders[ReaderKind::Public];
 bool HasPrivate = CurrentModuleReaders[ReaderKind::Private];
-assert((!HasPrivate || HasPublic) && "private module requires public 
module");
+assert((!HasPrivate || HasPublic) &&
+   "private module requires public module");
 if (!HasPrivate && !HasPublic)
   return {};
 return ArrayRef(CurrentModuleReaders).slice(0, HasPrivate ? 2 : 1);
diff --git 
a/clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h 
b/clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h
index 27e9167ca1ad0..f8759bf2d8f25 100644
--- a/clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h
+++ b/clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h
@@ -17,7 +17,6 @@
 #ifndef LLVM_CLANG_EXTRACTAPI_SERIALIZATION_SYMBOLGRAPHSERIALIZER_H
 #define LLVM_CLANG_EXTRACTAPI_SERIALIZATION_SYMBOLGRAPHSERIALIZER_H
 
-#include "clang/Basic/Module.h"
 #include "clang/ExtractAPI/API.h"
 #include "clang/ExtractAPI/APIIgnoresList.h"
 #include "clang/ExtractAPI/Serialization/APISetVisitor.h"
diff --git a/clang/include/clang/Serialization/ASTWriter.h 
b/clang/include/clang/Serialization/ASTWriter.h
index 88192e439a3f0..ddd3514b3c2db 100644
--- a/clang/include/clang/Serialization/ASTWriter.h
+++ b/clang/include/clang/Serialization/ASTWriter.h
@@ -18,7 +18,6 @@
 #include "clang/AST/Decl.h"
 #include "clang/AST/Type.h"
 #include "clang/Basic/LLVM.h"
-#include "clang/Basic/Module.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Sema/Sema.h"
 #include "clang/Sema/SemaConsumer.h"
@@ -277,7 +276,8 @@ class ASTWriter : public ASTDeserializationListener,
   std::vector TypeOffsets;
 
   /// The first ID number we can use for our own identifiers.
-  serialization::IdentifierID FirstIdentID = 
serialization::NUM_PREDEF_IDENT_IDS;
+  serialization::IdentifierID FirstIdentID =
+  serialization::NUM_PREDEF_IDENT_IDS;
 
   /// The identifier ID that will be assigned to the next new identifier.
   serialization::IdentifierID NextIdentID = FirstIdentID;
@@ -288,7 +288,8 @@ class ASTWriter : public ASTDeserializationListener,
   /// The ID numbers for identifiers are consecutive (in order of
   /// discovery), starting at 1

[clang] f28085a - Fix the warning in RefCntblBaseVirtualDtorChecker.cpp:61 (#93403)

2024-05-26 Thread via cfe-commits

Author: Ryosuke Niwa
Date: 2024-05-26T10:50:53-07:00
New Revision: f28085aac2b2202f911911a6f6e459a9fd099460

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

LOG: Fix the warning in RefCntblBaseVirtualDtorChecker.cpp:61 (#93403)

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp

Removed: 




diff  --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
index 26879f2f87c8b..9df108e28ecdb 100644
--- 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
+++ 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/RefCntblBaseVirtualDtorChecker.cpp
@@ -58,7 +58,7 @@ class DerefFuncDeleteExprVisitor
   std::optional HasSpecializedDelete(CXXMethodDecl *Decl) {
 if (auto *Body = Decl->getBody())
   return VisitBody(Body);
-if (auto *Tmpl = Decl->getTemplateInstantiationPattern())
+if (Decl->getTemplateInstantiationPattern())
   return std::nullopt; // Indeterminate. There was no concrete instance.
 return false;
   }



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


[clang] Fix the warning in RefCntblBaseVirtualDtorChecker.cpp:61 (PR #93403)

2024-05-26 Thread Ryosuke Niwa via cfe-commits

https://github.com/rniwa closed https://github.com/llvm/llvm-project/pull/93403
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-tools-extra] [libcxx] [lldb] [llvm] Add clang basic module directory (PR #93388)

2024-05-26 Thread Sergei Barannikov via cfe-commits


@@ -11,7 +11,7 @@
 //

s-barannikov wrote:

I guess this file should've been removed.


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


[clang] [clang-tools-extra] [libcxx] [lldb] [llvm] Add clang basic module directory (PR #93388)

2024-05-26 Thread David Stone via cfe-commits

https://github.com/davidstone updated 
https://github.com/llvm/llvm-project/pull/93388

>From f4b9852b0c11a9b5087c5fdb7794b5cab7f4d22c Mon Sep 17 00:00:00 2001
From: David Stone 
Date: Sun, 26 May 2024 10:34:09 -0600
Subject: [PATCH 1/3] [clang][Modules] Remove unnecessary includes of
 `Module.h`

---
 .../clangd/unittests/ReplayPeambleTests.cpp   |  10 +-
 .../include/clang/APINotes/APINotesManager.h  |   5 +-
 .../Serialization/SymbolGraphSerializer.h |   1 -
 clang/include/clang/Serialization/ASTWriter.h |  32 ++---
 .../clang/Serialization/ModuleManager.h   |  14 +-
 clang/lib/APINotes/APINotesManager.cpp|   1 +
 clang/lib/AST/ASTDumper.cpp   |  12 +-
 clang/lib/CodeGen/CodeGenModule.h | 126 --
 clang/lib/ExtractAPI/API.cpp  |   1 -
 .../header_exportable_declarations.cpp|   2 -
 10 files changed, 93 insertions(+), 111 deletions(-)

diff --git a/clang-tools-extra/clangd/unittests/ReplayPeambleTests.cpp 
b/clang-tools-extra/clangd/unittests/ReplayPeambleTests.cpp
index 147d9abe69137..32942e6bbfdc8 100644
--- a/clang-tools-extra/clangd/unittests/ReplayPeambleTests.cpp
+++ b/clang-tools-extra/clangd/unittests/ReplayPeambleTests.cpp
@@ -25,7 +25,6 @@
 #include "clang/AST/DeclTemplate.h"
 #include "clang/Basic/FileEntry.h"
 #include "clang/Basic/LLVM.h"
-#include "clang/Basic/Module.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/TokenKinds.h"
@@ -42,7 +41,11 @@
 #include 
 #include 
 
-namespace clang::clangd {
+namespace clang {
+
+class Module;
+
+namespace clangd {
 namespace {
 struct Inclusion {
   Inclusion(const SourceManager &SM, SourceLocation HashLoc,
@@ -170,4 +173,5 @@ TEST(ReplayPreambleTest, IncludesAndSkippedFiles) {
   }
 }
 } // namespace
-} // namespace clang::clangd
+} // namespace clangd
+} // namespace clang
diff --git a/clang/include/clang/APINotes/APINotesManager.h 
b/clang/include/clang/APINotes/APINotesManager.h
index 18375c9e51a17..40c6328319dbd 100644
--- a/clang/include/clang/APINotes/APINotesManager.h
+++ b/clang/include/clang/APINotes/APINotesManager.h
@@ -9,7 +9,6 @@
 #ifndef LLVM_CLANG_APINOTES_APINOTESMANAGER_H
 #define LLVM_CLANG_APINOTES_APINOTESMANAGER_H
 
-#include "clang/Basic/Module.h"
 #include "clang/Basic/SourceLocation.h"
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/DenseMap.h"
@@ -24,6 +23,7 @@ namespace clang {
 class DirectoryEntry;
 class FileEntry;
 class LangOptions;
+class Module;
 class SourceManager;
 
 namespace api_notes {
@@ -159,7 +159,8 @@ class APINotesManager {
   ArrayRef getCurrentModuleReaders() const {
 bool HasPublic = CurrentModuleReaders[ReaderKind::Public];
 bool HasPrivate = CurrentModuleReaders[ReaderKind::Private];
-assert((!HasPrivate || HasPublic) && "private module requires public 
module");
+assert((!HasPrivate || HasPublic) &&
+   "private module requires public module");
 if (!HasPrivate && !HasPublic)
   return {};
 return ArrayRef(CurrentModuleReaders).slice(0, HasPrivate ? 2 : 1);
diff --git 
a/clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h 
b/clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h
index 27e9167ca1ad0..f8759bf2d8f25 100644
--- a/clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h
+++ b/clang/include/clang/ExtractAPI/Serialization/SymbolGraphSerializer.h
@@ -17,7 +17,6 @@
 #ifndef LLVM_CLANG_EXTRACTAPI_SERIALIZATION_SYMBOLGRAPHSERIALIZER_H
 #define LLVM_CLANG_EXTRACTAPI_SERIALIZATION_SYMBOLGRAPHSERIALIZER_H
 
-#include "clang/Basic/Module.h"
 #include "clang/ExtractAPI/API.h"
 #include "clang/ExtractAPI/APIIgnoresList.h"
 #include "clang/ExtractAPI/Serialization/APISetVisitor.h"
diff --git a/clang/include/clang/Serialization/ASTWriter.h 
b/clang/include/clang/Serialization/ASTWriter.h
index 88192e439a3f0..ddd3514b3c2db 100644
--- a/clang/include/clang/Serialization/ASTWriter.h
+++ b/clang/include/clang/Serialization/ASTWriter.h
@@ -18,7 +18,6 @@
 #include "clang/AST/Decl.h"
 #include "clang/AST/Type.h"
 #include "clang/Basic/LLVM.h"
-#include "clang/Basic/Module.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Sema/Sema.h"
 #include "clang/Sema/SemaConsumer.h"
@@ -277,7 +276,8 @@ class ASTWriter : public ASTDeserializationListener,
   std::vector TypeOffsets;
 
   /// The first ID number we can use for our own identifiers.
-  serialization::IdentifierID FirstIdentID = 
serialization::NUM_PREDEF_IDENT_IDS;
+  serialization::IdentifierID FirstIdentID =
+  serialization::NUM_PREDEF_IDENT_IDS;
 
   /// The identifier ID that will be assigned to the next new identifier.
   serialization::IdentifierID NextIdentID = FirstIdentID;
@@ -288,7 +288,8 @@ class ASTWriter : public ASTDeserializationListener,
   /// The ID numbers for identifiers are consecutive (in order of
   /// discovery), starting at 1. An ID of zero refers to a NULL
   /// IdentifierInfo.
-  llvm::MapVect

[clang] [clang-tools-extra] [libcxx] [lldb] [llvm] Add clang basic module directory (PR #93388)

2024-05-26 Thread David Stone via cfe-commits

https://github.com/davidstone edited 
https://github.com/llvm/llvm-project/pull/93388
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-tools-extra] [libcxx] [lldb] [llvm] Add clang basic module directory (PR #93388)

2024-05-26 Thread David Stone via cfe-commits

davidstone wrote:

> I don't like the PR since I don't feel it makes the code cleaner and it may 
> make the downstream suffering backporting.
> 
> If there are deeper reasons or following patches, we can discuss them 
> seperately.

On its own, I would agree. My goal is to split several more things out of 
`Module.h` but still keep all the module things together. I'm fine letting this 
sit until I get some of those other changes together and we can look over a 
broader set of changes and see if the direction is good.

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


[clang] [clang-tools-extra] [libcxx] [lldb] [llvm] Add clang basic module directory (PR #93388)

2024-05-26 Thread David Stone via cfe-commits

davidstone wrote:

To give a little more detail about my plans as of right now:

* Move `VisibleModuleSet` into its own file
* Move `ASTFileSignature` into its own file
* Take some of the related members of `Module`, group them together into their 
own class, and move the resulting classes into their own headers

That last one is the most vague, because until I actually do some of the work I 
won't really know what the proper divisions are. But even if that last bullet 
ends up being two things split out, the `Module` directory ends up with 6 files 
in it, which is a much more reasonable organizational structure than the 2 
files in this commit.

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


[clang] [llvm] [inline] Clone return range attribute on the callsite into inlined call (PR #92666)

2024-05-26 Thread Andreas Jonson via cfe-commits

andjo403 wrote:

It was the usage of exactIntersectWith in 
https://github.com/llvm/llvm-project/pull/91101 vs the intersectWith that I 
used that I wanted to sort out but think that we have conluded that it shall be 
intersectWith.
so this it ready for review

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


[clang] [llvm] [WebAssembly] Refactor Wasm Reference Types as TargetExtType (PR #93428)

2024-05-26 Thread Lucile Rose Nihlen via cfe-commits

https://github.com/lnihlen converted_to_draft 
https://github.com/llvm/llvm-project/pull/93428
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [WebAssembly] Refactor Wasm Reference Types as TargetExtType (PR #93428)

2024-05-26 Thread Lucile Rose Nihlen via cfe-commits

https://github.com/lnihlen created 
https://github.com/llvm/llvm-project/pull/93428

This is a re-application of #71540, with the hopes I can get some help from 
@pmatos and others to finish it. Right now the 
'../clang/test/CodeGen/WebAssembly/wasm-funcref.c' test fails with an assertion 
trying to cast the target("wasm.funcref") instruction to a pointer. Looking in 
to that further but wanted to checkpoint the code here from the first patch.

>From 2f38d84d921bd3c4fe00ed6bfd360943d8cda15f Mon Sep 17 00:00:00 2001
From: Lucile Nihlen 
Date: Sat, 25 May 2024 18:55:09 +
Subject: [PATCH 1/2] Apply patch from #71540

---
 .../test/CodeGen/WebAssembly/builtins-table.c | 16 ++--
 .../test/CodeGen/WebAssembly/wasm-externref.c |  9 +-
 clang/test/CodeGen/builtins-wasm.c|  2 +-
 llvm/include/llvm/IR/Intrinsics.h |  2 +
 llvm/include/llvm/IR/IntrinsicsWebAssembly.td |  7 ++
 llvm/lib/CodeGen/ValueTypes.cpp   |  4 +
 llvm/lib/IR/Function.cpp  | 14 ++-
 llvm/lib/IR/Type.cpp  | 10 ++-
 llvm/lib/Target/WebAssembly/CMakeLists.txt|  1 -
 .../WebAssembly/Utils/WasmAddressSpaces.h |  4 -
 .../Utils/WebAssemblyTypeUtilities.h  | 10 +--
 llvm/lib/Target/WebAssembly/WebAssembly.h |  2 -
 .../lib/Target/WebAssembly/WebAssemblyISD.def |  3 +
 .../WebAssembly/WebAssemblyISelLowering.cpp   | 22 +
 .../WebAssembly/WebAssemblyISelLowering.h |  3 -
 .../Target/WebAssembly/WebAssemblyInstrRef.td |  8 ++
 .../WebAssemblyLowerRefTypesIntPtrConv.cpp| 86 ---
 .../WebAssembly/WebAssemblyTargetMachine.cpp  |  2 -
 .../WebAssembly/externref-globalget.ll|  2 +-
 .../WebAssembly/externref-globalset.ll|  2 +-
 .../CodeGen/WebAssembly/externref-inttoptr.ll | 12 +--
 .../CodeGen/WebAssembly/externref-ptrtoint.ll |  2 +-
 .../CodeGen/WebAssembly/externref-tableget.ll |  2 +-
 .../CodeGen/WebAssembly/externref-tableset.ll |  2 +-
 .../WebAssembly/externref-unsized-load.ll |  4 +-
 .../WebAssembly/externref-unsized-store.ll|  4 +-
 llvm/test/CodeGen/WebAssembly/funcref-call.ll | 10 ++-
 .../CodeGen/WebAssembly/funcref-globalget.ll  |  2 +-
 .../CodeGen/WebAssembly/funcref-globalset.ll  |  2 +-
 .../CodeGen/WebAssembly/funcref-table_call.ll |  2 +-
 .../CodeGen/WebAssembly/funcref-tableget.ll   |  2 +-
 .../CodeGen/WebAssembly/funcref-tableset.ll   |  2 +-
 llvm/test/CodeGen/WebAssembly/ref-null.ll |  4 +-
 llvm/test/CodeGen/WebAssembly/table-copy.ll   |  2 +-
 llvm/test/CodeGen/WebAssembly/table-fill.ll   |  2 +-
 llvm/test/CodeGen/WebAssembly/table-grow.ll   |  2 +-
 llvm/test/CodeGen/WebAssembly/table-size.ll   |  2 +-
 llvm/test/CodeGen/WebAssembly/table-types.ll  |  4 +-
 .../llvm/lib/Target/WebAssembly/BUILD.gn  |  1 -
 39 files changed, 93 insertions(+), 179 deletions(-)
 delete mode 100644 
llvm/lib/Target/WebAssembly/WebAssemblyLowerRefTypesIntPtrConv.cpp

diff --git a/clang/test/CodeGen/WebAssembly/builtins-table.c 
b/clang/test/CodeGen/WebAssembly/builtins-table.c
index 74bb2442fe552..eeed335855e40 100644
--- a/clang/test/CodeGen/WebAssembly/builtins-table.c
+++ b/clang/test/CodeGen/WebAssembly/builtins-table.c
@@ -7,17 +7,17 @@ static __externref_t table[0];
 // CHECK-LABEL: define {{[^@]+}}@test_builtin_wasm_table_get
 // CHECK-SAME: (i32 noundef [[INDEX:%.*]]) #[[ATTR0:[0-9]+]] {
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = call ptr addrspace(10) 
@llvm.wasm.table.get.externref(ptr addrspace(1) @table, i32 [[INDEX]])
-// CHECK-NEXT:ret ptr addrspace(10) [[TMP0]]
+// CHECK-NEXT:[[TMP0:%.*]] = call target("wasm.externref") 
@llvm.wasm.table.get.externref(ptr addrspace(1) @table, i32 [[INDEX]])
+// CHECK-NEXT:ret target("wasm.externref") [[TMP0]]
 //
 __externref_t test_builtin_wasm_table_get(int index) {
   return __builtin_wasm_table_get(table, index);
 }
 
 // CHECK-LABEL: define {{[^@]+}}@test_builtin_wasm_table_set
-// CHECK-SAME: (i32 noundef [[INDEX:%.*]], ptr addrspace(10) [[REF:%.*]]) 
#[[ATTR0]] {
+// CHECK-SAME: (i32 noundef [[INDEX:%.*]], target("wasm.externref") 
[[REF:%.*]]) #[[ATTR0]] {
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:call void @llvm.wasm.table.set.externref(ptr addrspace(1) 
@table, i32 [[INDEX]], ptr addrspace(10) [[REF]])
+// CHECK-NEXT:call void @llvm.wasm.table.set.externref(ptr addrspace(1) 
@table, i32 [[INDEX]], target("wasm.externref") [[REF]])
 // CHECK-NEXT:ret void
 //
 void test_builtin_wasm_table_set(int index, __externref_t ref) {
@@ -35,9 +35,9 @@ int test_builtin_wasm_table_size() {
 }
 
 // CHECK-LABEL: define {{[^@]+}}@test_builtin_wasm_table_grow
-// CHECK-SAME: (ptr addrspace(10) [[REF:%.*]], i32 noundef [[NELEM:%.*]]) 
#[[ATTR0]] {
+// CHECK-SAME: (target("wasm.externref") [[REF:%.*]], i32 noundef 
[[NELEM:%.*]]) #[[ATTR0]] {
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = call i32 @llvm.wasm.table.grow.externref(ptr 
addrspace(1) @table, ptr addrspace(10) [[REF]], i32 [[NELEM]])
+// CHE

[clang] [llvm] [WebAssembly] Refactor Wasm Reference Types as TargetExtType (PR #93428)

2024-05-26 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-backend-webassembly

Author: Lucile Rose Nihlen (lnihlen)


Changes

This is a re-application of #71540, with the hopes I can get some help 
from @pmatos and others to finish it. Right now the 
'../clang/test/CodeGen/WebAssembly/wasm-funcref.c' test fails with an assertion 
trying to cast the target("wasm.funcref") instruction to a pointer. Looking in 
to that further but wanted to checkpoint the code here from the first patch.

---

Patch is 40.56 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/93428.diff


40 Files Affected:

- (modified) clang/test/CodeGen/WebAssembly/builtins-table.c (+8-8) 
- (modified) clang/test/CodeGen/WebAssembly/wasm-externref.c (+5-4) 
- (modified) clang/test/CodeGen/WebAssembly/wasm-funcref.c (+20-20) 
- (modified) clang/test/CodeGen/builtins-wasm.c (+1-1) 
- (modified) llvm/include/llvm/IR/Intrinsics.h (+2) 
- (modified) llvm/include/llvm/IR/IntrinsicsWebAssembly.td (+7) 
- (modified) llvm/lib/CodeGen/ValueTypes.cpp (+4) 
- (modified) llvm/lib/IR/Function.cpp (+12-2) 
- (modified) llvm/lib/IR/Type.cpp (+6-4) 
- (modified) llvm/lib/Target/WebAssembly/CMakeLists.txt (-1) 
- (modified) llvm/lib/Target/WebAssembly/Utils/WasmAddressSpaces.h (-4) 
- (modified) llvm/lib/Target/WebAssembly/Utils/WebAssemblyTypeUtilities.h 
(+4-6) 
- (modified) llvm/lib/Target/WebAssembly/WebAssembly.h (-2) 
- (modified) llvm/lib/Target/WebAssembly/WebAssemblyISD.def (+3) 
- (modified) llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp (+1-21) 
- (modified) llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.h (-3) 
- (modified) llvm/lib/Target/WebAssembly/WebAssemblyInstrRef.td (+8) 
- (removed) llvm/lib/Target/WebAssembly/WebAssemblyLowerRefTypesIntPtrConv.cpp 
(-86) 
- (modified) llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp (-2) 
- (modified) llvm/test/CodeGen/WebAssembly/externref-globalget.ll (+1-1) 
- (modified) llvm/test/CodeGen/WebAssembly/externref-globalset.ll (+1-1) 
- (modified) llvm/test/CodeGen/WebAssembly/externref-inttoptr.ll (+3-9) 
- (modified) llvm/test/CodeGen/WebAssembly/externref-ptrtoint.ll (+1-1) 
- (modified) llvm/test/CodeGen/WebAssembly/externref-tableget.ll (+1-1) 
- (modified) llvm/test/CodeGen/WebAssembly/externref-tableset.ll (+1-1) 
- (modified) llvm/test/CodeGen/WebAssembly/externref-unsized-load.ll (+2-2) 
- (modified) llvm/test/CodeGen/WebAssembly/externref-unsized-store.ll (+2-2) 
- (modified) llvm/test/CodeGen/WebAssembly/funcref-call.ll (+7-3) 
- (modified) llvm/test/CodeGen/WebAssembly/funcref-globalget.ll (+1-1) 
- (modified) llvm/test/CodeGen/WebAssembly/funcref-globalset.ll (+1-1) 
- (modified) llvm/test/CodeGen/WebAssembly/funcref-table_call.ll (+1-1) 
- (modified) llvm/test/CodeGen/WebAssembly/funcref-tableget.ll (+1-1) 
- (modified) llvm/test/CodeGen/WebAssembly/funcref-tableset.ll (+1-1) 
- (modified) llvm/test/CodeGen/WebAssembly/ref-null.ll (+2-2) 
- (modified) llvm/test/CodeGen/WebAssembly/table-copy.ll (+1-1) 
- (modified) llvm/test/CodeGen/WebAssembly/table-fill.ll (+1-1) 
- (modified) llvm/test/CodeGen/WebAssembly/table-grow.ll (+1-1) 
- (modified) llvm/test/CodeGen/WebAssembly/table-size.ll (+1-1) 
- (modified) llvm/test/CodeGen/WebAssembly/table-types.ll (+2-2) 
- (modified) llvm/utils/gn/secondary/llvm/lib/Target/WebAssembly/BUILD.gn (-1) 


``diff
diff --git a/clang/test/CodeGen/WebAssembly/builtins-table.c 
b/clang/test/CodeGen/WebAssembly/builtins-table.c
index 74bb2442fe552..eeed335855e40 100644
--- a/clang/test/CodeGen/WebAssembly/builtins-table.c
+++ b/clang/test/CodeGen/WebAssembly/builtins-table.c
@@ -7,17 +7,17 @@ static __externref_t table[0];
 // CHECK-LABEL: define {{[^@]+}}@test_builtin_wasm_table_get
 // CHECK-SAME: (i32 noundef [[INDEX:%.*]]) #[[ATTR0:[0-9]+]] {
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = call ptr addrspace(10) 
@llvm.wasm.table.get.externref(ptr addrspace(1) @table, i32 [[INDEX]])
-// CHECK-NEXT:ret ptr addrspace(10) [[TMP0]]
+// CHECK-NEXT:[[TMP0:%.*]] = call target("wasm.externref") 
@llvm.wasm.table.get.externref(ptr addrspace(1) @table, i32 [[INDEX]])
+// CHECK-NEXT:ret target("wasm.externref") [[TMP0]]
 //
 __externref_t test_builtin_wasm_table_get(int index) {
   return __builtin_wasm_table_get(table, index);
 }
 
 // CHECK-LABEL: define {{[^@]+}}@test_builtin_wasm_table_set
-// CHECK-SAME: (i32 noundef [[INDEX:%.*]], ptr addrspace(10) [[REF:%.*]]) 
#[[ATTR0]] {
+// CHECK-SAME: (i32 noundef [[INDEX:%.*]], target("wasm.externref") 
[[REF:%.*]]) #[[ATTR0]] {
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:call void @llvm.wasm.table.set.externref(ptr addrspace(1) 
@table, i32 [[INDEX]], ptr addrspace(10) [[REF]])
+// CHECK-NEXT:call void @llvm.wasm.table.set.externref(ptr addrspace(1) 
@table, i32 [[INDEX]], target("wasm.externref") [[REF]])
 // CHECK-NEXT:ret void
 //
 void test_builtin_wasm_table_set(int index, __externref_t ref) {
@@ -35,9 +35,9 @@ int test_builtin_wasm_tab

[clang] [llvm] [WebAssembly] Refactor Wasm Reference Types as TargetExtType (PR #93428)

2024-05-26 Thread Lucile Rose Nihlen via cfe-commits

https://github.com/lnihlen updated 
https://github.com/llvm/llvm-project/pull/93428

>From fc5e70b0f4e3182487ddb52b0b675b798dff62ba Mon Sep 17 00:00:00 2001
From: Lucile Nihlen 
Date: Sat, 25 May 2024 18:55:09 +
Subject: [PATCH 1/2] Apply patch from #71540

---
 .../test/CodeGen/WebAssembly/builtins-table.c | 16 ++--
 .../test/CodeGen/WebAssembly/wasm-externref.c |  9 +-
 clang/test/CodeGen/builtins-wasm.c|  2 +-
 llvm/include/llvm/IR/Intrinsics.h |  2 +
 llvm/include/llvm/IR/IntrinsicsWebAssembly.td |  7 ++
 llvm/lib/CodeGen/ValueTypes.cpp   |  4 +
 llvm/lib/IR/Function.cpp  | 14 ++-
 llvm/lib/IR/Type.cpp  | 10 ++-
 llvm/lib/Target/WebAssembly/CMakeLists.txt|  1 -
 .../WebAssembly/Utils/WasmAddressSpaces.h |  4 -
 .../Utils/WebAssemblyTypeUtilities.h  | 10 +--
 llvm/lib/Target/WebAssembly/WebAssembly.h |  2 -
 .../lib/Target/WebAssembly/WebAssemblyISD.def |  3 +
 .../WebAssembly/WebAssemblyISelLowering.cpp   | 22 +
 .../WebAssembly/WebAssemblyISelLowering.h |  3 -
 .../Target/WebAssembly/WebAssemblyInstrRef.td |  8 ++
 .../WebAssemblyLowerRefTypesIntPtrConv.cpp| 86 ---
 .../WebAssembly/WebAssemblyTargetMachine.cpp  |  2 -
 .../WebAssembly/externref-globalget.ll|  2 +-
 .../WebAssembly/externref-globalset.ll|  2 +-
 .../CodeGen/WebAssembly/externref-inttoptr.ll | 12 +--
 .../CodeGen/WebAssembly/externref-ptrtoint.ll |  2 +-
 .../CodeGen/WebAssembly/externref-tableget.ll |  2 +-
 .../CodeGen/WebAssembly/externref-tableset.ll |  2 +-
 .../WebAssembly/externref-unsized-load.ll |  4 +-
 .../WebAssembly/externref-unsized-store.ll|  4 +-
 llvm/test/CodeGen/WebAssembly/funcref-call.ll | 10 ++-
 .../CodeGen/WebAssembly/funcref-globalget.ll  |  2 +-
 .../CodeGen/WebAssembly/funcref-globalset.ll  |  2 +-
 .../CodeGen/WebAssembly/funcref-table_call.ll |  2 +-
 .../CodeGen/WebAssembly/funcref-tableget.ll   |  2 +-
 .../CodeGen/WebAssembly/funcref-tableset.ll   |  2 +-
 llvm/test/CodeGen/WebAssembly/ref-null.ll |  4 +-
 llvm/test/CodeGen/WebAssembly/table-copy.ll   |  2 +-
 llvm/test/CodeGen/WebAssembly/table-fill.ll   |  2 +-
 llvm/test/CodeGen/WebAssembly/table-grow.ll   |  2 +-
 llvm/test/CodeGen/WebAssembly/table-size.ll   |  2 +-
 llvm/test/CodeGen/WebAssembly/table-types.ll  |  4 +-
 .../llvm/lib/Target/WebAssembly/BUILD.gn  |  1 -
 39 files changed, 93 insertions(+), 179 deletions(-)
 delete mode 100644 
llvm/lib/Target/WebAssembly/WebAssemblyLowerRefTypesIntPtrConv.cpp

diff --git a/clang/test/CodeGen/WebAssembly/builtins-table.c 
b/clang/test/CodeGen/WebAssembly/builtins-table.c
index 74bb2442fe552..eeed335855e40 100644
--- a/clang/test/CodeGen/WebAssembly/builtins-table.c
+++ b/clang/test/CodeGen/WebAssembly/builtins-table.c
@@ -7,17 +7,17 @@ static __externref_t table[0];
 // CHECK-LABEL: define {{[^@]+}}@test_builtin_wasm_table_get
 // CHECK-SAME: (i32 noundef [[INDEX:%.*]]) #[[ATTR0:[0-9]+]] {
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = call ptr addrspace(10) 
@llvm.wasm.table.get.externref(ptr addrspace(1) @table, i32 [[INDEX]])
-// CHECK-NEXT:ret ptr addrspace(10) [[TMP0]]
+// CHECK-NEXT:[[TMP0:%.*]] = call target("wasm.externref") 
@llvm.wasm.table.get.externref(ptr addrspace(1) @table, i32 [[INDEX]])
+// CHECK-NEXT:ret target("wasm.externref") [[TMP0]]
 //
 __externref_t test_builtin_wasm_table_get(int index) {
   return __builtin_wasm_table_get(table, index);
 }
 
 // CHECK-LABEL: define {{[^@]+}}@test_builtin_wasm_table_set
-// CHECK-SAME: (i32 noundef [[INDEX:%.*]], ptr addrspace(10) [[REF:%.*]]) 
#[[ATTR0]] {
+// CHECK-SAME: (i32 noundef [[INDEX:%.*]], target("wasm.externref") 
[[REF:%.*]]) #[[ATTR0]] {
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:call void @llvm.wasm.table.set.externref(ptr addrspace(1) 
@table, i32 [[INDEX]], ptr addrspace(10) [[REF]])
+// CHECK-NEXT:call void @llvm.wasm.table.set.externref(ptr addrspace(1) 
@table, i32 [[INDEX]], target("wasm.externref") [[REF]])
 // CHECK-NEXT:ret void
 //
 void test_builtin_wasm_table_set(int index, __externref_t ref) {
@@ -35,9 +35,9 @@ int test_builtin_wasm_table_size() {
 }
 
 // CHECK-LABEL: define {{[^@]+}}@test_builtin_wasm_table_grow
-// CHECK-SAME: (ptr addrspace(10) [[REF:%.*]], i32 noundef [[NELEM:%.*]]) 
#[[ATTR0]] {
+// CHECK-SAME: (target("wasm.externref") [[REF:%.*]], i32 noundef 
[[NELEM:%.*]]) #[[ATTR0]] {
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = call i32 @llvm.wasm.table.grow.externref(ptr 
addrspace(1) @table, ptr addrspace(10) [[REF]], i32 [[NELEM]])
+// CHECK-NEXT:[[TMP0:%.*]] = call i32 @llvm.wasm.table.grow.externref(ptr 
addrspace(1) @table, target("wasm.externref") [[REF]], i32 [[NELEM]])
 // CHECK-NEXT:ret i32 [[TMP0]]
 //
 int test_builtin_wasm_table_grow(__externref_t ref, int nelem) {
@@ -45,9 +45,9 @@ int test_builtin_wasm_table_grow(__externref_t ref, int 
nelem) {
 }
 
 // CHECK-LABEL: define {{

[clang] [llvm] [WebAssembly] Refactor Wasm Reference Types as TargetExtType (PR #93428)

2024-05-26 Thread via cfe-commits

github-actions[bot] wrote:




:warning: C/C++ code formatter, clang-format found issues in your code. 
:warning:



You can test this locally with the following command:


``bash
git-clang-format --diff faef8b4aa245a671e2013319e8073a9fc52ae12e 
e79363aed798ce22f408fea3c283bb7d6387535a -- 
clang/test/CodeGen/WebAssembly/builtins-table.c 
clang/test/CodeGen/WebAssembly/wasm-externref.c 
clang/test/CodeGen/WebAssembly/wasm-funcref.c 
clang/test/CodeGen/builtins-wasm.c llvm/include/llvm/IR/Intrinsics.h 
llvm/lib/CodeGen/ValueTypes.cpp llvm/lib/IR/Function.cpp llvm/lib/IR/Type.cpp 
llvm/lib/Target/WebAssembly/Utils/WasmAddressSpaces.h 
llvm/lib/Target/WebAssembly/Utils/WebAssemblyTypeUtilities.h 
llvm/lib/Target/WebAssembly/WebAssembly.h 
llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp 
llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.h 
llvm/lib/Target/WebAssembly/WebAssemblyTargetMachine.cpp
``





View the diff from clang-format here.


``diff
diff --git a/llvm/lib/IR/Function.cpp b/llvm/lib/IR/Function.cpp
index 40964c7a33..718b0e55a2 100644
--- a/llvm/lib/IR/Function.cpp
+++ b/llvm/lib/IR/Function.cpp
@@ -1556,10 +1556,10 @@ static bool matchIntrinsicType(
  cast(Ty)->getName() != "aarch64.svcount";
 case IITDescriptor::WasmExternref:
   return !isa(Ty) ||
-cast(Ty)->getName() != "wasm.externref";
+ cast(Ty)->getName() != "wasm.externref";
 case IITDescriptor::WasmFuncref:
   return !isa(Ty) ||
-cast(Ty)->getName() != "wasm.funcref";
+ cast(Ty)->getName() != "wasm.funcref";
 case IITDescriptor::Vector: {
   VectorType *VT = dyn_cast(Ty);
   return !VT || VT->getElementCount() != D.Vector_Width ||
diff --git a/llvm/lib/IR/Type.cpp b/llvm/lib/IR/Type.cpp
index 3fdc4310a8..edffd04a01 100644
--- a/llvm/lib/IR/Type.cpp
+++ b/llvm/lib/IR/Type.cpp
@@ -845,7 +845,8 @@ static TargetTypeInfo getTargetTypeInfo(const TargetExtType 
*Ty) {
 
   // Opaque types in the WebAssembly name space.
   if (Name.starts_with("wasm."))
-return TargetTypeInfo(PointerType::getUnqual(C), 
TargetExtType::HasZeroInit, TargetExtType::CanBeGlobal);
+return TargetTypeInfo(PointerType::getUnqual(C), 
TargetExtType::HasZeroInit,
+  TargetExtType::CanBeGlobal);
 
   return TargetTypeInfo(Type::getVoidTy(C));
 }
diff --git a/llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp 
b/llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp
index b640467cbc..668942c0b9 100644
--- a/llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp
+++ b/llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp
@@ -1243,8 +1243,7 @@ WebAssemblyTargetLowering::LowerCall(CallLoweringInfo 
&CLI,
 SDValue TableSetOps[] = {Chain, Sym, TableSlot, Callee};
 SDValue TableSet = DAG.getMemIntrinsicNode(
 WebAssemblyISD::TABLE_SET, DL, DAG.getVTList(MVT::Other), TableSetOps,
-MVT::funcref,
-MachinePointerInfo(),
+MVT::funcref, MachinePointerInfo(),
 CLI.CB->getCalledOperand()->getPointerAlignment(DAG.getDataLayout()),
 MachineMemOperand::MOStore);
 

``




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


[clang] [Clang] Static and explicit object member functions with the same parameter-type-lists (PR #93430)

2024-05-26 Thread via cfe-commits

https://github.com/cor3ntin created 
https://github.com/llvm/llvm-project/pull/93430

Implement wg21.link/P2797.

Because taking the address of an explicit object member function results in a 
function pointer, a call expression where the id-expression is an explicit 
object member is made to behave consistently with that model.

This change forces clang to perform overload resolution in the presence of an 
id-expression of the form `(&Foo::bar)(args...)`, which we previously failed to 
do consistently.

>From 131f515c1341122896ea3c9624751a634db06cb7 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Mon, 27 May 2024 01:16:06 +0200
Subject: [PATCH] [Clang] Static and explicit object member functions with the
 same parameter-type-lists

Implement wg21.link/P2797.

Because taking the address of an explicit object member function
results in a function pointer, a call expression where
the id-expression is an explicit object member is made to behave
consistently with that model.

This change forces clang to perform overload resolution
in the presence of an ixpression of the form `(&Foo::bar)(args...)`,
which we previously failed to do consistently.
---
 clang/docs/ReleaseNotes.rst   |  3 +
 clang/include/clang/AST/ExprCXX.h |  4 +
 clang/include/clang/Sema/Overload.h   |  4 +
 clang/lib/Sema/SemaExpr.cpp   | 27 ++-
 clang/lib/Sema/SemaOverload.cpp   | 74 ---
 clang/test/CXX/drs/cwg1xx.cpp |  8 +-
 clang/test/CXX/drs/cwg26xx.cpp| 26 +++
 clang/test/CXX/drs/cwg2771.cpp| 18 +
 clang/test/CodeGenCXX/cxx2b-deducing-this.cpp | 20 +
 clang/test/SemaCXX/cxx2b-deducing-this.cpp| 27 +++
 clang/www/cxx_dr_status.html  |  6 +-
 clang/www/cxx_status.html |  2 +-
 12 files changed, 197 insertions(+), 22 deletions(-)
 create mode 100644 clang/test/CXX/drs/cwg2771.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 825e91876ffce..0a945a9989b0d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -209,6 +209,9 @@ C++23 Feature Support
 - Added a ``__reference_converts_from_temporary`` builtin, completing the 
necessary compiler support for
   `P2255R2: Type trait to determine if a reference binds to a temporary 
`_.
 
+- Implemented `P2797R0: Static and explicit object member functions with the 
same parameter-type-lists `.
+  This completes the support for "deducing this".
+
 C++2c Feature Support
 ^
 
diff --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index dbf693611a7fa..557e9fd99c293 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -3027,6 +3027,7 @@ class OverloadExpr : public Expr {
   struct FindResult {
 OverloadExpr *Expression;
 bool IsAddressOfOperand;
+bool IsAddressOfOperandWithParen;
 bool HasFormOfMemberPointer;
   };
 
@@ -3039,6 +3040,7 @@ class OverloadExpr : public Expr {
 assert(E->getType()->isSpecificBuiltinType(BuiltinType::Overload));
 
 FindResult Result;
+bool HasParen = isa(E);
 
 E = E->IgnoreParens();
 if (isa(E)) {
@@ -3048,10 +3050,12 @@ class OverloadExpr : public Expr {
 
   Result.HasFormOfMemberPointer = (E == Ovl && Ovl->getQualifier());
   Result.IsAddressOfOperand = true;
+  Result.IsAddressOfOperandWithParen = HasParen;
   Result.Expression = Ovl;
 } else {
   Result.HasFormOfMemberPointer = false;
   Result.IsAddressOfOperand = false;
+  Result.IsAddressOfOperandWithParen = false;
   Result.Expression = cast(E);
 }
 
diff --git a/clang/include/clang/Sema/Overload.h 
b/clang/include/clang/Sema/Overload.h
index 76311b00d2fc5..64cdd6cdf043d 100644
--- a/clang/include/clang/Sema/Overload.h
+++ b/clang/include/clang/Sema/Overload.h
@@ -899,6 +899,8 @@ class Sema;
 /// object argument.
 bool IgnoreObjectArgument : 1;
 
+bool TookAddressOfOverload : 1;
+
 /// True if the candidate was found using ADL.
 CallExpr::ADLCallKind IsADLCandidate : 1;
 
@@ -999,6 +1001,8 @@ class Sema;
   /// Initialization of an object of class type by constructor,
   /// using either a parenthesized or braced list of arguments.
   CSK_InitByConstructor,
+
+  CSK_AddressOfOverloadSet,
 };
 
 /// Information about operator rewrites to consider when adding operator
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 410f80ae864a1..15496f3323b02 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -5813,6 +5813,24 @@ static TypoCorrection TryTypoCorrectionForCall(Sema &S, 
Expr *Fn,
   return TypoCorrection();
 }
 
+static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn) {
+  if (!isa(Fn))
+return false;
+
+  Fn = Fn->IgnoreParens();
+  auto *UO = dyn_cast(F

[clang] [Clang] Static and explicit object member functions with the same parameter-type-lists (PR #93430)

2024-05-26 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: cor3ntin (cor3ntin)


Changes

Implement wg21.link/P2797.

Because taking the address of an explicit object member function results in a 
function pointer, a call expression where the id-expression is an explicit 
object member is made to behave consistently with that model.

This change forces clang to perform overload resolution in the presence of an 
id-expression of the form `(&Foo::bar)(args...)`, which we previously 
failed to do consistently.

---

Patch is 20.88 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/93430.diff


12 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+3) 
- (modified) clang/include/clang/AST/ExprCXX.h (+4) 
- (modified) clang/include/clang/Sema/Overload.h (+4) 
- (modified) clang/lib/Sema/SemaExpr.cpp (+24-3) 
- (modified) clang/lib/Sema/SemaOverload.cpp (+64-10) 
- (modified) clang/test/CXX/drs/cwg1xx.cpp (+3-5) 
- (modified) clang/test/CXX/drs/cwg26xx.cpp (+26) 
- (added) clang/test/CXX/drs/cwg2771.cpp (+18) 
- (modified) clang/test/CodeGenCXX/cxx2b-deducing-this.cpp (+20) 
- (modified) clang/test/SemaCXX/cxx2b-deducing-this.cpp (+27) 
- (modified) clang/www/cxx_dr_status.html (+3-3) 
- (modified) clang/www/cxx_status.html (+1-1) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 825e91876ffce..0a945a9989b0d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -209,6 +209,9 @@ C++23 Feature Support
 - Added a ``__reference_converts_from_temporary`` builtin, completing the 
necessary compiler support for
   `P2255R2: Type trait to determine if a reference binds to a temporary 
`_.
 
+- Implemented `P2797R0: Static and explicit object member functions with the 
same parameter-type-lists `.
+  This completes the support for "deducing this".
+
 C++2c Feature Support
 ^
 
diff --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index dbf693611a7fa..557e9fd99c293 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -3027,6 +3027,7 @@ class OverloadExpr : public Expr {
   struct FindResult {
 OverloadExpr *Expression;
 bool IsAddressOfOperand;
+bool IsAddressOfOperandWithParen;
 bool HasFormOfMemberPointer;
   };
 
@@ -3039,6 +3040,7 @@ class OverloadExpr : public Expr {
 assert(E->getType()->isSpecificBuiltinType(BuiltinType::Overload));
 
 FindResult Result;
+bool HasParen = isa(E);
 
 E = E->IgnoreParens();
 if (isa(E)) {
@@ -3048,10 +3050,12 @@ class OverloadExpr : public Expr {
 
   Result.HasFormOfMemberPointer = (E == Ovl && Ovl->getQualifier());
   Result.IsAddressOfOperand = true;
+  Result.IsAddressOfOperandWithParen = HasParen;
   Result.Expression = Ovl;
 } else {
   Result.HasFormOfMemberPointer = false;
   Result.IsAddressOfOperand = false;
+  Result.IsAddressOfOperandWithParen = false;
   Result.Expression = cast(E);
 }
 
diff --git a/clang/include/clang/Sema/Overload.h 
b/clang/include/clang/Sema/Overload.h
index 76311b00d2fc5..64cdd6cdf043d 100644
--- a/clang/include/clang/Sema/Overload.h
+++ b/clang/include/clang/Sema/Overload.h
@@ -899,6 +899,8 @@ class Sema;
 /// object argument.
 bool IgnoreObjectArgument : 1;
 
+bool TookAddressOfOverload : 1;
+
 /// True if the candidate was found using ADL.
 CallExpr::ADLCallKind IsADLCandidate : 1;
 
@@ -999,6 +1001,8 @@ class Sema;
   /// Initialization of an object of class type by constructor,
   /// using either a parenthesized or braced list of arguments.
   CSK_InitByConstructor,
+
+  CSK_AddressOfOverloadSet,
 };
 
 /// Information about operator rewrites to consider when adding operator
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 410f80ae864a1..15496f3323b02 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -5813,6 +5813,24 @@ static TypoCorrection TryTypoCorrectionForCall(Sema &S, 
Expr *Fn,
   return TypoCorrection();
 }
 
+static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn) {
+  if (!isa(Fn))
+return false;
+
+  Fn = Fn->IgnoreParens();
+  auto *UO = dyn_cast(Fn);
+  if (!UO)
+return false;
+  assert(cast(Fn)->getOpcode() == UO_AddrOf);
+  if (auto *DRE = dyn_cast(UO->getSubExpr()->IgnoreParens())) {
+return DRE->hasQualifier();
+  }
+  if (auto *OVL = dyn_cast(UO->getSubExpr()->IgnoreParens())) {
+return OVL->getQualifier();
+  }
+  return false;
+}
+
 /// ConvertArgumentsForCall - Converts the arguments specified in
 /// Args/NumArgs to the parameter types of the function FDecl with
 /// function prototype Proto. Call is the call expression itself, and
@@ -5834,9 +5852,12 @@ Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
 
   // C99 6.5.2.2p7 - the arguments are implicitly converted, as

[clang] [llvm] [WebAssembly] Refactor Wasm Reference Types as TargetExtType (PR #93428)

2024-05-26 Thread Paulo Matos via cfe-commits

pmatos wrote:

> This is a re-application of #71540, with the hopes I can get some help from 
> @pmatos and others to finish it. Right now the 
> '../clang/test/CodeGen/WebAssembly/wasm-funcref.c' test fails with an 
> assertion trying to cast the target("wasm.funcref") instruction to a pointer. 
> Looking in to that further but wanted to checkpoint the code here from the 
> first patch.

I will keep this bug in mind but I am taking a leave at the moment until June 
3rd. I will take a look at it then.

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


[clang] [Clang] Resolve FIXME: Use class method when receiver is reference to class (PR #85316)

2024-05-26 Thread via cfe-commits

https://github.com/AtariDreams converted_to_draft 
https://github.com/llvm/llvm-project/pull/85316
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Improve ast-dumper text printing of TemplateArgument (PR #93431)

2024-05-26 Thread Matheus Izvekov via cfe-commits

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

This improves and unifies our approach to printing all template arguments.

The same approach to printing types is extended to all TemplateArguments: A 
sugared version is printed in quotes, followed by printing the canonical form, 
unless they would print the same.

Special improvements are done to add more detail to template template arguments.

It's planned in a future patch to use this improved TemplateName printer for 
other places besides TemplateArguments.

Note: The sugared/desugared printing does not show up for TemplateNames in 
tests yet, because we do a poor job of preserving their type sugar. This will 
be improved in a future patch.

>From 51ca62950c19648895f1947bbf981408193d9002 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Fri, 24 May 2024 12:22:55 -0300
Subject: [PATCH] [clang] Improve ast-dumper text printing of TemplateArgument

This improves and unifies our approach to printing all template
arguments.

The same approach to printing types is extended to all
TemplateArguments: A sugared version is printed in quotes,
followed by printing the canonical form, unless they would print
the same.

Special improvements are done to add more detail to template template
arguments.

It's planned in a future patch to use this improved TemplateName
printer for other places besides TemplateArguments.

Note: The sugared/desugared printing does not show up for
TemplateNames in tests yet, because we do a poor job of preserving
their type sugar. This will be improved in a future patch.
---
 clang/docs/ReleaseNotes.rst   |  5 +
 clang/include/clang/AST/TextNodeDumper.h  |  3 +
 clang/lib/AST/TextNodeDumper.cpp  | 94 ---
 clang/test/AST/ast-dump-decl.cpp  | 25 ++---
 ...penmp-begin-declare-variant_template_2.cpp |  6 +-
 clang/test/AST/ast-dump-template-name.cpp | 54 +++
 clang/test/AST/ast-dump-using-template.cpp|  8 +-
 .../constraints-explicit-instantiation.cpp|  6 +-
 clang/test/OpenMP/align_clause_ast_print.cpp  |  2 +-
 clang/test/OpenMP/generic_loop_ast_print.cpp  |  2 +-
 clang/test/OpenMP/interop_ast_print.cpp   |  2 +-
 clang/test/SemaOpenACC/sub-array-ast.cpp  |  2 +-
 .../aggregate-deduction-candidate.cpp | 16 ++--
 clang/test/SemaTemplate/attributes.cpp| 64 ++---
 clang/test/SemaTemplate/deduction-guide.cpp   | 14 +--
 clang/test/SemaTemplate/make_integer_seq.cpp  | 68 --
 clang/test/SemaTemplate/type_pack_element.cpp | 20 ++--
 17 files changed, 266 insertions(+), 125 deletions(-)
 create mode 100644 clang/test/AST/ast-dump-template-name.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 825e91876ffce..403a107edef17 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -818,6 +818,11 @@ Miscellaneous Clang Crashes Fixed
   when ``-fdump-record-layouts-complete`` is passed. Fixes #GH83684.
 - Unhandled StructuralValues in the template differ (#GH93068).
 
+Miscellaneous Clang Improvements
+^
+
+- The text ast-dumper has improved printing of TemplateArguments.
+
 OpenACC Specific Changes
 
 
diff --git a/clang/include/clang/AST/TextNodeDumper.h 
b/clang/include/clang/AST/TextNodeDumper.h
index 1fede6e462e92..0d057b8011164 100644
--- a/clang/include/clang/AST/TextNodeDumper.h
+++ b/clang/include/clang/AST/TextNodeDumper.h
@@ -211,8 +211,11 @@ class TextNodeDumper
   void dumpAccessSpecifier(AccessSpecifier AS);
   void dumpCleanupObject(const ExprWithCleanups::CleanupObject &C);
   void dumpTemplateSpecializationKind(TemplateSpecializationKind TSK);
+  void dumpBareNestedNameSpecifier(NestedNameSpecifier *NNS);
   void dumpNestedNameSpecifier(const NestedNameSpecifier *NNS);
   void dumpConceptReference(const ConceptReference *R);
+  void dumpTemplateArgument(const TemplateArgument &TA);
+  void dumpTemplateName(TemplateName TN);
 
   void dumpDeclRef(const Decl *D, StringRef Label = {});
 
diff --git a/clang/lib/AST/TextNodeDumper.cpp b/clang/lib/AST/TextNodeDumper.cpp
index 4a1e94ffe283b..742203e3b946d 100644
--- a/clang/lib/AST/TextNodeDumper.cpp
+++ b/clang/lib/AST/TextNodeDumper.cpp
@@ -947,6 +947,26 @@ void TextNodeDumper::dumpDeclRef(const Decl *D, StringRef 
Label) {
   });
 }
 
+void TextNodeDumper::dumpTemplateArgument(const TemplateArgument &TA) {
+  llvm::SmallString<128> Str;
+  {
+llvm::raw_svector_ostream SS(Str);
+TA.print(PrintPolicy, SS, /*IncludeType=*/true);
+  }
+  OS << " '" << Str << "'";
+
+  if (TemplateArgument CanonTA = Context->getCanonicalTemplateArgument(TA);
+  !CanonTA.structurallyEquals(TA)) {
+llvm::SmallString<128> CanonStr;
+{
+  llvm::raw_svector_ostream SS(CanonStr);
+  CanonTA.print(PrintPolicy, SS, /*IncludeType=*/true);
+}
+if (CanonStr != Str)
+  OS << ":'" << CanonStr << "'";
+  }
+}
+
 const 

[clang] [clang] Improve ast-dumper text printing of TemplateArgument (PR #93431)

2024-05-26 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Matheus Izvekov (mizvekov)


Changes

This improves and unifies our approach to printing all template arguments.

The same approach to printing types is extended to all TemplateArguments: A 
sugared version is printed in quotes, followed by printing the canonical form, 
unless they would print the same.

Special improvements are done to add more detail to template template arguments.

It's planned in a future patch to use this improved TemplateName printer for 
other places besides TemplateArguments.

Note: The sugared/desugared printing does not show up for TemplateNames in 
tests yet, because we do a poor job of preserving their type sugar. This will 
be improved in a future patch.

---

Patch is 50.89 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/93431.diff


17 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+5) 
- (modified) clang/include/clang/AST/TextNodeDumper.h (+3) 
- (modified) clang/lib/AST/TextNodeDumper.cpp (+80-14) 
- (modified) clang/test/AST/ast-dump-decl.cpp (+14-11) 
- (modified) 
clang/test/AST/ast-dump-openmp-begin-declare-variant_template_2.cpp (+3-3) 
- (added) clang/test/AST/ast-dump-template-name.cpp (+54) 
- (modified) clang/test/AST/ast-dump-using-template.cpp (+5-3) 
- (modified) clang/test/AST/constraints-explicit-instantiation.cpp (+3-3) 
- (modified) clang/test/OpenMP/align_clause_ast_print.cpp (+1-1) 
- (modified) clang/test/OpenMP/generic_loop_ast_print.cpp (+1-1) 
- (modified) clang/test/OpenMP/interop_ast_print.cpp (+1-1) 
- (modified) clang/test/SemaOpenACC/sub-array-ast.cpp (+1-1) 
- (modified) clang/test/SemaTemplate/aggregate-deduction-candidate.cpp (+8-8) 
- (modified) clang/test/SemaTemplate/attributes.cpp (+32-32) 
- (modified) clang/test/SemaTemplate/deduction-guide.cpp (+7-7) 
- (modified) clang/test/SemaTemplate/make_integer_seq.cpp (+38-30) 
- (modified) clang/test/SemaTemplate/type_pack_element.cpp (+10-10) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 825e91876ffce..403a107edef17 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -818,6 +818,11 @@ Miscellaneous Clang Crashes Fixed
   when ``-fdump-record-layouts-complete`` is passed. Fixes #GH83684.
 - Unhandled StructuralValues in the template differ (#GH93068).
 
+Miscellaneous Clang Improvements
+^
+
+- The text ast-dumper has improved printing of TemplateArguments.
+
 OpenACC Specific Changes
 
 
diff --git a/clang/include/clang/AST/TextNodeDumper.h 
b/clang/include/clang/AST/TextNodeDumper.h
index 1fede6e462e92..0d057b8011164 100644
--- a/clang/include/clang/AST/TextNodeDumper.h
+++ b/clang/include/clang/AST/TextNodeDumper.h
@@ -211,8 +211,11 @@ class TextNodeDumper
   void dumpAccessSpecifier(AccessSpecifier AS);
   void dumpCleanupObject(const ExprWithCleanups::CleanupObject &C);
   void dumpTemplateSpecializationKind(TemplateSpecializationKind TSK);
+  void dumpBareNestedNameSpecifier(NestedNameSpecifier *NNS);
   void dumpNestedNameSpecifier(const NestedNameSpecifier *NNS);
   void dumpConceptReference(const ConceptReference *R);
+  void dumpTemplateArgument(const TemplateArgument &TA);
+  void dumpTemplateName(TemplateName TN);
 
   void dumpDeclRef(const Decl *D, StringRef Label = {});
 
diff --git a/clang/lib/AST/TextNodeDumper.cpp b/clang/lib/AST/TextNodeDumper.cpp
index 4a1e94ffe283b..742203e3b946d 100644
--- a/clang/lib/AST/TextNodeDumper.cpp
+++ b/clang/lib/AST/TextNodeDumper.cpp
@@ -947,6 +947,26 @@ void TextNodeDumper::dumpDeclRef(const Decl *D, StringRef 
Label) {
   });
 }
 
+void TextNodeDumper::dumpTemplateArgument(const TemplateArgument &TA) {
+  llvm::SmallString<128> Str;
+  {
+llvm::raw_svector_ostream SS(Str);
+TA.print(PrintPolicy, SS, /*IncludeType=*/true);
+  }
+  OS << " '" << Str << "'";
+
+  if (TemplateArgument CanonTA = Context->getCanonicalTemplateArgument(TA);
+  !CanonTA.structurallyEquals(TA)) {
+llvm::SmallString<128> CanonStr;
+{
+  llvm::raw_svector_ostream SS(CanonStr);
+  CanonTA.print(PrintPolicy, SS, /*IncludeType=*/true);
+}
+if (CanonStr != Str)
+  OS << ":'" << CanonStr << "'";
+  }
+}
+
 const char *TextNodeDumper::getCommandName(unsigned CommandID) {
   if (Traits)
 return Traits->getCommandInfo(CommandID)->Name;
@@ -1086,45 +1106,91 @@ void TextNodeDumper::VisitNullTemplateArgument(const 
TemplateArgument &) {
 
 void TextNodeDumper::VisitTypeTemplateArgument(const TemplateArgument &TA) {
   OS << " type";
-  dumpType(TA.getAsType());
+  dumpTemplateArgument(TA);
 }
 
 void TextNodeDumper::VisitDeclarationTemplateArgument(
 const TemplateArgument &TA) {
   OS << " decl";
+  dumpTemplateArgument(TA);
   dumpDeclRef(TA.getAsDecl());
 }
 
-void TextNodeDumper::VisitNullPtrTemplateArgument(const TemplateArgument &) {
+void TextNodeDumper::VisitNullPtrTemplateArgument(const T

[clang-tools-extra] [run-clang-tidy.py] Refactor, add progress indicator, add type hints (PR #89490)

2024-05-26 Thread Julian Schmidt via cfe-commits

https://github.com/5chmidti edited 
https://github.com/llvm/llvm-project/pull/89490
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [run-clang-tidy.py] Refactor, add progress indicator, add type hints (PR #89490)

2024-05-26 Thread Julian Schmidt via cfe-commits


@@ -501,70 +506,72 @@ def main():
 
 # Build up a big regexy filter from all command line arguments.
 file_name_re = re.compile("|".join(args.files))
+files = {f for f in files if file_name_re.search(f)}
 
-return_code = 0
+returncode = 0
 try:
-# Spin up a bunch of tidy-launching threads.
-task_queue = queue.Queue(max_task)
-# List of files with a non-zero return code.
-failed_files = []
-lock = threading.Lock()
-for _ in range(max_task):
-t = threading.Thread(
-target=run_tidy,
-args=(
-args,
-clang_tidy_binary,
-export_fixes_dir,
-build_path,
-task_queue,
-lock,
-failed_files,
-),
+semaphore = asyncio.Semaphore(max_task)
+tasks = [
+run_with_semaphore(
+semaphore,
+run_tidy,
+args,
+f,
+clang_tidy_binary,
+export_fixes_dir,
+build_path,
 )
-t.daemon = True
-t.start()
-
-# Fill the queue with files.
-for name in files:
-if file_name_re.search(name):
-task_queue.put(name)
-
-# Wait for all threads to be done.
-task_queue.join()
-if len(failed_files):
-return_code = 1
-
+for f in files
+]
+
+for i, coro in enumerate(asyncio.as_completed(tasks)):
+name, process_returncode, stdout, stderr = await coro
+if process_returncode != 0:
+returncode = 1
+if process_returncode < 0:
+stderr += f"{name}: terminated by signal 
{-process_returncode}\n"
+print(f"[{i + 1}/{len(files)}] {name}")
+if stdout:
+print(stdout)
+if stderr:
+print(stderr, file=sys.stderr)
 except KeyboardInterrupt:
 # This is a sad hack. Unfortunately subprocess goes
 # bonkers with ctrl-c and we start forking merrily.
 print("\nCtrl-C detected, goodbye.")
 if delete_fixes_dir:
+assert export_fixes_dir
 shutil.rmtree(export_fixes_dir)
 os.kill(0, 9)
 
 if combine_fixes:
-print("Writing fixes to " + args.export_fixes + " ...")
+print(f"Writing fixes to {args.export_fixes} ...")
 try:
+assert export_fixes_dir
 merge_replacement_files(export_fixes_dir, args.export_fixes)
 except:
 print("Error exporting fixes.\n", file=sys.stderr)
 traceback.print_exc()
-return_code = 1
+returncode = 1
 
 if args.fix:
 print("Applying fixes ...")
 try:
+assert export_fixes_dir
 apply_fixes(args, clang_apply_replacements_binary, 
export_fixes_dir)
 except:
 print("Error applying fixes.\n", file=sys.stderr)
 traceback.print_exc()
-return_code = 1
+returncode = 1
 
 if delete_fixes_dir:
+assert export_fixes_dir
 shutil.rmtree(export_fixes_dir)
-sys.exit(return_code)
+sys.exit(returncode)
 
 
 if __name__ == "__main__":
-main()
+# FIXME Python 3.7: This can be simplified by asyncio.run(main()).
+loop = asyncio.new_event_loop()
+loop.run_until_complete(main())
+loop.close()

5chmidti wrote:

Just asking: Being unfamiliar with `asyncio`, why do we need this part and an 
`async main`, instead of calling plain `main`?

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


[clang-tools-extra] [run-clang-tidy.py] Refactor, add progress indicator, add type hints (PR #89490)

2024-05-26 Thread Julian Schmidt via cfe-commits


@@ -501,70 +506,72 @@ def main():
 
 # Build up a big regexy filter from all command line arguments.
 file_name_re = re.compile("|".join(args.files))
+files = {f for f in files if file_name_re.search(f)}
 
-return_code = 0
+returncode = 0
 try:
-# Spin up a bunch of tidy-launching threads.
-task_queue = queue.Queue(max_task)
-# List of files with a non-zero return code.
-failed_files = []
-lock = threading.Lock()
-for _ in range(max_task):
-t = threading.Thread(
-target=run_tidy,
-args=(
-args,
-clang_tidy_binary,
-export_fixes_dir,
-build_path,
-task_queue,
-lock,
-failed_files,
-),
+semaphore = asyncio.Semaphore(max_task)
+tasks = [
+run_with_semaphore(
+semaphore,
+run_tidy,
+args,
+f,
+clang_tidy_binary,
+export_fixes_dir,
+build_path,
 )
-t.daemon = True
-t.start()
-
-# Fill the queue with files.
-for name in files:
-if file_name_re.search(name):
-task_queue.put(name)
-
-# Wait for all threads to be done.
-task_queue.join()
-if len(failed_files):
-return_code = 1
-
+for f in files
+]
+
+for i, coro in enumerate(asyncio.as_completed(tasks)):
+name, process_returncode, stdout, stderr = await coro
+if process_returncode != 0:
+returncode = 1
+if process_returncode < 0:
+stderr += f"{name}: terminated by signal 
{-process_returncode}\n"
+print(f"[{i + 1}/{len(files)}] {name}")

5chmidti wrote:

It would look even nicer if the first number was printed with the width of the 
second number, i.e.: 

```
[ 3/15]
...
[15/15]
```

That way, the position of the second number and the command(/file) does not 
shift when the next power of ten is reached.

```python
i = 4
num_files = 15

print("[{0: >{1}}/{2}]".format(i+1,len(f"{num_files}"), num_files))
print(f'[{i+1: >{len(f"{num_files}")}}/{num_files}]')
```


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


[clang-tools-extra] [run-clang-tidy.py] Refactor, add progress indicator, add type hints (PR #89490)

2024-05-26 Thread Julian Schmidt via cfe-commits

https://github.com/5chmidti commented:

Thanks for the cleanup, it looks overall good (w.r.t `asyncio`: I only know 
about `asyncio` what I read in this pr).

> Only print the filename after completion, not the entire Clang-Tidy 
> invocation command. I find this neater but the behavior can easily be 
> restored.

> By default print like in original script (command line), but add --progress 
> switch that will change it to current behavior.

I'd prefer the original behavior as well, but printing only the filename can be 
added as a flag. Although, I'm not sure `--progress` is a good name for 
something that only changes if the command or file is printed, because the 
progress indicator should be emitted either way.

> Added an initial message with the number of files to process over the number 
> of files in compilation database.

Maybe that was removed? Either way, I think it's +- not necessary, but I'm not 
against having it.

> More graceful shutdown would be welcome.

+1
IMO, that needs to be done before merging.


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


[clang] [clang] Improve ast-dumper text printing of TemplateArgument (PR #93431)

2024-05-26 Thread Matheus Izvekov via cfe-commits

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

>From c23a96038a8233b44b49bc0a1d2a2475e4d2a8ae Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Fri, 24 May 2024 12:22:55 -0300
Subject: [PATCH] [clang] Improve ast-dumper text printing of TemplateArgument

This improves and unifies our approach to printing all template
arguments.

The same approach to printing types is extended to all
TemplateArguments: A sugared version is printed in quotes,
followed by printing the canonical form, unless they would print
the same.

Special improvements are done to add more detail to template template
arguments.

It's planned in a future patch to use this improved TemplateName
printer for other places besides TemplateArguments.

Note: The sugared/desugared printing does not show up for
TemplateNames in tests yet, because we do a poor job of preserving
their type sugar. This will be improved in a future patch.
---
 clang/docs/ReleaseNotes.rst   |  5 +
 clang/include/clang/AST/TextNodeDumper.h  |  2 +
 clang/lib/AST/TextNodeDumper.cpp  | 94 ---
 clang/test/AST/ast-dump-decl.cpp  | 25 ++---
 ...penmp-begin-declare-variant_template_2.cpp |  6 +-
 clang/test/AST/ast-dump-template-name.cpp | 54 +++
 clang/test/AST/ast-dump-using-template.cpp|  8 +-
 .../constraints-explicit-instantiation.cpp|  6 +-
 clang/test/OpenMP/align_clause_ast_print.cpp  |  2 +-
 clang/test/OpenMP/generic_loop_ast_print.cpp  |  2 +-
 clang/test/OpenMP/interop_ast_print.cpp   |  2 +-
 clang/test/SemaOpenACC/sub-array-ast.cpp  |  2 +-
 .../aggregate-deduction-candidate.cpp | 16 ++--
 clang/test/SemaTemplate/attributes.cpp| 64 ++---
 clang/test/SemaTemplate/deduction-guide.cpp   | 14 +--
 clang/test/SemaTemplate/make_integer_seq.cpp  | 68 --
 clang/test/SemaTemplate/type_pack_element.cpp | 20 ++--
 17 files changed, 265 insertions(+), 125 deletions(-)
 create mode 100644 clang/test/AST/ast-dump-template-name.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 825e91876ffce..403a107edef17 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -818,6 +818,11 @@ Miscellaneous Clang Crashes Fixed
   when ``-fdump-record-layouts-complete`` is passed. Fixes #GH83684.
 - Unhandled StructuralValues in the template differ (#GH93068).
 
+Miscellaneous Clang Improvements
+^
+
+- The text ast-dumper has improved printing of TemplateArguments.
+
 OpenACC Specific Changes
 
 
diff --git a/clang/include/clang/AST/TextNodeDumper.h 
b/clang/include/clang/AST/TextNodeDumper.h
index 1fede6e462e92..63fa16c9ec47c 100644
--- a/clang/include/clang/AST/TextNodeDumper.h
+++ b/clang/include/clang/AST/TextNodeDumper.h
@@ -213,6 +213,8 @@ class TextNodeDumper
   void dumpTemplateSpecializationKind(TemplateSpecializationKind TSK);
   void dumpNestedNameSpecifier(const NestedNameSpecifier *NNS);
   void dumpConceptReference(const ConceptReference *R);
+  void dumpTemplateArgument(const TemplateArgument &TA);
+  void dumpTemplateName(TemplateName TN);
 
   void dumpDeclRef(const Decl *D, StringRef Label = {});
 
diff --git a/clang/lib/AST/TextNodeDumper.cpp b/clang/lib/AST/TextNodeDumper.cpp
index 4a1e94ffe283b..742203e3b946d 100644
--- a/clang/lib/AST/TextNodeDumper.cpp
+++ b/clang/lib/AST/TextNodeDumper.cpp
@@ -947,6 +947,26 @@ void TextNodeDumper::dumpDeclRef(const Decl *D, StringRef 
Label) {
   });
 }
 
+void TextNodeDumper::dumpTemplateArgument(const TemplateArgument &TA) {
+  llvm::SmallString<128> Str;
+  {
+llvm::raw_svector_ostream SS(Str);
+TA.print(PrintPolicy, SS, /*IncludeType=*/true);
+  }
+  OS << " '" << Str << "'";
+
+  if (TemplateArgument CanonTA = Context->getCanonicalTemplateArgument(TA);
+  !CanonTA.structurallyEquals(TA)) {
+llvm::SmallString<128> CanonStr;
+{
+  llvm::raw_svector_ostream SS(CanonStr);
+  CanonTA.print(PrintPolicy, SS, /*IncludeType=*/true);
+}
+if (CanonStr != Str)
+  OS << ":'" << CanonStr << "'";
+  }
+}
+
 const char *TextNodeDumper::getCommandName(unsigned CommandID) {
   if (Traits)
 return Traits->getCommandInfo(CommandID)->Name;
@@ -1086,45 +1106,91 @@ void TextNodeDumper::VisitNullTemplateArgument(const 
TemplateArgument &) {
 
 void TextNodeDumper::VisitTypeTemplateArgument(const TemplateArgument &TA) {
   OS << " type";
-  dumpType(TA.getAsType());
+  dumpTemplateArgument(TA);
 }
 
 void TextNodeDumper::VisitDeclarationTemplateArgument(
 const TemplateArgument &TA) {
   OS << " decl";
+  dumpTemplateArgument(TA);
   dumpDeclRef(TA.getAsDecl());
 }
 
-void TextNodeDumper::VisitNullPtrTemplateArgument(const TemplateArgument &) {
+void TextNodeDumper::VisitNullPtrTemplateArgument(const TemplateArgument &TA) {
   OS << " nullptr";
+  dumpTemplateArgument(TA);
 }
 
 void TextNodeDumper::VisitIntegralTemplateArgument(const Te

[clang] [llvm] [PowerPC] Support -fpatchable-function-entry (PR #92997)

2024-05-26 Thread Fangrui Song via cfe-commits

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


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


[clang] [clang] Improve ast-dumper text printing of TemplateArgument (PR #93431)

2024-05-26 Thread Matheus Izvekov via cfe-commits

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

>From 031e7c235ce5cbae31504c21eeecc7655fbd1566 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Fri, 24 May 2024 12:22:55 -0300
Subject: [PATCH] [clang] Improve ast-dumper text printing of TemplateArgument

This improves and unifies our approach to printing all template
arguments.

The same approach to printing types is extended to all
TemplateArguments: A sugared version is printed in quotes,
followed by printing the canonical form, unless they would print
the same.

Special improvements are done to add more detail to template template
arguments.

It's planned in a future patch to use this improved TemplateName
printer for other places besides TemplateArguments.

Note: The sugared/desugared printing does not show up for
TemplateNames in tests yet, because we do a poor job of preserving
their type sugar. This will be improved in a future patch.
---
 clang/docs/ReleaseNotes.rst   |   5 +
 clang/include/clang/AST/TextNodeDumper.h  |   2 +
 clang/lib/AST/TextNodeDumper.cpp  | 103 +++---
 clang/test/AST/ast-dump-decl.cpp  |  25 +++--
 ...penmp-begin-declare-variant_template_2.cpp |   6 +-
 clang/test/AST/ast-dump-template-name.cpp |  54 +
 clang/test/AST/ast-dump-using-template.cpp|   8 +-
 .../constraints-explicit-instantiation.cpp|   6 +-
 clang/test/OpenMP/align_clause_ast_print.cpp  |   2 +-
 clang/test/OpenMP/generic_loop_ast_print.cpp  |   2 +-
 clang/test/OpenMP/interop_ast_print.cpp   |   2 +-
 clang/test/SemaOpenACC/sub-array-ast.cpp  |   2 +-
 .../aggregate-deduction-candidate.cpp |  16 +--
 clang/test/SemaTemplate/attributes.cpp|  64 +--
 clang/test/SemaTemplate/deduction-guide.cpp   |  14 +--
 clang/test/SemaTemplate/make_integer_seq.cpp  |  68 +++-
 clang/test/SemaTemplate/type_pack_element.cpp |  20 ++--
 17 files changed, 274 insertions(+), 125 deletions(-)
 create mode 100644 clang/test/AST/ast-dump-template-name.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 825e91876ffce..403a107edef17 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -818,6 +818,11 @@ Miscellaneous Clang Crashes Fixed
   when ``-fdump-record-layouts-complete`` is passed. Fixes #GH83684.
 - Unhandled StructuralValues in the template differ (#GH93068).
 
+Miscellaneous Clang Improvements
+^
+
+- The text ast-dumper has improved printing of TemplateArguments.
+
 OpenACC Specific Changes
 
 
diff --git a/clang/include/clang/AST/TextNodeDumper.h 
b/clang/include/clang/AST/TextNodeDumper.h
index 1fede6e462e92..63fa16c9ec47c 100644
--- a/clang/include/clang/AST/TextNodeDumper.h
+++ b/clang/include/clang/AST/TextNodeDumper.h
@@ -213,6 +213,8 @@ class TextNodeDumper
   void dumpTemplateSpecializationKind(TemplateSpecializationKind TSK);
   void dumpNestedNameSpecifier(const NestedNameSpecifier *NNS);
   void dumpConceptReference(const ConceptReference *R);
+  void dumpTemplateArgument(const TemplateArgument &TA);
+  void dumpTemplateName(TemplateName TN);
 
   void dumpDeclRef(const Decl *D, StringRef Label = {});
 
diff --git a/clang/lib/AST/TextNodeDumper.cpp b/clang/lib/AST/TextNodeDumper.cpp
index 4a1e94ffe283b..ed343ffb74124 100644
--- a/clang/lib/AST/TextNodeDumper.cpp
+++ b/clang/lib/AST/TextNodeDumper.cpp
@@ -947,6 +947,26 @@ void TextNodeDumper::dumpDeclRef(const Decl *D, StringRef 
Label) {
   });
 }
 
+void TextNodeDumper::dumpTemplateArgument(const TemplateArgument &TA) {
+  llvm::SmallString<128> Str;
+  {
+llvm::raw_svector_ostream SS(Str);
+TA.print(PrintPolicy, SS, /*IncludeType=*/true);
+  }
+  OS << " '" << Str << "'";
+
+  if (TemplateArgument CanonTA = Context->getCanonicalTemplateArgument(TA);
+  !CanonTA.structurallyEquals(TA)) {
+llvm::SmallString<128> CanonStr;
+{
+  llvm::raw_svector_ostream SS(CanonStr);
+  CanonTA.print(PrintPolicy, SS, /*IncludeType=*/true);
+}
+if (CanonStr != Str)
+  OS << ":'" << CanonStr << "'";
+  }
+}
+
 const char *TextNodeDumper::getCommandName(unsigned CommandID) {
   if (Traits)
 return Traits->getCommandInfo(CommandID)->Name;
@@ -1086,45 +1106,100 @@ void TextNodeDumper::VisitNullTemplateArgument(const 
TemplateArgument &) {
 
 void TextNodeDumper::VisitTypeTemplateArgument(const TemplateArgument &TA) {
   OS << " type";
-  dumpType(TA.getAsType());
+  dumpTemplateArgument(TA);
 }
 
 void TextNodeDumper::VisitDeclarationTemplateArgument(
 const TemplateArgument &TA) {
   OS << " decl";
+  dumpTemplateArgument(TA);
   dumpDeclRef(TA.getAsDecl());
 }
 
-void TextNodeDumper::VisitNullPtrTemplateArgument(const TemplateArgument &) {
+void TextNodeDumper::VisitNullPtrTemplateArgument(const TemplateArgument &TA) {
   OS << " nullptr";
+  dumpTemplateArgument(TA);
 }
 
 void TextNodeDumper::VisitIntegralTemplateArgumen

[clang] [Clang][Sema] Use correct TemplateName when transforming TemplateSpecializationType (PR #93411)

2024-05-26 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov commented:

The problem here is the loss of the qualification on the TemplateNames

This patch fixes the problem, without taking any workarounds: 
https://github.com/llvm/llvm-project/pull/93433

It also doesn't cause any change in diagnostics in 
`clang/test/SemaTemplate/typename-specifier-3.cpp`.

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


[clang] [clang-tools-extra] [libcxx] [clang][Modules] Remove unnecessary includes of `Module.h` (PR #93417)

2024-05-26 Thread Chuanqi Xu via cfe-commits


@@ -159,7 +159,8 @@ class APINotesManager {
   ArrayRef getCurrentModuleReaders() const {
 bool HasPublic = CurrentModuleReaders[ReaderKind::Public];
 bool HasPrivate = CurrentModuleReaders[ReaderKind::Private];
-assert((!HasPrivate || HasPublic) && "private module requires public 
module");
+assert((!HasPrivate || HasPublic) &&
+   "private module requires public module");

ChuanqiXu9 wrote:

Please don't change untouched codes.

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


[clang] [clang-tools-extra] [libcxx] [lldb] [llvm] Add clang basic module directory (PR #93388)

2024-05-26 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

BTW, I tried to split `Module` class into `ModuleBase`, `ClangModule` and 
`Cpp20Modules` (and HeaderUnits) classes to improve the readability. But it 
showed too hard and too many things get changes then I stopped.

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


[clang] [clang] Improve ast-dumper text printing of TemplateArgument (PR #93431)

2024-05-26 Thread Matheus Izvekov via cfe-commits

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

>From f9892ebed002d73c74f44629e926386006f7bec1 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Fri, 24 May 2024 12:22:55 -0300
Subject: [PATCH] [clang] Improve ast-dumper text printing of TemplateArgument

This improves and unifies our approach to printing all template
arguments.

The same approach to printing types is extended to all
TemplateArguments: A sugared version is printed in quotes,
followed by printing the canonical form, unless they would print
the same.

Special improvements are done to add more detail to template template
arguments.

It's planned in a future patch to use this improved TemplateName
printer for other places besides TemplateArguments.

Note: The sugared/desugared printing does not show up for
TemplateNames in tests yet, because we do a poor job of preserving
their type sugar. This will be improved in a future patch.
---
 clang/docs/ReleaseNotes.rst   |   2 +
 clang/include/clang/AST/TextNodeDumper.h  |   2 +
 clang/lib/AST/TextNodeDumper.cpp  | 103 +++---
 clang/test/AST/ast-dump-decl.cpp  |  25 +++--
 ...penmp-begin-declare-variant_template_2.cpp |   6 +-
 clang/test/AST/ast-dump-template-name.cpp |  54 +
 clang/test/AST/ast-dump-using-template.cpp|   8 +-
 .../constraints-explicit-instantiation.cpp|   6 +-
 clang/test/OpenMP/align_clause_ast_print.cpp  |   2 +-
 clang/test/OpenMP/generic_loop_ast_print.cpp  |   2 +-
 clang/test/OpenMP/interop_ast_print.cpp   |   2 +-
 clang/test/SemaOpenACC/sub-array-ast.cpp  |   2 +-
 .../aggregate-deduction-candidate.cpp |  18 +--
 clang/test/SemaTemplate/attributes.cpp|  64 +--
 clang/test/SemaTemplate/deduction-guide.cpp   |  14 +--
 clang/test/SemaTemplate/make_integer_seq.cpp  |  68 +++-
 clang/test/SemaTemplate/type_pack_element.cpp |  20 ++--
 17 files changed, 272 insertions(+), 126 deletions(-)
 create mode 100644 clang/test/AST/ast-dump-template-name.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 825e91876ffce..f7562ce74f4ed 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -98,6 +98,8 @@ ABI Changes in This Version
 AST Dumping Potentially Breaking Changes
 
 
+- The text ast-dumper has improved printing of TemplateArguments.
+
 Clang Frontend Potentially Breaking Changes
 ---
 - Removed support for constructing on-stack ``TemplateArgumentList``\ s; 
interfaces should instead
diff --git a/clang/include/clang/AST/TextNodeDumper.h 
b/clang/include/clang/AST/TextNodeDumper.h
index 1fede6e462e92..63fa16c9ec47c 100644
--- a/clang/include/clang/AST/TextNodeDumper.h
+++ b/clang/include/clang/AST/TextNodeDumper.h
@@ -213,6 +213,8 @@ class TextNodeDumper
   void dumpTemplateSpecializationKind(TemplateSpecializationKind TSK);
   void dumpNestedNameSpecifier(const NestedNameSpecifier *NNS);
   void dumpConceptReference(const ConceptReference *R);
+  void dumpTemplateArgument(const TemplateArgument &TA);
+  void dumpTemplateName(TemplateName TN);
 
   void dumpDeclRef(const Decl *D, StringRef Label = {});
 
diff --git a/clang/lib/AST/TextNodeDumper.cpp b/clang/lib/AST/TextNodeDumper.cpp
index 4a1e94ffe283b..ed343ffb74124 100644
--- a/clang/lib/AST/TextNodeDumper.cpp
+++ b/clang/lib/AST/TextNodeDumper.cpp
@@ -947,6 +947,26 @@ void TextNodeDumper::dumpDeclRef(const Decl *D, StringRef 
Label) {
   });
 }
 
+void TextNodeDumper::dumpTemplateArgument(const TemplateArgument &TA) {
+  llvm::SmallString<128> Str;
+  {
+llvm::raw_svector_ostream SS(Str);
+TA.print(PrintPolicy, SS, /*IncludeType=*/true);
+  }
+  OS << " '" << Str << "'";
+
+  if (TemplateArgument CanonTA = Context->getCanonicalTemplateArgument(TA);
+  !CanonTA.structurallyEquals(TA)) {
+llvm::SmallString<128> CanonStr;
+{
+  llvm::raw_svector_ostream SS(CanonStr);
+  CanonTA.print(PrintPolicy, SS, /*IncludeType=*/true);
+}
+if (CanonStr != Str)
+  OS << ":'" << CanonStr << "'";
+  }
+}
+
 const char *TextNodeDumper::getCommandName(unsigned CommandID) {
   if (Traits)
 return Traits->getCommandInfo(CommandID)->Name;
@@ -1086,45 +1106,100 @@ void TextNodeDumper::VisitNullTemplateArgument(const 
TemplateArgument &) {
 
 void TextNodeDumper::VisitTypeTemplateArgument(const TemplateArgument &TA) {
   OS << " type";
-  dumpType(TA.getAsType());
+  dumpTemplateArgument(TA);
 }
 
 void TextNodeDumper::VisitDeclarationTemplateArgument(
 const TemplateArgument &TA) {
   OS << " decl";
+  dumpTemplateArgument(TA);
   dumpDeclRef(TA.getAsDecl());
 }
 
-void TextNodeDumper::VisitNullPtrTemplateArgument(const TemplateArgument &) {
+void TextNodeDumper::VisitNullPtrTemplateArgument(const TemplateArgument &TA) {
   OS << " nullptr";
+  dumpTemplateArgument(TA);
 }
 
 void TextNodeDumper::VisitIntegralTemplateA

[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-26 Thread Chuanqi Xu via cfe-commits

https://github.com/ChuanqiXu9 edited 
https://github.com/llvm/llvm-project/pull/66462
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-26 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,106 @@
+//===-- ModuleDependencyScanner.h *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+
+#include "GlobalCompilationDatabase.h"
+#include "support/Path.h"
+#include "support/ThreadsafeFS.h"
+
+#include "clang/Tooling/DependencyScanning/DependencyScanningService.h"
+#include "clang/Tooling/DependencyScanning/DependencyScanningTool.h"
+
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringMap.h"
+
+namespace clang {
+namespace clangd {
+
+/// A scanner to query the dependency information for C++20 Modules.
+///
+/// The scanner can scan a single file with `scan(PathRef)` member function
+/// or scan the whole project with `globalScan(PathRef)` member function. See
+/// the comments of `globalScan` to see the details.
+///
+/// ModuleDependencyScanner should only be used via ScanningAllProjectModules.
+///
+/// The ModuleDependencyScanner can get the directly required module name for a
+/// specific source file. Also the ModuleDependencyScanner can get the source
+/// file declaring a specific module name.
+///
+/// IMPORTANT NOTE: we assume that every module unit is only declared once in a
+/// source file in the project. But the assumption is not strictly true even
+/// besides the invalid projects. The language specification requires that 
every
+/// module unit should be unique in a valid program. But a project can contain
+/// multiple programs. Then it is valid that we can have multiple source files
+/// declaring the same module in a project as long as these source files don't
+/// interere with each other.`
+class ModuleDependencyScanner {
+public:
+  ModuleDependencyScanner(const GlobalCompilationDatabase &CDB,
+  const ThreadsafeFS &TFS)
+  : CDB(CDB), TFS(TFS),
+Service(tooling::dependencies::ScanningMode::CanonicalPreprocessing,
+tooling::dependencies::ScanningOutputFormat::P1689) {}
+
+  // The scanned modules dependency information for a specific source file.
+  struct ModuleDependencyInfo {
+// The name of the module if the file is a module unit.
+std::optional ModuleName;
+// A list of names for the modules that the file directly depends.
+std::vector RequiredModules;
+  };
+
+  /// Scanning the single file specified by \param FilePath.
+  /// NOTE: This is only used by unittests for external uses.
+  std::optional scan(PathRef FilePath);
+
+  /// Scanning every source file in the current project to get the
+  ///  to  map.
+  /// It looks unefficiency to scan the whole project especially for
+  /// every version of every file!
+  /// TODO: We should find an efficient method to get the 
+  /// to  map. We can make it either by providing
+  /// a global module dependency scanner to monitor every file. Or we
+  /// can simply require the build systems (or even if the end users)

ChuanqiXu9 wrote:

Done

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-26 Thread Chuanqi Xu via cfe-commits


@@ -740,6 +741,21 @@ 
DirectoryBasedGlobalCompilationDatabase::getProjectInfo(PathRef File) const {
   return Res->PI;
 }
 
+std::shared_ptr
+DirectoryBasedGlobalCompilationDatabase::getProjectModules(PathRef File) const 
{
+  CDBLookupRequest Req;
+  Req.FileName = File;
+  Req.ShouldBroadcast = false;
+  Req.FreshTime = Req.FreshTimeMissing =
+  std::chrono::steady_clock::time_point::min();
+  auto Res = lookupCDB(Req);
+  if (!Res)
+return {};
+  return ProjectModules::create(
+  ProjectModules::ProjectModulesKind::ScanningAllFiles,
+  Res->CDB->getAllFiles(), *this, Opts.TFS);

ChuanqiXu9 wrote:

I added a FIXME for this since I am not sure can we do here. Should we pass 
`Res->CDB` here? If we can't solve it in a simple manner. I suggest to address 
this in future versions and not blocking the initial version.

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-26 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,106 @@
+//===-- ModuleDependencyScanner.h *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+
+#include "GlobalCompilationDatabase.h"
+#include "support/Path.h"
+#include "support/ThreadsafeFS.h"
+
+#include "clang/Tooling/DependencyScanning/DependencyScanningService.h"
+#include "clang/Tooling/DependencyScanning/DependencyScanningTool.h"
+
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringMap.h"
+
+namespace clang {
+namespace clangd {
+
+/// A scanner to query the dependency information for C++20 Modules.
+///
+/// The scanner can scan a single file with `scan(PathRef)` member function
+/// or scan the whole project with `globalScan(PathRef)` member function. See

ChuanqiXu9 wrote:

Done

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-26 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,106 @@
+//===-- ModuleDependencyScanner.h *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+
+#include "GlobalCompilationDatabase.h"
+#include "support/Path.h"
+#include "support/ThreadsafeFS.h"
+
+#include "clang/Tooling/DependencyScanning/DependencyScanningService.h"
+#include "clang/Tooling/DependencyScanning/DependencyScanningTool.h"
+
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringMap.h"
+
+namespace clang {
+namespace clangd {
+
+/// A scanner to query the dependency information for C++20 Modules.
+///
+/// The scanner can scan a single file with `scan(PathRef)` member function
+/// or scan the whole project with `globalScan(PathRef)` member function. See
+/// the comments of `globalScan` to see the details.
+///
+/// ModuleDependencyScanner should only be used via ScanningAllProjectModules.

ChuanqiXu9 wrote:

Done

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-26 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,81 @@
+//=== ModuleDependencyScanner.cpp *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ModuleDependencyScanner.h"
+#include "support/Logger.h"
+
+namespace clang {
+namespace clangd {
+
+std::optional
+ModuleDependencyScanner::scan(PathRef FilePath) {
+  std::optional Cmd = CDB.getCompileCommand(FilePath);
+
+  if (!Cmd)
+return std::nullopt;
+
+  using namespace clang::tooling::dependencies;
+
+  llvm::SmallString<128> FilePathDir(FilePath);
+  llvm::sys::path::remove_filename(FilePathDir);
+  DependencyScanningTool ScanningTool(Service, TFS.view(FilePathDir));
+
+  llvm::Expected ScanningResult =
+  ScanningTool.getP1689ModuleDependencyFile(*Cmd, Cmd->Directory);
+
+  if (auto E = ScanningResult.takeError()) {
+log("Scanning modules dependencies for {0} failed: {1}", FilePath,

ChuanqiXu9 wrote:

Done

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-26 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,106 @@
+//===-- ModuleDependencyScanner.h *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+
+#include "GlobalCompilationDatabase.h"
+#include "support/Path.h"
+#include "support/ThreadsafeFS.h"
+
+#include "clang/Tooling/DependencyScanning/DependencyScanningService.h"
+#include "clang/Tooling/DependencyScanning/DependencyScanningTool.h"
+
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringMap.h"
+
+namespace clang {
+namespace clangd {
+
+/// A scanner to query the dependency information for C++20 Modules.
+///
+/// The scanner can scan a single file with `scan(PathRef)` member function
+/// or scan the whole project with `globalScan(PathRef)` member function. See
+/// the comments of `globalScan` to see the details.
+///
+/// ModuleDependencyScanner should only be used via ScanningAllProjectModules.
+///
+/// The ModuleDependencyScanner can get the directly required module name for a
+/// specific source file. Also the ModuleDependencyScanner can get the source
+/// file declaring a specific module name.
+///
+/// IMPORTANT NOTE: we assume that every module unit is only declared once in a
+/// source file in the project. But the assumption is not strictly true even
+/// besides the invalid projects. The language specification requires that 
every
+/// module unit should be unique in a valid program. But a project can contain
+/// multiple programs. Then it is valid that we can have multiple source files
+/// declaring the same module in a project as long as these source files don't
+/// interere with each other.`
+class ModuleDependencyScanner {
+public:
+  ModuleDependencyScanner(const GlobalCompilationDatabase &CDB,
+  const ThreadsafeFS &TFS)
+  : CDB(CDB), TFS(TFS),
+Service(tooling::dependencies::ScanningMode::CanonicalPreprocessing,
+tooling::dependencies::ScanningOutputFormat::P1689) {}
+
+  // The scanned modules dependency information for a specific source file.

ChuanqiXu9 wrote:

Done

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-26 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,106 @@
+//===-- ModuleDependencyScanner.h *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+
+#include "GlobalCompilationDatabase.h"
+#include "support/Path.h"
+#include "support/ThreadsafeFS.h"
+
+#include "clang/Tooling/DependencyScanning/DependencyScanningService.h"
+#include "clang/Tooling/DependencyScanning/DependencyScanningTool.h"
+
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringMap.h"
+
+namespace clang {
+namespace clangd {
+
+/// A scanner to query the dependency information for C++20 Modules.
+///
+/// The scanner can scan a single file with `scan(PathRef)` member function
+/// or scan the whole project with `globalScan(PathRef)` member function. See
+/// the comments of `globalScan` to see the details.
+///
+/// ModuleDependencyScanner should only be used via ScanningAllProjectModules.
+///
+/// The ModuleDependencyScanner can get the directly required module name for a
+/// specific source file. Also the ModuleDependencyScanner can get the source
+/// file declaring a specific module name.
+///
+/// IMPORTANT NOTE: we assume that every module unit is only declared once in a
+/// source file in the project. But the assumption is not strictly true even
+/// besides the invalid projects. The language specification requires that 
every
+/// module unit should be unique in a valid program. But a project can contain
+/// multiple programs. Then it is valid that we can have multiple source files
+/// declaring the same module in a project as long as these source files don't
+/// interere with each other.`

ChuanqiXu9 wrote:

Done

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-26 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,106 @@
+//===-- ModuleDependencyScanner.h *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+
+#include "GlobalCompilationDatabase.h"
+#include "support/Path.h"
+#include "support/ThreadsafeFS.h"
+
+#include "clang/Tooling/DependencyScanning/DependencyScanningService.h"
+#include "clang/Tooling/DependencyScanning/DependencyScanningTool.h"
+
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringMap.h"
+
+namespace clang {
+namespace clangd {
+
+/// A scanner to query the dependency information for C++20 Modules.
+///
+/// The scanner can scan a single file with `scan(PathRef)` member function
+/// or scan the whole project with `globalScan(PathRef)` member function. See
+/// the comments of `globalScan` to see the details.
+///
+/// ModuleDependencyScanner should only be used via ScanningAllProjectModules.
+///
+/// The ModuleDependencyScanner can get the directly required module name for a
+/// specific source file. Also the ModuleDependencyScanner can get the source
+/// file declaring a specific module name.
+///
+/// IMPORTANT NOTE: we assume that every module unit is only declared once in a
+/// source file in the project. But the assumption is not strictly true even
+/// besides the invalid projects. The language specification requires that 
every
+/// module unit should be unique in a valid program. But a project can contain
+/// multiple programs. Then it is valid that we can have multiple source files
+/// declaring the same module in a project as long as these source files don't
+/// interere with each other.`
+class ModuleDependencyScanner {
+public:
+  ModuleDependencyScanner(const GlobalCompilationDatabase &CDB,
+  const ThreadsafeFS &TFS)
+  : CDB(CDB), TFS(TFS),
+Service(tooling::dependencies::ScanningMode::CanonicalPreprocessing,
+tooling::dependencies::ScanningOutputFormat::P1689) {}
+
+  // The scanned modules dependency information for a specific source file.
+  struct ModuleDependencyInfo {
+// The name of the module if the file is a module unit.
+std::optional ModuleName;
+// A list of names for the modules that the file directly depends.
+std::vector RequiredModules;
+  };
+
+  /// Scanning the single file specified by \param FilePath.
+  /// NOTE: This is only used by unittests for external uses.
+  std::optional scan(PathRef FilePath);
+
+  /// Scanning every source file in the current project to get the
+  ///  to  map.
+  /// It looks unefficiency to scan the whole project especially for
+  /// every version of every file!
+  /// TODO: We should find an efficient method to get the 
+  /// to  map. We can make it either by providing
+  /// a global module dependency scanner to monitor every file. Or we
+  /// can simply require the build systems (or even if the end users)
+  /// to provide the map.
+  void globalScan(const std::vector &AllFiles);

ChuanqiXu9 wrote:

Done

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-26 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,106 @@
+//===-- ModuleDependencyScanner.h *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+
+#include "GlobalCompilationDatabase.h"
+#include "support/Path.h"
+#include "support/ThreadsafeFS.h"
+
+#include "clang/Tooling/DependencyScanning/DependencyScanningService.h"
+#include "clang/Tooling/DependencyScanning/DependencyScanningTool.h"
+
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringMap.h"
+
+namespace clang {
+namespace clangd {
+
+/// A scanner to query the dependency information for C++20 Modules.
+///
+/// The scanner can scan a single file with `scan(PathRef)` member function
+/// or scan the whole project with `globalScan(PathRef)` member function. See
+/// the comments of `globalScan` to see the details.
+///
+/// ModuleDependencyScanner should only be used via ScanningAllProjectModules.
+///
+/// The ModuleDependencyScanner can get the directly required module name for a
+/// specific source file. Also the ModuleDependencyScanner can get the source
+/// file declaring a specific module name.
+///
+/// IMPORTANT NOTE: we assume that every module unit is only declared once in a
+/// source file in the project. But the assumption is not strictly true even
+/// besides the invalid projects. The language specification requires that 
every
+/// module unit should be unique in a valid program. But a project can contain
+/// multiple programs. Then it is valid that we can have multiple source files
+/// declaring the same module in a project as long as these source files don't
+/// interere with each other.`
+class ModuleDependencyScanner {
+public:
+  ModuleDependencyScanner(const GlobalCompilationDatabase &CDB,
+  const ThreadsafeFS &TFS)
+  : CDB(CDB), TFS(TFS),
+Service(tooling::dependencies::ScanningMode::CanonicalPreprocessing,
+tooling::dependencies::ScanningOutputFormat::P1689) {}
+
+  // The scanned modules dependency information for a specific source file.
+  struct ModuleDependencyInfo {
+// The name of the module if the file is a module unit.
+std::optional ModuleName;
+// A list of names for the modules that the file directly depends.
+std::vector RequiredModules;
+  };
+
+  /// Scanning the single file specified by \param FilePath.
+  /// NOTE: This is only used by unittests for external uses.

ChuanqiXu9 wrote:

I just thought it will be better if it has less interfaces. Then currently 
`scan()` is not directly called outside the class so I add the note. But I see 
your thoughts about ModuleDependencyScanner to treat it as a self-contained 
class. I feel it good too. So I'd like to remove the note.

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-26 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,81 @@
+//=== ModuleDependencyScanner.cpp *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ModuleDependencyScanner.h"
+#include "support/Logger.h"
+
+namespace clang {
+namespace clangd {
+
+std::optional
+ModuleDependencyScanner::scan(PathRef FilePath) {
+  std::optional Cmd = CDB.getCompileCommand(FilePath);
+
+  if (!Cmd)
+return std::nullopt;
+
+  using namespace clang::tooling::dependencies;
+
+  llvm::SmallString<128> FilePathDir(FilePath);
+  llvm::sys::path::remove_filename(FilePathDir);
+  DependencyScanningTool ScanningTool(Service, TFS.view(FilePathDir));
+
+  llvm::Expected ScanningResult =
+  ScanningTool.getP1689ModuleDependencyFile(*Cmd, Cmd->Directory);
+
+  if (auto E = ScanningResult.takeError()) {
+log("Scanning modules dependencies for {0} failed: {1}", FilePath,
+llvm::toString(std::move(E)));
+return std::nullopt;
+  }
+
+  ModuleDependencyInfo Result;
+
+  if (ScanningResult->Provides) {
+ModuleNameToSource[ScanningResult->Provides->ModuleName] = FilePath;

ChuanqiXu9 wrote:

We can't make `scan()` const, since we will pass the member variable `Service` 
as a non-const reference to construct `DependencyScanningTool`.

And we can't (or we don't want) assume the `getRequiredModules()` will be 
executed after `globalScan()`. We require to run `getSourceForModuleName()` 
after `globalScan()` since we have to.

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-26 Thread Chuanqi Xu via cfe-commits

https://github.com/ChuanqiXu9 commented:

Thanks for reviewing. It makes the code looks better indeed.

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-26 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,339 @@
+//===- ModulesBuilder.cpp *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ModulesBuilder.h"
+#include "PrerequisiteModules.h"
+#include "support/Logger.h"
+
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/FrontendActions.h"
+
+namespace clang {
+namespace clangd {
+
+namespace {
+
+/// Get or create a path to store module files. Generally it should be:
+///
+///   project_root/.cache/clangd/module_files/{RequiredPrefixDir}/.
+///
+/// \param MainFile is used to get the root of the project from global
+/// compilation database. \param RequiredPrefixDir is used to get the user
+/// defined prefix for module files. This is useful when we want to seperate
+/// module files. e.g., we want to build module files for the same module unit
+/// `a.cppm` with 2 different users `b.cpp` and `c.cpp` and we don't want the
+/// module file for `b.cpp` be conflict with the module files for `c.cpp`. Then
+/// we can put the 2 module files into different dirs like:
+///
+///   project_root/.cache/clangd/module_files/b.cpp/a.pcm
+///   project_root/.cache/clangd/module_files/c.cpp/a.pcm
+llvm::SmallString<256> getModuleFilesPath(PathRef MainFile,
+  const GlobalCompilationDatabase &CDB,
+  StringRef RequiredPrefixDir) {
+  std::optional PI = CDB.getProjectInfo(MainFile);
+  if (!PI)
+return {};
+
+  // FIXME: PI->SourceRoot may be empty, depending on the CDB strategy.
+  llvm::SmallString<256> Result(PI->SourceRoot);
+
+  llvm::sys::path::append(Result, ".cache");
+  llvm::sys::path::append(Result, "clangd");
+  llvm::sys::path::append(Result, "module_files");
+
+  llvm::sys::path::append(Result, RequiredPrefixDir);
+
+  llvm::sys::fs::create_directories(Result, /*IgnoreExisting=*/true);
+
+  return Result;
+}
+
+/// Get the absolute path for the filename from the compile command.
+llvm::SmallString<128> getAbsolutePath(const tooling::CompileCommand &Cmd) {
+  llvm::SmallString<128> AbsolutePath;
+  if (llvm::sys::path::is_absolute(Cmd.Filename)) {
+AbsolutePath = Cmd.Filename;
+  } else {
+AbsolutePath = Cmd.Directory;
+llvm::sys::path::append(AbsolutePath, Cmd.Filename);
+llvm::sys::path::remove_dots(AbsolutePath, true);
+  }
+  return AbsolutePath;
+}
+
+/// Get a unique module file path under \param ModuleFilesPrefix.
+std::string getUniqueModuleFilePath(StringRef ModuleName,
+PathRef ModuleFilesPrefix) {
+  llvm::SmallString<256> ModuleFilePattern(ModuleFilesPrefix);
+  auto [PrimaryModuleName, PartitionName] = ModuleName.split(':');
+  llvm::sys::path::append(ModuleFilePattern, PrimaryModuleName);
+  if (!PartitionName.empty()) {
+ModuleFilePattern.append("-");
+ModuleFilePattern.append(PartitionName);
+  }
+
+  ModuleFilePattern.append("-%%-%%-%%-%%-%%-%%");
+  ModuleFilePattern.append(".pcm");
+
+  llvm::SmallString<256> ModuleFilePath;
+  llvm::sys::fs::createUniquePath(ModuleFilePattern, ModuleFilePath,
+  /*MakeAbsolute=*/false);
+
+  return (std::string)ModuleFilePath;
+}
+} // namespace
+
+bool ModulesBuilder::buildModuleFile(StringRef ModuleName,
+ const ThreadsafeFS *TFS,
+ std::shared_ptr MDB,
+ PathRef ModuleFilesPrefix,
+ PrerequisiteModules &BuiltModuleFiles) {
+  if (BuiltModuleFiles.isModuleUnitBuilt(ModuleName))
+return true;
+
+  PathRef ModuleUnitFileName = MDB->getSourceForModuleName(ModuleName);
+  /// It is possible that we're meeting third party modules (modules whose
+  /// source are not in the project. e.g, the std module may be a third-party
+  /// module for most project) or something wrong with the implementation of
+  /// ProjectModules.
+  /// FIXME: How should we treat third party modules here? If we want to ignore
+  /// third party modules, we should return true instead of false here.
+  /// Currently we simply bail out.
+  if (ModuleUnitFileName.empty())
+return false;
+
+  for (auto &RequiredModuleName : MDB->getRequiredModules(ModuleUnitFileName)) 
{
+// Return early if there are errors building the module file.
+if (!buildModuleFile(RequiredModuleName, TFS, MDB, ModuleFilesPrefix,
+ BuiltModuleFiles)) {
+  log("Failed to build module {0}", RequiredModuleName);
+  return false;
+}
+  }
+
+  auto Cmd = CDB.getCompileCommand(ModuleUnitFileName);
+  if (!Cmd)
+return false;
+
+  std::string ModuleFileName =
+  getUniqueModuleFilePath(ModuleName, M

[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-26 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,106 @@
+//===-- ModuleDependencyScanner.h *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULEDEPENDENCYSCANNER_H
+
+#include "GlobalCompilationDatabase.h"
+#include "support/Path.h"
+#include "support/ThreadsafeFS.h"
+
+#include "clang/Tooling/DependencyScanning/DependencyScanningService.h"
+#include "clang/Tooling/DependencyScanning/DependencyScanningTool.h"
+
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/StringMap.h"
+
+namespace clang {
+namespace clangd {
+
+/// A scanner to query the dependency information for C++20 Modules.
+///
+/// The scanner can scan a single file with `scan(PathRef)` member function
+/// or scan the whole project with `globalScan(PathRef)` member function. See
+/// the comments of `globalScan` to see the details.
+///
+/// ModuleDependencyScanner should only be used via ScanningAllProjectModules.
+///
+/// The ModuleDependencyScanner can get the directly required module name for a
+/// specific source file. Also the ModuleDependencyScanner can get the source
+/// file declaring a specific module name.
+///
+/// IMPORTANT NOTE: we assume that every module unit is only declared once in a
+/// source file in the project. But the assumption is not strictly true even
+/// besides the invalid projects. The language specification requires that 
every
+/// module unit should be unique in a valid program. But a project can contain
+/// multiple programs. Then it is valid that we can have multiple source files
+/// declaring the same module in a project as long as these source files don't
+/// interere with each other.`
+class ModuleDependencyScanner {
+public:
+  ModuleDependencyScanner(const GlobalCompilationDatabase &CDB,
+  const ThreadsafeFS &TFS)
+  : CDB(CDB), TFS(TFS),
+Service(tooling::dependencies::ScanningMode::CanonicalPreprocessing,
+tooling::dependencies::ScanningOutputFormat::P1689) {}
+
+  // The scanned modules dependency information for a specific source file.
+  struct ModuleDependencyInfo {
+// The name of the module if the file is a module unit.
+std::optional ModuleName;
+// A list of names for the modules that the file directly depends.
+std::vector RequiredModules;
+  };
+
+  /// Scanning the single file specified by \param FilePath.
+  /// NOTE: This is only used by unittests for external uses.
+  std::optional scan(PathRef FilePath);
+
+  /// Scanning every source file in the current project to get the
+  ///  to  map.
+  /// It looks unefficiency to scan the whole project especially for
+  /// every version of every file!
+  /// TODO: We should find an efficient method to get the 
+  /// to  map. We can make it either by providing
+  /// a global module dependency scanner to monitor every file. Or we
+  /// can simply require the build systems (or even if the end users)
+  /// to provide the map.
+  void globalScan(const std::vector &AllFiles);
+  bool isGlobalScanned() const { return GlobalScanned; }

ChuanqiXu9 wrote:

It was majorly for efficiency. But as we mentioned multiple times, the 
efficiency is not a goal for the first version (it is expected to be slow 
already) and let's improve that in the following patches. So I'd like to remove 
the interface as you suggested. 

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-26 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,71 @@
+//===- ModulesBuilder.h --*- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// Experimental support for C++20 Modules.
+//
+// Currently we simplify the implementations by preventing reusing module files
+// across different versions and different source files. But this is clearly a
+// waste of time and space in the end of the day.
+//
+// FIXME: Supporting reusing module files across different versions and
+// different source files.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULES_BUILDER_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULES_BUILDER_H
+
+#include "GlobalCompilationDatabase.h"
+#include "ProjectModules.h"
+
+#include "support/Path.h"
+#include "support/ThreadsafeFS.h"
+
+#include "llvm/ADT/SmallString.h"
+
+#include 
+
+namespace clang {
+namespace clangd {
+
+class PrerequisiteModules;
+
+/// This class handles building module files for a given source file.
+///
+/// In the future, we want the class to manage the module files acorss
+/// different versions and different source files.
+class ModulesBuilder {
+public:
+  ModulesBuilder() = delete;
+
+  ModulesBuilder(const GlobalCompilationDatabase &CDB) : CDB(CDB) {}
+
+  ModulesBuilder(const ModulesBuilder &) = delete;
+  ModulesBuilder(ModulesBuilder &&) = delete;
+
+  ModulesBuilder &operator=(const ModulesBuilder &) = delete;
+  ModulesBuilder &operator=(ModulesBuilder &&) = delete;
+
+  ~ModulesBuilder() = default;
+
+  std::unique_ptr
+  buildPrerequisiteModulesFor(PathRef File, const ThreadsafeFS *TFS);
+
+private:
+  bool buildModuleFile(StringRef ModuleName, const ThreadsafeFS *TFS,

ChuanqiXu9 wrote:

Done

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-26 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,71 @@
+//===- ModulesBuilder.h --*- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// Experimental support for C++20 Modules.
+//
+// Currently we simplify the implementations by preventing reusing module files
+// across different versions and different source files. But this is clearly a
+// waste of time and space in the end of the day.
+//
+// FIXME: Supporting reusing module files across different versions and
+// different source files.
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULES_BUILDER_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_MODULES_BUILDER_H
+
+#include "GlobalCompilationDatabase.h"
+#include "ProjectModules.h"
+
+#include "support/Path.h"
+#include "support/ThreadsafeFS.h"
+
+#include "llvm/ADT/SmallString.h"
+
+#include 
+
+namespace clang {
+namespace clangd {
+
+class PrerequisiteModules;
+
+/// This class handles building module files for a given source file.
+///
+/// In the future, we want the class to manage the module files acorss
+/// different versions and different source files.
+class ModulesBuilder {
+public:
+  ModulesBuilder() = delete;
+
+  ModulesBuilder(const GlobalCompilationDatabase &CDB) : CDB(CDB) {}
+
+  ModulesBuilder(const ModulesBuilder &) = delete;
+  ModulesBuilder(ModulesBuilder &&) = delete;
+
+  ModulesBuilder &operator=(const ModulesBuilder &) = delete;
+  ModulesBuilder &operator=(ModulesBuilder &&) = delete;

ChuanqiXu9 wrote:

Primarily a conservative design. Since this is owned by the ClangdLSPServer, 
and it looks like we won't copy or move the server. Then it is safe to mark it 
as non-copyable and non-movable. It may be easy to convert a non-moveable and 
non-copyable to the opposite. But it is not the case vice versa. 

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-26 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,339 @@
+//===- ModulesBuilder.cpp *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ModulesBuilder.h"
+#include "PrerequisiteModules.h"
+#include "support/Logger.h"
+
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/FrontendActions.h"
+
+namespace clang {
+namespace clangd {
+
+namespace {
+
+/// Get or create a path to store module files. Generally it should be:
+///
+///   project_root/.cache/clangd/module_files/{RequiredPrefixDir}/.
+///
+/// \param MainFile is used to get the root of the project from global
+/// compilation database. \param RequiredPrefixDir is used to get the user
+/// defined prefix for module files. This is useful when we want to seperate
+/// module files. e.g., we want to build module files for the same module unit
+/// `a.cppm` with 2 different users `b.cpp` and `c.cpp` and we don't want the
+/// module file for `b.cpp` be conflict with the module files for `c.cpp`. Then
+/// we can put the 2 module files into different dirs like:
+///
+///   project_root/.cache/clangd/module_files/b.cpp/a.pcm
+///   project_root/.cache/clangd/module_files/c.cpp/a.pcm
+llvm::SmallString<256> getModuleFilesPath(PathRef MainFile,
+  const GlobalCompilationDatabase &CDB,
+  StringRef RequiredPrefixDir) {
+  std::optional PI = CDB.getProjectInfo(MainFile);
+  if (!PI)
+return {};
+
+  // FIXME: PI->SourceRoot may be empty, depending on the CDB strategy.
+  llvm::SmallString<256> Result(PI->SourceRoot);
+
+  llvm::sys::path::append(Result, ".cache");
+  llvm::sys::path::append(Result, "clangd");
+  llvm::sys::path::append(Result, "module_files");
+
+  llvm::sys::path::append(Result, RequiredPrefixDir);
+
+  llvm::sys::fs::create_directories(Result, /*IgnoreExisting=*/true);
+
+  return Result;
+}
+
+/// Get the absolute path for the filename from the compile command.
+llvm::SmallString<128> getAbsolutePath(const tooling::CompileCommand &Cmd) {
+  llvm::SmallString<128> AbsolutePath;
+  if (llvm::sys::path::is_absolute(Cmd.Filename)) {
+AbsolutePath = Cmd.Filename;
+  } else {
+AbsolutePath = Cmd.Directory;
+llvm::sys::path::append(AbsolutePath, Cmd.Filename);
+llvm::sys::path::remove_dots(AbsolutePath, true);
+  }
+  return AbsolutePath;
+}
+
+/// Get a unique module file path under \param ModuleFilesPrefix.
+std::string getUniqueModuleFilePath(StringRef ModuleName,
+PathRef ModuleFilesPrefix) {
+  llvm::SmallString<256> ModuleFilePattern(ModuleFilesPrefix);
+  auto [PrimaryModuleName, PartitionName] = ModuleName.split(':');
+  llvm::sys::path::append(ModuleFilePattern, PrimaryModuleName);
+  if (!PartitionName.empty()) {
+ModuleFilePattern.append("-");
+ModuleFilePattern.append(PartitionName);
+  }
+
+  ModuleFilePattern.append("-%%-%%-%%-%%-%%-%%");
+  ModuleFilePattern.append(".pcm");
+
+  llvm::SmallString<256> ModuleFilePath;
+  llvm::sys::fs::createUniquePath(ModuleFilePattern, ModuleFilePath,
+  /*MakeAbsolute=*/false);
+
+  return (std::string)ModuleFilePath;
+}
+} // namespace
+
+bool ModulesBuilder::buildModuleFile(StringRef ModuleName,
+ const ThreadsafeFS *TFS,
+ std::shared_ptr MDB,
+ PathRef ModuleFilesPrefix,
+ PrerequisiteModules &BuiltModuleFiles) {
+  if (BuiltModuleFiles.isModuleUnitBuilt(ModuleName))
+return true;
+
+  PathRef ModuleUnitFileName = MDB->getSourceForModuleName(ModuleName);
+  /// It is possible that we're meeting third party modules (modules whose
+  /// source are not in the project. e.g, the std module may be a third-party
+  /// module for most project) or something wrong with the implementation of
+  /// ProjectModules.
+  /// FIXME: How should we treat third party modules here? If we want to ignore
+  /// third party modules, we should return true instead of false here.
+  /// Currently we simply bail out.
+  if (ModuleUnitFileName.empty())
+return false;
+
+  for (auto &RequiredModuleName : MDB->getRequiredModules(ModuleUnitFileName)) 
{
+// Return early if there are errors building the module file.
+if (!buildModuleFile(RequiredModuleName, TFS, MDB, ModuleFilesPrefix,
+ BuiltModuleFiles)) {
+  log("Failed to build module {0}", RequiredModuleName);
+  return false;
+}
+  }
+
+  auto Cmd = CDB.getCompileCommand(ModuleUnitFileName);
+  if (!Cmd)
+return false;
+
+  std::string ModuleFileName =
+  getUniqueModuleFilePath(ModuleName, M

[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-26 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,62 @@
+//===-- ProjectModules.h -*- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ProjectModules.h"
+
+namespace clang {
+namespace clangd {
+
+/// TODO: The existing `ScanningAllProjectModules` is not efficient. See the
+/// comments in ModuleDependencyScanner for detail.
+///
+/// In the future, we wish the build system can provide a well design
+/// compilation database for modules then we can query that new compilation
+/// database directly. Or we need to have a global long-live scanner to detect
+/// the state of each file.
+class ScanningAllProjectModules : public ProjectModules {
+public:
+  ScanningAllProjectModules(std::vector &&AllFiles,
+const GlobalCompilationDatabase &CDB,
+const ThreadsafeFS &TFS)
+  : AllFiles(std::move(AllFiles)), Scanner(CDB, TFS) {}
+
+  ~ScanningAllProjectModules() override = default;
+
+  std::vector getRequiredModules(PathRef File) override {
+return Scanner.getRequiredModules(File);
+  }
+
+  /// RequiredSourceFile is not used intentionally. See the comments of
+  /// ModuleDependencyScanner for detail.
+  PathRef
+  getSourceForModuleName(StringRef ModuleName,
+ PathRef RequiredSourceFile = PathRef()) override {
+if (!Scanner.isGlobalScanned())
+  Scanner.globalScan(AllFiles);
+
+return Scanner.getSourceForModuleName(ModuleName);
+  }
+
+private:
+  std::vector AllFiles;
+
+  ModuleDependencyScanner Scanner;

ChuanqiXu9 wrote:

Done. Good idea. I like it.

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-26 Thread Chuanqi Xu via cfe-commits


@@ -0,0 +1,339 @@
+//===- ModulesBuilder.cpp *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "ModulesBuilder.h"
+#include "PrerequisiteModules.h"
+#include "support/Logger.h"
+
+#include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/FrontendActions.h"
+
+namespace clang {
+namespace clangd {
+
+namespace {
+
+/// Get or create a path to store module files. Generally it should be:
+///
+///   project_root/.cache/clangd/module_files/{RequiredPrefixDir}/.
+///
+/// \param MainFile is used to get the root of the project from global
+/// compilation database. \param RequiredPrefixDir is used to get the user
+/// defined prefix for module files. This is useful when we want to seperate
+/// module files. e.g., we want to build module files for the same module unit
+/// `a.cppm` with 2 different users `b.cpp` and `c.cpp` and we don't want the
+/// module file for `b.cpp` be conflict with the module files for `c.cpp`. Then
+/// we can put the 2 module files into different dirs like:
+///
+///   project_root/.cache/clangd/module_files/b.cpp/a.pcm
+///   project_root/.cache/clangd/module_files/c.cpp/a.pcm
+llvm::SmallString<256> getModuleFilesPath(PathRef MainFile,
+  const GlobalCompilationDatabase &CDB,
+  StringRef RequiredPrefixDir) {
+  std::optional PI = CDB.getProjectInfo(MainFile);
+  if (!PI)
+return {};
+
+  // FIXME: PI->SourceRoot may be empty, depending on the CDB strategy.
+  llvm::SmallString<256> Result(PI->SourceRoot);
+
+  llvm::sys::path::append(Result, ".cache");
+  llvm::sys::path::append(Result, "clangd");
+  llvm::sys::path::append(Result, "module_files");
+
+  llvm::sys::path::append(Result, RequiredPrefixDir);
+
+  llvm::sys::fs::create_directories(Result, /*IgnoreExisting=*/true);
+
+  return Result;
+}
+
+/// Get the absolute path for the filename from the compile command.
+llvm::SmallString<128> getAbsolutePath(const tooling::CompileCommand &Cmd) {
+  llvm::SmallString<128> AbsolutePath;
+  if (llvm::sys::path::is_absolute(Cmd.Filename)) {
+AbsolutePath = Cmd.Filename;
+  } else {
+AbsolutePath = Cmd.Directory;
+llvm::sys::path::append(AbsolutePath, Cmd.Filename);
+llvm::sys::path::remove_dots(AbsolutePath, true);
+  }
+  return AbsolutePath;
+}
+
+/// Get a unique module file path under \param ModuleFilesPrefix.
+std::string getUniqueModuleFilePath(StringRef ModuleName,
+PathRef ModuleFilesPrefix) {
+  llvm::SmallString<256> ModuleFilePattern(ModuleFilesPrefix);
+  auto [PrimaryModuleName, PartitionName] = ModuleName.split(':');
+  llvm::sys::path::append(ModuleFilePattern, PrimaryModuleName);
+  if (!PartitionName.empty()) {
+ModuleFilePattern.append("-");
+ModuleFilePattern.append(PartitionName);
+  }
+
+  ModuleFilePattern.append("-%%-%%-%%-%%-%%-%%");
+  ModuleFilePattern.append(".pcm");
+
+  llvm::SmallString<256> ModuleFilePath;
+  llvm::sys::fs::createUniquePath(ModuleFilePattern, ModuleFilePath,
+  /*MakeAbsolute=*/false);
+
+  return (std::string)ModuleFilePath;
+}
+} // namespace
+
+bool ModulesBuilder::buildModuleFile(StringRef ModuleName,
+ const ThreadsafeFS *TFS,
+ std::shared_ptr MDB,
+ PathRef ModuleFilesPrefix,
+ PrerequisiteModules &BuiltModuleFiles) {
+  if (BuiltModuleFiles.isModuleUnitBuilt(ModuleName))
+return true;
+
+  PathRef ModuleUnitFileName = MDB->getSourceForModuleName(ModuleName);
+  /// It is possible that we're meeting third party modules (modules whose
+  /// source are not in the project. e.g, the std module may be a third-party
+  /// module for most project) or something wrong with the implementation of
+  /// ProjectModules.
+  /// FIXME: How should we treat third party modules here? If we want to ignore
+  /// third party modules, we should return true instead of false here.
+  /// Currently we simply bail out.
+  if (ModuleUnitFileName.empty())
+return false;
+
+  for (auto &RequiredModuleName : MDB->getRequiredModules(ModuleUnitFileName)) 
{
+// Return early if there are errors building the module file.
+if (!buildModuleFile(RequiredModuleName, TFS, MDB, ModuleFilesPrefix,
+ BuiltModuleFiles)) {
+  log("Failed to build module {0}", RequiredModuleName);
+  return false;
+}
+  }
+
+  auto Cmd = CDB.getCompileCommand(ModuleUnitFileName);
+  if (!Cmd)
+return false;
+
+  std::string ModuleFileName =
+  getUniqueModuleFilePath(ModuleName, M

[clang] [Clang] Add support for [[msvc::noinline]] attribute. (PR #91720)

2024-05-26 Thread Xu Zhang via cfe-commits

simonzgx wrote:

Hi @erichkeane , can this patch be merged? Or if there is anything else I need 
to do, please let me know.

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


[clang-tools-extra] [clangd] [C++20] [Modules] Introduce initial support for C++20 Modules (PR #66462)

2024-05-26 Thread Chuanqi Xu via cfe-commits




ChuanqiXu9 wrote:

Oh, I don't know why I didn't get this in files page so I missed this.

But since we can't get rid of writing/reading the modules actually in 
`ModulesBuilder` (Or it is pretty hard). Then it looks not so worthy to 
introduce the layer. 

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


[clang] [compiler-rt] [lldb] [llvm] [Support] Remove terminfo dependency (PR #92865)

2024-05-26 Thread via cfe-commits

gulfemsavrun wrote:

We started seeing the following issue after this patch in our Clang toolchain 
builders: 
```
1448/1517](45) Linking CXX executable unittests/LineEditor/LineEditorTests
FAILED: unittests/LineEditor/LineEditorTests 
: && /b/s/w/ir/x/w/cipd/bin/clang++ --sysroot=/b/s/w/ir/x/w/cipd/linux 
-stdlib=libc++ -fPIC -fno-semantic-interposition -fvisibility-inlines-hidden 
-Werror=date-time -Werror=unguarded-availability-new -Wall -Wextra 
-Wno-unused-parameter -Wwrite-strings -Wcast-qual -Wmissing-field-initializers 
-pedantic -Wno-long-long -Wc++98-compat-extra-semi -Wimplicit-fallthrough 
-Wcovered-switch-default -Wno-noexcept-type -Wnon-virtual-dtor 
-Wdelete-non-virtual-dtor -Wsuggest-override -Wno-comment -Wstring-conversion 
-Wmisleading-indentation -Wctad-maybe-unsupported -fdiagnostics-color 
-ffunction-sections -fdata-sections -ffat-lto-objects 
-ffile-prefix-map=/b/s/w/ir/x/w/llvm_build=../llvm-llvm-project 
-ffile-prefix-map=/b/s/w/ir/x/w/llvm-llvm-project/= -no-canonical-prefixes -O3 
-DNDEBUG -static-libstdc++ -stdlib=libc++ -static-libstdc++ -fuse-ld=lld 
-Wl,--color-diagnostics -ffat-lto-objects-Wl,--gc-sections 
unittests/LineEditor/CMakeFiles/LineEditorTests.dir/LineEditor.cpp.o -o 
unittests/LineEditor/LineEditorTests  lib/libLLVMLineEditor.a  
lib/libLLVMSupport.a  lib/libLLVMSupport.a  -lpthread  lib/libllvm_gtest_main.a 
 lib/libllvm_gtest.a  -lpthread  /b/s/w/ir/x/w/libedit_install/lib/libedit.a  
lib/libLLVMSupport.a  -lrt  -ldl  -lpthread  -lm  
/b/s/w/ir/x/w/zlib_install_target/lib/libz.a  
/b/s/w/ir/x/w/zstd_install/lib/libzstd.a  -pthread  lib/libLLVMDemangle.a  
-lpthread && :
ld.lld: error: undefined symbol: tgetent
>>> referenced by terminal.c
>>>   terminal.o:(terminal_set) in archive 
>>> /b/s/w/ir/x/w/libedit_install/lib/libedit.a
```
https://logs.chromium.org/logs/fuchsia/buildbucket/cr-buildbucket/8747030306803673361/+/u/clang/test/stdout

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


[clang] [clang-format] Add SpacesInParensOption for filtering repeated parens (PR #77522)

2024-05-26 Thread Owen Pan via cfe-commits

https://github.com/owenca edited https://github.com/llvm/llvm-project/pull/77522
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


  1   2   >