[clang] [llvm] [ARM] Emit an error when the hard-float ABI is enabled but can't be used. (PR #111334)

2025-01-01 Thread Ralf Jung via cfe-commits

RalfJung wrote:

RISC-V has similar checks here:

https://github.com/llvm/llvm-project/blob/ed572f2003275da8e06a634b4d6658b7921e8334/llvm/lib/Target/RISCV/RISCVISelLowering.cpp#L88-L100

So maybe the ARM checks could be added in a similar place? RISC-V handles ABI 
variants in a very clean way, and it does seem to work in practice too, so it'd 
be a good model for other architectures to follow.


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


[clang] [llvm] [ARM] Emit an error when the hard-float ABI is enabled but can't be used. (PR #111334)

2025-01-01 Thread Ralf Jung via cfe-commits

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


[clang] [llvm] [ARM] Emit an error when the hard-float ABI is enabled but can't be used. (PR #111334)

2025-01-01 Thread Ralf Jung via cfe-commits

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


[clang] [clang-tools-extra] [libcxx] [llvm] [libc++] implement views::concat (PR #120920)

2025-01-01 Thread via cfe-commits


@@ -0,0 +1,623 @@
+// -*- 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 _LIBCPP___RANGES_CONCAT_VIEW_H
+#define _LIBCPP___RANGES_CONCAT_VIEW_H
+
+#include <__algorithm/ranges_find_if.h>
+#include <__assert>
+#include <__concepts/common_reference_with.h>
+#include <__concepts/constructible.h>
+#include <__concepts/convertible_to.h>
+#include <__concepts/copyable.h>
+#include <__concepts/derived_from.h>
+#include <__concepts/equality_comparable.h>
+#include <__concepts/swappable.h>
+#include <__config>
+#include <__functional/bind_back.h>
+#include <__functional/invoke.h>
+#include <__functional/reference_wrapper.h>
+#include <__iterator/concepts.h>
+#include <__iterator/default_sentinel.h>
+#include <__iterator/distance.h>
+#include <__iterator/incrementable_traits.h>
+#include <__iterator/iter_move.h>
+#include <__iterator/iter_swap.h>
+#include <__iterator/iterator_traits.h>
+#include <__iterator/next.h>
+#include <__memory/addressof.h>
+#include <__ranges/access.h>
+#include <__ranges/all.h>
+#include <__ranges/concepts.h>
+#include <__ranges/movable_box.h>
+#include <__ranges/non_propagating_cache.h>
+#include <__ranges/range_adaptor.h>
+#include <__ranges/size.h>
+#include <__ranges/view_interface.h>
+#include <__ranges/zip_view.h>
+#include <__type_traits/conditional.h>
+#include <__type_traits/decay.h>
+#include <__type_traits/is_nothrow_constructible.h>
+#include <__type_traits/is_nothrow_convertible.h>
+#include <__type_traits/is_object.h>
+#include <__type_traits/make_unsigned.h>
+#include <__type_traits/maybe_const.h>
+#include <__utility/forward.h>
+#include <__utility/in_place.h>
+#include <__utility/move.h>
+#include 
+#include 
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#  pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER >= 26
+
+namespace ranges {
+
+template 
+struct __extract_last : __extract_last<_Tail...> {};

huixie90 wrote:

when i first wrote P2542R0, my reference implementation was based on C++20. now 
that lots of new features have been implemented in clang/gcc, i think you might 
be able to make use of them. For example, you might be able to use pack 
indexing to replace most of the meta programming here

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


[clang] [Clang] emit -Wignored-qualifiers diagnostic for cv-qualified base classes (PR #121419)

2025-01-01 Thread Oleksandr T. via cfe-commits

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

>From f3b5fc2a32fe2da301779048e3afbbeb7af8cb3c Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Wed, 1 Jan 2025 01:47:17 +0200
Subject: [PATCH] [Clang] emit -Wignored-qualifiers diagnostic for cv-qualified
 base classes

---
 clang/docs/ReleaseNotes.rst|  1 +
 clang/include/clang/Basic/DiagnosticSemaKinds.td   |  4 
 clang/lib/Sema/SemaDeclCXX.cpp |  9 +
 clang/test/CXX/drs/cwg4xx.cpp  |  3 ++-
 clang/test/CXX/special/class.inhctor/elsewhere.cpp |  5 +++--
 clang/test/Sema/GH70594.cpp| 13 +++--
 clang/test/SemaCXX/class-base-member-init.cpp  |  3 ++-
 clang/test/SemaCXX/warn-base-type-qualifiers.cpp   | 11 +++
 8 files changed, 39 insertions(+), 10 deletions(-)
 create mode 100644 clang/test/SemaCXX/warn-base-type-qualifiers.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b7da12bcf65818..659f0ebd97fc46 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -733,6 +733,7 @@ Improvements to Clang's diagnostics
   scope.Unlock();
   require(scope); // Warning!  Requires mu1.
 }
+- Clang now emits a ``-Wignored-qualifiers`` diagnostic when a base class 
includes cv-qualifiers (#GH55474).
 
 Improvements to Clang's time-trace
 --
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 330ae045616aba..f2d56ce7c69f95 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -487,6 +487,10 @@ def err_noreturn_non_function : Error<
 def warn_qual_return_type : Warning<
   "'%0' type qualifier%s1 on return type %plural{1:has|:have}1 no effect">,
   InGroup, DefaultIgnore;
+def ext_warn_qual_base_type : ExtWarn<
+  "'%0' qualifier%s1 on base class type %2 have no effect">,
+  InGroup;
+
 def warn_deprecated_redundant_constexpr_static_def : Warning<
   "out-of-line definition of constexpr static data member is redundant "
   "in C++17 and is deprecated">,
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index c5a72cf812ebc9..b57153a002c696 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -2655,6 +2655,15 @@ CXXBaseSpecifier *Sema::CheckBaseSpecifier(CXXRecordDecl 
*Class,
   return nullptr;
 }
 
+if (BaseType.hasQualifiers()) {
+  auto Quals =
+  BaseType.getQualifiers().getAsString(Context.getPrintingPolicy());
+  Diag(BaseLoc, diag::ext_warn_qual_base_type)
+  << Quals << std::count(Quals.begin(), Quals.end(), ' ') + 1
+  << BaseType;
+  Diag(BaseLoc, diag::note_base_class_specified_here) << BaseType;
+}
+
 // For the MS ABI, propagate DLL attributes to base class templates.
 if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
 Context.getTargetInfo().getTriple().isPS()) {
diff --git a/clang/test/CXX/drs/cwg4xx.cpp b/clang/test/CXX/drs/cwg4xx.cpp
index 825065840f1181..992b1172b9ddf3 100644
--- a/clang/test/CXX/drs/cwg4xx.cpp
+++ b/clang/test/CXX/drs/cwg4xx.cpp
@@ -1309,7 +1309,8 @@ namespace cwg484 { // cwg484: yes
   }
   CA::A() {}
 
-  struct B : CA {
+  struct B : CA { // expected-error {{'const' qualifier on base class type 
'CA' (aka 'const cwg484::A') have no effect}} \
+  // expected-note {{base class 'CA' (aka 'const cwg484::A') 
specified here}}
 B() : CA() {}
 void f() { return CA::f(); }
   };
diff --git a/clang/test/CXX/special/class.inhctor/elsewhere.cpp 
b/clang/test/CXX/special/class.inhctor/elsewhere.cpp
index f86f4b86faa7d7..079422fd99d98a 100644
--- a/clang/test/CXX/special/class.inhctor/elsewhere.cpp
+++ b/clang/test/CXX/special/class.inhctor/elsewhere.cpp
@@ -57,9 +57,10 @@ template struct F : D {
 F fb; // expected-note {{here}}
 
 template
-struct G : T {
+struct G : T {// expected-warning {{'const' qualifier on base class 
type 'const B1' have no effect}} \
+  // expected-note {{base class 'const B1' specified here}}
   using T::T;
   G(int &) : G(0) {}
 };
 G g(123);
-G g2(123);
+G g2(123); // expected-note {{in instantiation of template class 
'G' requested here}}
diff --git a/clang/test/Sema/GH70594.cpp b/clang/test/Sema/GH70594.cpp
index ce98e9b12b5cba..91ec31f6b053cb 100644
--- a/clang/test/Sema/GH70594.cpp
+++ b/clang/test/Sema/GH70594.cpp
@@ -1,12 +1,11 @@
 // RUN: %clang_cc1 -fsyntax-only -std=c++11 %s -verify
 // RUN: %clang_cc1 -fsyntax-only -std=c++23 %s -verify
 
-// expected-no-diagnostics
-
 struct A {};
 using CA = const A;
 
-struct S1 : CA {
+struct S1 : CA {   // expected-warning {{'const' qualifier on base 
class type 'CA' (aka 'const A') have no effect}} \
+   // expected-note {{base class 'CA' (aka 'const A') 
specified here}}

[clang] [Clang][ASTMatcher] Add `dependentTemplateSpecializationType` AST mat… (PR #121435)

2025-01-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: kefan cao (caokefan)


Changes

Add AST Matcher for `dependentTemplateSpecializationType`
Fixes:https://github.com/llvm/llvm-project/issues/121307

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


7 Files Affected:

- (modified) clang/docs/LibASTMatchersReference.html (+11) 
- (modified) clang/docs/ReleaseNotes.rst (+2) 
- (modified) clang/include/clang/ASTMatchers/ASTMatchers.h (+12) 
- (modified) clang/lib/ASTMatchers/ASTMatchersInternal.cpp (+2) 
- (modified) clang/lib/ASTMatchers/Dynamic/Registry.cpp (+1) 
- (modified) clang/unittests/AST/ASTImporterTest.cpp (-4) 
- (modified) clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp (+15) 


``diff
diff --git a/clang/docs/LibASTMatchersReference.html 
b/clang/docs/LibASTMatchersReference.html
index 8564f2650d205f..428a3385e2f39e 100644
--- a/clang/docs/LibASTMatchersReference.html
+++ b/clang/docs/LibASTMatchersReference.html
@@ -2546,6 +2546,17 @@ Node Matchers
   };
 
 
+MatcherType>dependentTemplateSpecializationTypeMatcherDependentTemplateSpecializationType>...
+Matches dependent template 
specialization types.
+
+Example matches  A::template B
+
+  template struct A;
+  template struct declToImport {
+typename A::template B a;
+  };
+
+
 MatcherType>deducedTemplateSpecializationTypeMatcherDeducedTemplateSpecializationType>...
 Matches C++17 deduced template 
specialization types, e.g. deduced class
 template types.
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2a688a677294f8..e17d22d1e1cdcf 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -1113,6 +1113,8 @@ AST Matchers
 
 - Add ``dependentNameType`` matcher to match a dependent name type.
 
+- Add ``dependentTemplateSpecializationType`` matcher to match dependent 
template specialization types.
+
 clang-format
 
 
diff --git a/clang/include/clang/ASTMatchers/ASTMatchers.h 
b/clang/include/clang/ASTMatchers/ASTMatchers.h
index 9a046714068a51..1b678f30c5d01c 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -7721,6 +7721,18 @@ AST_MATCHER_P(DecayedType, hasDecayedType, 
internal::Matcher,
 /// \endcode
 extern const AstTypeMatcher dependentNameType;
 
+/// Matches dependent template specialization types
+///
+/// Example matches  A::template B
+/// \code
+///   template struct A;
+///   template struct declToImport {
+/// typename A::template B a;
+///   };
+/// \endcode
+extern const AstTypeMatcher
+dependentTemplateSpecializationType;
+
 /// Matches declarations whose declaration context, interpreted as a
 /// Decl, matches \c InnerMatcher.
 ///
diff --git a/clang/lib/ASTMatchers/ASTMatchersInternal.cpp 
b/clang/lib/ASTMatchers/ASTMatchersInternal.cpp
index a47633bf4bae24..9c7943a98d6523 100644
--- a/clang/lib/ASTMatchers/ASTMatchersInternal.cpp
+++ b/clang/lib/ASTMatchers/ASTMatchersInternal.cpp
@@ -1109,6 +1109,8 @@ const AstTypeMatcher 
templateTypeParmType;
 const AstTypeMatcher injectedClassNameType;
 const AstTypeMatcher decayedType;
 const AstTypeMatcher dependentNameType;
+const AstTypeMatcher
+dependentTemplateSpecializationType;
 AST_TYPELOC_TRAVERSE_MATCHER_DEF(hasElementType,
  AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType,
  ComplexType));
diff --git a/clang/lib/ASTMatchers/Dynamic/Registry.cpp 
b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
index bfdee412c53281..97e6bbc093fe46 100644
--- a/clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -224,6 +224,7 @@ RegistryMaps::RegistryMaps() {
   REGISTER_MATCHER(declRefExpr);
   REGISTER_MATCHER(dependentNameType);
   REGISTER_MATCHER(dependentScopeDeclRefExpr);
+  REGISTER_MATCHER(dependentTemplateSpecializationType);
   REGISTER_MATCHER(declStmt);
   REGISTER_MATCHER(declaratorDecl);
   REGISTER_MATCHER(decltypeType);
diff --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index ee1d896f1ca6dc..d197d30df3adf5 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -763,10 +763,6 @@ TEST_P(ImportType, ImportPackExpansion) {
implicitCastExpr(has(declRefExpr();
 }
 
-const internal::VariadicDynCastAllOfMatcher
-dependentTemplateSpecializationType;
-
 TEST_P(ImportType, ImportDependentTemplateSpecialization) {
   MatchVerifier Verifier;
   testImport("template"
diff --git a/clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp 
b/clang/unittests/ASTMatchers/ASTMatc

[clang] [Clang][ASTMatcher] Add `dependentTemplateSpecializationType` AST mat… (PR #121435)

2025-01-01 Thread kefan cao via cfe-commits

https://github.com/caokefan created 
https://github.com/llvm/llvm-project/pull/121435

Add AST Matcher for `dependentTemplateSpecializationType`
Fixes:https://github.com/llvm/llvm-project/issues/121307

>From a70a9e55f99accc659b23d1a76888e151bdd8f73 Mon Sep 17 00:00:00 2001
From: Kefan Cao <45958009+caoke...@users.noreply.github.com>
Date: Tue, 31 Dec 2024 09:17:18 +
Subject: [PATCH] [Clang][ASTMatcher] Add `dependentTemplateSpecializationType`
 AST matcher

---
 clang/docs/LibASTMatchersReference.html   | 11 +++
 clang/docs/ReleaseNotes.rst   |  2 ++
 clang/include/clang/ASTMatchers/ASTMatchers.h | 12 
 clang/lib/ASTMatchers/ASTMatchersInternal.cpp |  2 ++
 clang/lib/ASTMatchers/Dynamic/Registry.cpp|  1 +
 clang/unittests/AST/ASTImporterTest.cpp   |  4 
 .../unittests/ASTMatchers/ASTMatchersNodeTest.cpp | 15 +++
 7 files changed, 43 insertions(+), 4 deletions(-)

diff --git a/clang/docs/LibASTMatchersReference.html 
b/clang/docs/LibASTMatchersReference.html
index 8564f2650d205f..428a3385e2f39e 100644
--- a/clang/docs/LibASTMatchersReference.html
+++ b/clang/docs/LibASTMatchersReference.html
@@ -2546,6 +2546,17 @@ Node Matchers
   };
 
 
+MatcherType>dependentTemplateSpecializationTypeMatcherDependentTemplateSpecializationType>...
+Matches dependent template 
specialization types.
+
+Example matches  A::template B
+
+  template struct A;
+  template struct declToImport {
+typename A::template B a;
+  };
+
+
 MatcherType>deducedTemplateSpecializationTypeMatcherDeducedTemplateSpecializationType>...
 Matches C++17 deduced template 
specialization types, e.g. deduced class
 template types.
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2a688a677294f8..e17d22d1e1cdcf 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -1113,6 +1113,8 @@ AST Matchers
 
 - Add ``dependentNameType`` matcher to match a dependent name type.
 
+- Add ``dependentTemplateSpecializationType`` matcher to match dependent 
template specialization types.
+
 clang-format
 
 
diff --git a/clang/include/clang/ASTMatchers/ASTMatchers.h 
b/clang/include/clang/ASTMatchers/ASTMatchers.h
index 9a046714068a51..1b678f30c5d01c 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -7721,6 +7721,18 @@ AST_MATCHER_P(DecayedType, hasDecayedType, 
internal::Matcher,
 /// \endcode
 extern const AstTypeMatcher dependentNameType;
 
+/// Matches dependent template specialization types
+///
+/// Example matches  A::template B
+/// \code
+///   template struct A;
+///   template struct declToImport {
+/// typename A::template B a;
+///   };
+/// \endcode
+extern const AstTypeMatcher
+dependentTemplateSpecializationType;
+
 /// Matches declarations whose declaration context, interpreted as a
 /// Decl, matches \c InnerMatcher.
 ///
diff --git a/clang/lib/ASTMatchers/ASTMatchersInternal.cpp 
b/clang/lib/ASTMatchers/ASTMatchersInternal.cpp
index a47633bf4bae24..9c7943a98d6523 100644
--- a/clang/lib/ASTMatchers/ASTMatchersInternal.cpp
+++ b/clang/lib/ASTMatchers/ASTMatchersInternal.cpp
@@ -1109,6 +1109,8 @@ const AstTypeMatcher 
templateTypeParmType;
 const AstTypeMatcher injectedClassNameType;
 const AstTypeMatcher decayedType;
 const AstTypeMatcher dependentNameType;
+const AstTypeMatcher
+dependentTemplateSpecializationType;
 AST_TYPELOC_TRAVERSE_MATCHER_DEF(hasElementType,
  AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType,
  ComplexType));
diff --git a/clang/lib/ASTMatchers/Dynamic/Registry.cpp 
b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
index bfdee412c53281..97e6bbc093fe46 100644
--- a/clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -224,6 +224,7 @@ RegistryMaps::RegistryMaps() {
   REGISTER_MATCHER(declRefExpr);
   REGISTER_MATCHER(dependentNameType);
   REGISTER_MATCHER(dependentScopeDeclRefExpr);
+  REGISTER_MATCHER(dependentTemplateSpecializationType);
   REGISTER_MATCHER(declStmt);
   REGISTER_MATCHER(declaratorDecl);
   REGISTER_MATCHER(decltypeType);
diff --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index ee1d896f1ca6dc..d197d30df3adf5 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -763,10 +763,6 @@ TEST_P(ImportType, ImportPackExpansion) {
implicitCastExpr(has(declRefExpr();
 }
 
-const internal::VariadicDynCastAllOfMatcher
-dependentTemplateSpecializa

[clang] [Clang][ASTMatcher] Add `dependentTemplateSpecializationType` AST mat… (PR #121435)

2025-01-01 Thread via cfe-commits

github-actions[bot] wrote:



Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this 
page.

If this is not working for you, it is probably because you do not have write 
permissions for the repository. In which case you can instead tag reviewers by 
name in a comment by using `@` followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a 
review by "ping"ing the PR by adding a comment “Ping”. The common courtesy 
"ping" rate is once a week. Please remember that you are asking for valuable 
time from other developers.

If you have further questions, they may be answered by the [LLVM GitHub User 
Guide](https://llvm.org/docs/GitHub.html).

You can also ask questions in a comment on this PR, on the [LLVM 
Discord](https://discord.com/invite/xS7Z362) or on the 
[forums](https://discourse.llvm.org/).

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


[clang] Reapply "[Driver][OHOS] Fix lld link issue for OHOS (#118192)" (PR #120159)

2025-01-01 Thread Peng Huang via cfe-commits

phuang wrote:

Thanks for reviewing it. Could you please land it for me? Seems I cannot land 
it.

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


[clang] [clang-format] Support globstar in .clang-format-ignore (PR #121404)

2025-01-01 Thread Owen Pan via cfe-commits


@@ -164,6 +164,41 @@ TEST_F(MatchFilePathTest, Path) {
   EXPECT_FALSE(match("foo\\", R"(foo*\)"));
 }
 
+TEST_F(MatchFilePathTest, Globstar) {
+  EXPECT_TRUE(match("/", "**"));
+  EXPECT_TRUE(match("foo", "**"));
+  EXPECT_TRUE(match("/foo", "**"));
+  EXPECT_TRUE(match("foo/", "**"));
+  EXPECT_TRUE(match("foo/bar", "**"));
+
+  EXPECT_TRUE(match("/", "**/"));
+  EXPECT_TRUE(match("foo/", "**/"));
+  EXPECT_TRUE(match("/foo/", "**/"));
+  EXPECT_TRUE(match("foo/bar/", "**/"));
+
+  EXPECT_TRUE(match("/", "/**"));
+  EXPECT_TRUE(match("/foo", "/**"));
+  EXPECT_TRUE(match("/foo/", "/**"));
+  EXPECT_TRUE(match("/foo/bar", "/**"));
+
+  EXPECT_TRUE(match("foo", "**/foo"));
+  EXPECT_TRUE(match("/foo", "**/foo"));
+  EXPECT_TRUE(match("foo/bar", "**/bar"));
+  EXPECT_TRUE(match("/foo/bar", "**/foo/bar"));
+  EXPECT_TRUE(match("foo/bar/baz", "**/bar/baz"));
+
+  EXPECT_TRUE(match("abc/foo", "abc/**"));
+  EXPECT_TRUE(match("abc/foo/", "abc/**"));
+  EXPECT_TRUE(match("abc/foo/bar", "abc/**"));
+
+  EXPECT_TRUE(match("a/b", "a/**/b"));
+  EXPECT_TRUE(match("a/x/b", "a/**/b"));
+  EXPECT_TRUE(match("a/x/y/b", "a/**/b"));
+
+  EXPECT_FALSE(match("a/x/b", "a**/b"));
+  EXPECT_FALSE(match("a/x/y/b", "a/**b"));

owenca wrote:

```suggestion
  EXPECT_FALSE(match("a/x/b", "a/**b"));
```

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


[clang] [clang-format] Support globstar in .clang-format-ignore (PR #121404)

2025-01-01 Thread Owen Pan via cfe-commits

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/121404

>From 36efaa2849ee6276be5b3c0739f295d0921d1e6e Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Tue, 31 Dec 2024 08:13:53 -0800
Subject: [PATCH 1/3] [clang-format] Support globstar in .clang-format-ignore

Closes #114969.
---
 clang/docs/ClangFormat.rst   |  1 +
 clang/docs/ReleaseNotes.rst  |  1 +
 clang/lib/Format/MatchFilePath.cpp   | 35 ++--
 clang/unittests/Format/MatchFilePathTest.cpp | 35 
 4 files changed, 61 insertions(+), 11 deletions(-)

diff --git a/clang/docs/ClangFormat.rst b/clang/docs/ClangFormat.rst
index c8f1d7f5a77581..e1f677178c00ab 100644
--- a/clang/docs/ClangFormat.rst
+++ b/clang/docs/ClangFormat.rst
@@ -150,6 +150,7 @@ names. It has the following format:
 * Patterns follow the rules specified in `POSIX 2.13.1, 2.13.2, and Rule 1 of
   2.13.3 `_.
+* Bash globstar (``**``) is supported.
 * A pattern is negated if it starts with a bang (``!``).
 
 To match all files in a directory, use e.g. ``foo/bar/*``. To match all files 
in
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b7da12bcf65818..2d59d74ddf35fc 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -1124,6 +1124,7 @@ clang-format
 - Adds ``RemoveEmptyLinesInUnwrappedLines`` option.
 - Adds ``KeepFormFeed`` option and set it to ``true`` for ``GNU`` style.
 - Adds ``AllowShortNamespacesOnASingleLine`` option.
+- Adds support for bash globstar in ``.clang-format-ignore``.
 
 libclang
 
diff --git a/clang/lib/Format/MatchFilePath.cpp 
b/clang/lib/Format/MatchFilePath.cpp
index 062b334dcdd8fd..aca3433dc7fa78 100644
--- a/clang/lib/Format/MatchFilePath.cpp
+++ b/clang/lib/Format/MatchFilePath.cpp
@@ -49,25 +49,38 @@ bool matchFilePath(StringRef Pattern, StringRef FilePath) {
 return false;
   break;
 case '*': {
-  while (++I < EOP && Pattern[I] == '*') { // Skip consecutive stars.
+  const bool MaybeGlobstar = I == 0 || Pattern[I - 1] == Separator;
+  int StarCount = 1;
+  for (; ++I < EOP && Pattern[I] == '*'; ++StarCount) {
+// Skip consecutive stars.
   }
   const auto K = FilePath.find(Separator, J); // Index of next `Separator`.
   const bool NoMoreSeparatorsInFilePath = K == StringRef::npos;
+  bool Globstar = MaybeGlobstar && StarCount == 2;
   if (I == EOP) // `Pattern` ends with a star.
-return NoMoreSeparatorsInFilePath;
-  // `Pattern` ends with a lone backslash.
-  if (Pattern[I] == '\\' && ++I == EOP)
-return false;
+return Globstar || NoMoreSeparatorsInFilePath;
+  if (Pattern[I] != Separator) {
+Globstar = false;
+// `Pattern` ends with a lone backslash.
+if (Pattern[I] == '\\' && ++I == EOP)
+  return false;
+  }
   // The star is followed by a (possibly escaped) `Separator`.
   if (Pattern[I] == Separator) {
-if (NoMoreSeparatorsInFilePath)
-  return false;
-J = K; // Skip to next `Separator` in `FilePath`.
-break;
+if (!Globstar) {
+  if (NoMoreSeparatorsInFilePath)
+return false;
+  J = K; // Skip to next `Separator` in `FilePath`.
+  break;
+}
+if (I + 1 < EOP &&
+matchFilePath(Pattern.substr(I + 1), FilePath.substr(J))) {
+  return true;
+}
   }
   // Recurse.
-  for (auto Pat = Pattern.substr(I); J < End && FilePath[J] != Separator;
-   ++J) {
+  for (auto Pat = Pattern.substr(I);
+   J < End && (Globstar || FilePath[J] != Separator); ++J) {
 if (matchFilePath(Pat, FilePath.substr(J)))
   return true;
   }
diff --git a/clang/unittests/Format/MatchFilePathTest.cpp 
b/clang/unittests/Format/MatchFilePathTest.cpp
index 28f665635718e5..9876a4583c226a 100644
--- a/clang/unittests/Format/MatchFilePathTest.cpp
+++ b/clang/unittests/Format/MatchFilePathTest.cpp
@@ -164,6 +164,41 @@ TEST_F(MatchFilePathTest, Path) {
   EXPECT_FALSE(match("foo\\", R"(foo*\)"));
 }
 
+TEST_F(MatchFilePathTest, Globstar) {
+  EXPECT_TRUE(match("/", "**"));
+  EXPECT_TRUE(match("foo", "**"));
+  EXPECT_TRUE(match("/foo", "**"));
+  EXPECT_TRUE(match("foo/", "**"));
+  EXPECT_TRUE(match("foo/bar", "**"));
+
+  EXPECT_TRUE(match("/", "**/"));
+  EXPECT_TRUE(match("foo/", "**/"));
+  EXPECT_TRUE(match("/foo/", "**/"));
+  EXPECT_TRUE(match("foo/bar/", "**/"));
+
+  EXPECT_TRUE(match("/", "/**"));
+  EXPECT_TRUE(match("/foo", "/**"));
+  EXPECT_TRUE(match("/foo/", "/**"));
+  EXPECT_TRUE(match("/foo/bar", "/**"));
+
+  EXPECT_TRUE(match("foo", "**/foo"));
+  EXPECT_TRUE(match("/foo", "**/foo"));
+  EXPECT_TRUE(match("foo/bar", "**/bar"));
+  EXPECT_TRUE(match("/foo/bar", "**/foo/bar"));
+  EXPECT_TRUE(match("foo/bar/baz", "**/bar/b

[clang] [clang-format] Support globstar in .clang-format-ignore (PR #121404)

2025-01-01 Thread Owen Pan via cfe-commits

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/121404

>From 36efaa2849ee6276be5b3c0739f295d0921d1e6e Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Tue, 31 Dec 2024 08:13:53 -0800
Subject: [PATCH 1/4] [clang-format] Support globstar in .clang-format-ignore

Closes #114969.
---
 clang/docs/ClangFormat.rst   |  1 +
 clang/docs/ReleaseNotes.rst  |  1 +
 clang/lib/Format/MatchFilePath.cpp   | 35 ++--
 clang/unittests/Format/MatchFilePathTest.cpp | 35 
 4 files changed, 61 insertions(+), 11 deletions(-)

diff --git a/clang/docs/ClangFormat.rst b/clang/docs/ClangFormat.rst
index c8f1d7f5a77581..e1f677178c00ab 100644
--- a/clang/docs/ClangFormat.rst
+++ b/clang/docs/ClangFormat.rst
@@ -150,6 +150,7 @@ names. It has the following format:
 * Patterns follow the rules specified in `POSIX 2.13.1, 2.13.2, and Rule 1 of
   2.13.3 `_.
+* Bash globstar (``**``) is supported.
 * A pattern is negated if it starts with a bang (``!``).
 
 To match all files in a directory, use e.g. ``foo/bar/*``. To match all files 
in
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b7da12bcf65818..2d59d74ddf35fc 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -1124,6 +1124,7 @@ clang-format
 - Adds ``RemoveEmptyLinesInUnwrappedLines`` option.
 - Adds ``KeepFormFeed`` option and set it to ``true`` for ``GNU`` style.
 - Adds ``AllowShortNamespacesOnASingleLine`` option.
+- Adds support for bash globstar in ``.clang-format-ignore``.
 
 libclang
 
diff --git a/clang/lib/Format/MatchFilePath.cpp 
b/clang/lib/Format/MatchFilePath.cpp
index 062b334dcdd8fd..aca3433dc7fa78 100644
--- a/clang/lib/Format/MatchFilePath.cpp
+++ b/clang/lib/Format/MatchFilePath.cpp
@@ -49,25 +49,38 @@ bool matchFilePath(StringRef Pattern, StringRef FilePath) {
 return false;
   break;
 case '*': {
-  while (++I < EOP && Pattern[I] == '*') { // Skip consecutive stars.
+  const bool MaybeGlobstar = I == 0 || Pattern[I - 1] == Separator;
+  int StarCount = 1;
+  for (; ++I < EOP && Pattern[I] == '*'; ++StarCount) {
+// Skip consecutive stars.
   }
   const auto K = FilePath.find(Separator, J); // Index of next `Separator`.
   const bool NoMoreSeparatorsInFilePath = K == StringRef::npos;
+  bool Globstar = MaybeGlobstar && StarCount == 2;
   if (I == EOP) // `Pattern` ends with a star.
-return NoMoreSeparatorsInFilePath;
-  // `Pattern` ends with a lone backslash.
-  if (Pattern[I] == '\\' && ++I == EOP)
-return false;
+return Globstar || NoMoreSeparatorsInFilePath;
+  if (Pattern[I] != Separator) {
+Globstar = false;
+// `Pattern` ends with a lone backslash.
+if (Pattern[I] == '\\' && ++I == EOP)
+  return false;
+  }
   // The star is followed by a (possibly escaped) `Separator`.
   if (Pattern[I] == Separator) {
-if (NoMoreSeparatorsInFilePath)
-  return false;
-J = K; // Skip to next `Separator` in `FilePath`.
-break;
+if (!Globstar) {
+  if (NoMoreSeparatorsInFilePath)
+return false;
+  J = K; // Skip to next `Separator` in `FilePath`.
+  break;
+}
+if (I + 1 < EOP &&
+matchFilePath(Pattern.substr(I + 1), FilePath.substr(J))) {
+  return true;
+}
   }
   // Recurse.
-  for (auto Pat = Pattern.substr(I); J < End && FilePath[J] != Separator;
-   ++J) {
+  for (auto Pat = Pattern.substr(I);
+   J < End && (Globstar || FilePath[J] != Separator); ++J) {
 if (matchFilePath(Pat, FilePath.substr(J)))
   return true;
   }
diff --git a/clang/unittests/Format/MatchFilePathTest.cpp 
b/clang/unittests/Format/MatchFilePathTest.cpp
index 28f665635718e5..9876a4583c226a 100644
--- a/clang/unittests/Format/MatchFilePathTest.cpp
+++ b/clang/unittests/Format/MatchFilePathTest.cpp
@@ -164,6 +164,41 @@ TEST_F(MatchFilePathTest, Path) {
   EXPECT_FALSE(match("foo\\", R"(foo*\)"));
 }
 
+TEST_F(MatchFilePathTest, Globstar) {
+  EXPECT_TRUE(match("/", "**"));
+  EXPECT_TRUE(match("foo", "**"));
+  EXPECT_TRUE(match("/foo", "**"));
+  EXPECT_TRUE(match("foo/", "**"));
+  EXPECT_TRUE(match("foo/bar", "**"));
+
+  EXPECT_TRUE(match("/", "**/"));
+  EXPECT_TRUE(match("foo/", "**/"));
+  EXPECT_TRUE(match("/foo/", "**/"));
+  EXPECT_TRUE(match("foo/bar/", "**/"));
+
+  EXPECT_TRUE(match("/", "/**"));
+  EXPECT_TRUE(match("/foo", "/**"));
+  EXPECT_TRUE(match("/foo/", "/**"));
+  EXPECT_TRUE(match("/foo/bar", "/**"));
+
+  EXPECT_TRUE(match("foo", "**/foo"));
+  EXPECT_TRUE(match("/foo", "**/foo"));
+  EXPECT_TRUE(match("foo/bar", "**/bar"));
+  EXPECT_TRUE(match("/foo/bar", "**/foo/bar"));
+  EXPECT_TRUE(match("foo/bar/baz", "**/bar/b

[clang] [llvm] [ARM] Emit an error when the hard-float ABI is enabled but can't be used. (PR #111334)

2025-01-01 Thread Chris Copeland via cfe-commits


@@ -16,7 +16,7 @@
 
 // RUN: %clang --target=arm-none-eabi -mcpu=cortex-m33 -mfloat-abi=hard -O1 %s 
-flto=thin -c -o %t.call_thin.bc -DCALL_LIB
 // RUN: %clang --target=arm-none-eabi -mcpu=cortex-m33 -mfloat-abi=hard -O1 %s 
-flto=thin -c -o %t.define_thin.bc -DDEFINE_LIB
-// RUN: llvm-lto2 run -o %t.lto_thin -save-temps %t.call_thin.bc 
%t.define_thin.bc \
+// RUN: llvm-lto2 run --mcpu=cortex-m33 --float-abi=hard -o %t.lto_thin 
-save-temps %t.call_thin.bc %t.define_thin.bc \

chrisnc wrote:

I attempted this approach, but there's an issue due to how the 
`getSubtargetImpl` function works. It essentially maintains a map of subtargets 
it's seen before, keyed by a string of cpu + feature list, and only does the 
error checking when it sees a new combination, otherwise returns the subtarget 
that's already been created for the given cpu + feature list key. What this 
means is that if a non-fp-using function is encountered first in a translation 
unit, then the check passes because its use of inconsistent ABI+feature is 
harmless, but subsequent functions that should be flagged will be ignored 
because the map already has a subtarget for them.

Any suggestions on how to deal with this would be appreciated, or if there is a 
maintainer for this specific subsystem who could provide guidance here that 
would also be helpful.

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


[clang] [Clang] Add GCC's __builtin_stack_address() to Clang. (PR #121332)

2025-01-01 Thread Nikolas Klauser via cfe-commits


@@ -4782,6 +4782,30 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 Function *F = CGM.getIntrinsic(Intrinsic::frameaddress, AllocaInt8PtrTy);
 return RValue::get(Builder.CreateCall(F, Depth));
   }
+  case Builtin::BI__builtin_stack_address: {
+IntegerType *SPRegType;
+StringRef SPRegName;
+switch (getTarget().getTriple().getArch()) {
+case Triple::x86:
+  SPRegType = Int32Ty;
+  SPRegName = "esp";
+  break;
+case Triple::x86_64:
+  SPRegType = Int64Ty;
+  SPRegName = "rsp";
+  break;
+default:
+  llvm_unreachable("Intrinsic __builtin_stack_address is not supported for 
"
+   "the target architecture");
+}

philnik777 wrote:

You should probably make this a target-specific builtin. The compiler shouldn't 
crash just because someone used an attribute on a platform where it's not 
supported.

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


[clang] [llvm] [ARM] Emit an error when the hard-float ABI is enabled but can't be used. (PR #111334)

2025-01-01 Thread Ralf Jung via cfe-commits


@@ -311,11 +311,15 @@ ARMBaseTargetMachine::getSubtargetImpl(const Function &F) 
const {
 // function that reside in TargetOptions.
 resetTargetOptions(F);
 I = std::make_unique(TargetTriple, CPU, FS, *this, isLittle,
-F.hasMinSize());
+   F.hasMinSize());
 
 if (!I->isThumb() && !I->hasARMOps())
   F.getContext().emitError("Function '" + F.getName() + "' uses ARM "
   "instructions, but the target does not support ARM mode execution.");
+
+if (I->isTargetHardFloat() && !I->hasFPRegs())
+  F.getContext().emitError("The hard-float ABI is enabled, but the target "
+   "lacks floating-point registers.");

RalfJung wrote:

This seems to check the target triple and do automatic hard float detection. 
Shouldn't this instead check Options.FloatABIType?

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


[clang] [Clang][ASTMatcher] Add `dependentTemplateSpecializationType` AST mat… (PR #121435)

2025-01-01 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 commented:

Thanks!

I agree with @AmrDeveloper's comments. Otherwise, this looks pretty good!

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


[clang] [Clang][ASTMatcher] Add `dependentTemplateSpecializationType` AST mat… (PR #121435)

2025-01-01 Thread Nathan Ridge via cfe-commits


@@ -1926,6 +1926,21 @@ TEST_P(ASTMatchersTest, DependentNameType) {
   dependentNameType()));
 }
 
+TEST_P(ASTMatchersTest, DependentTemplateSpecializationType) {
+  if (!GetParam().isCXX()) {
+return;
+  }
+
+  EXPECT_TRUE(matches(
+  R"(
+  template struct A;

HighCommander4 wrote:

nit: please indent the contents of the code one level (two spaces) relative to 
the beginning of the string (`R"(`), and the end of the string (`)"`) the same 
as the beginning

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


[clang] [Clang][ASTMatcher] Add `dependentTemplateSpecializationType` AST mat… (PR #121435)

2025-01-01 Thread Nathan Ridge via cfe-commits

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


[clang-tools-extra] [clang-tidy] Add readability-string-view-substr check (PR #120055)

2025-01-01 Thread Helmut Januschka via cfe-commits

https://github.com/hjanuschka updated 
https://github.com/llvm/llvm-project/pull/120055

>From 8b2dc9adf4fae2065823e5beb3a1cd851686913c Mon Sep 17 00:00:00 2001
From: Helmut Januschka 
Date: Mon, 16 Dec 2024 08:24:14 +0100
Subject: [PATCH 1/7] [clang-tidy] Add readability-string-view-substr check

Add a new check that suggests using string_view::remove_prefix() and
remove_suffix() instead of substr() when the intent is to remove
characters from either end of a string_view.
---
 .../clang-tidy/readability/CMakeLists.txt |   1 +
 .../readability/ReadabilityTidyModule.cpp |   3 +
 .../readability/StringViewSubstrCheck.cpp | 132 ++
 .../readability/StringViewSubstrCheck.h   |  39 ++
 clang-tools-extra/docs/ReleaseNotes.rst   |   7 +
 .../checks/readability/string-view-substr.rst |  16 +++
 .../readability/stringview_substr.cpp |  55 
 7 files changed, 253 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/readability/StringViewSubstrCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/readability/StringViewSubstrCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/readability/string-view-substr.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/readability/stringview_substr.cpp

diff --git a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
index 8f303c51e1b0da..8b44fc339441ac 100644
--- a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
@@ -53,6 +53,7 @@ add_clang_library(clangTidyReadabilityModule STATIC
   StaticAccessedThroughInstanceCheck.cpp
   StaticDefinitionInAnonymousNamespaceCheck.cpp
   StringCompareCheck.cpp
+  StringViewSubstrCheck.cpp
   SuspiciousCallArgumentCheck.cpp
   UniqueptrDeleteReleaseCheck.cpp
   UppercaseLiteralSuffixCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp 
b/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp
index d61c0ba39658e5..f36ec8f95ede60 100644
--- a/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp
@@ -56,6 +56,7 @@
 #include "StaticAccessedThroughInstanceCheck.h"
 #include "StaticDefinitionInAnonymousNamespaceCheck.h"
 #include "StringCompareCheck.h"
+#include "StringViewSubstrCheck.h"
 #include "SuspiciousCallArgumentCheck.h"
 #include "UniqueptrDeleteReleaseCheck.h"
 #include "UppercaseLiteralSuffixCheck.h"
@@ -146,6 +147,8 @@ class ReadabilityModule : public ClangTidyModule {
 "readability-static-definition-in-anonymous-namespace");
 CheckFactories.registerCheck(
 "readability-string-compare");
+CheckFactories.registerCheck(
+"readability-stringview-substr");
 CheckFactories.registerCheck(
 "readability-named-parameter");
 CheckFactories.registerCheck(
diff --git a/clang-tools-extra/clang-tidy/readability/StringViewSubstrCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/StringViewSubstrCheck.cpp
new file mode 100644
index 00..e86a971695a835
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/readability/StringViewSubstrCheck.cpp
@@ -0,0 +1,132 @@
+//===--- StringViewSubstrCheck.cpp - clang-tidy--*- 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 "StringViewSubstrCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+void StringViewSubstrCheck::registerMatchers(MatchFinder *Finder) {
+  const auto HasStringViewType = 
hasType(hasUnqualifiedDesugaredType(recordType(
+  hasDeclaration(recordDecl(hasName("::std::basic_string_view"));
+
+  // Match assignment to string_view's substr
+  Finder->addMatcher(
+  cxxOperatorCallExpr(
+  hasOverloadedOperatorName("="),
+  hasArgument(0, expr(HasStringViewType).bind("target")),
+  hasArgument(
+  1, cxxMemberCallExpr(callee(memberExpr(hasDeclaration(
+   cxxMethodDecl(hasName("substr"),
+   on(expr(HasStringViewType).bind("source")))
+ .bind("substr_call")))
+  .bind("assignment"),
+  this);
+}
+
+void StringViewSubstrCheck::check(const MatchFinder::MatchResult &Result) {
+  const auto *Assignment =
+  Result.Nodes.getNodeAs("assignment");
+  const auto *Target = Result.Nodes.getNodeAs("target");
+  const auto *Source = Result.Nodes.getNodeAs("source");
+  const auto *SubstrCall =
+  Result.Nod

[clang] bd154e8 - Reapply "[Driver][OHOS] Fix lld link issue for OHOS (#118192)" (#120159)

2025-01-01 Thread via cfe-commits

Author: Peng Huang
Date: 2025-01-01T13:19:39-08:00
New Revision: bd154e823eba4d62366dfa3d56ae0b99ab171b96

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

LOG: Reapply "[Driver][OHOS] Fix lld link issue for OHOS (#118192)" (#120159)

The problem in original change is because OHOS::getCompilerRT()
pickes a wrong builtin runtime
`./lib/clang/20/lib/linux/libclang_rt.builtins-x86_64.a`,
if `./lib/clang/20/lib/linux/libclang_rt.builtins-x86_64.a` exist on the
test filesystem. It shouldn't happen with a clean build.

Added: 


Modified: 
clang/lib/Driver/ToolChains/OHOS.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/OHOS.cpp 
b/clang/lib/Driver/ToolChains/OHOS.cpp
index 6e1a09ae908b2f..c9a532771b99e5 100644
--- a/clang/lib/Driver/ToolChains/OHOS.cpp
+++ b/clang/lib/Driver/ToolChains/OHOS.cpp
@@ -19,8 +19,8 @@
 #include "llvm/ProfileData/InstrProf.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Path.h"
-#include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/Support/ScopedPrinter.h"
+#include "llvm/Support/VirtualFileSystem.h"
 
 using namespace clang::driver;
 using namespace clang::driver::toolchains;
@@ -58,11 +58,9 @@ static bool findOHOSMuslMultilibs(const Driver &D,
   return false;
 }
 
-static bool findOHOSMultilibs(const Driver &D,
-  const ToolChain &TC,
-  const llvm::Triple &TargetTriple,
-  StringRef Path, const ArgList &Args,
-  DetectedMultilibs &Result) {
+static bool findOHOSMultilibs(const Driver &D, const ToolChain &TC,
+  const llvm::Triple &TargetTriple, StringRef Path,
+  const ArgList &Args, DetectedMultilibs &Result) {
   Multilib::flags_list Flags;
   bool IsA7 = false;
   if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
@@ -172,8 +170,7 @@ OHOS::OHOS(const Driver &D, const llvm::Triple &Triple, 
const ArgList &Args)
   Paths);
 }
 
-ToolChain::RuntimeLibType OHOS::GetRuntimeLibType(
-const ArgList &Args) const {
+ToolChain::RuntimeLibType OHOS::GetRuntimeLibType(const ArgList &Args) const {
   if (Arg *A = Args.getLastArg(clang::driver::options::OPT_rtlib_EQ)) {
 StringRef Value = A->getValue();
 if (Value != "compiler-rt")
@@ -184,20 +181,19 @@ ToolChain::RuntimeLibType OHOS::GetRuntimeLibType(
   return ToolChain::RLT_CompilerRT;
 }
 
-ToolChain::CXXStdlibType
-OHOS::GetCXXStdlibType(const ArgList &Args) const {
+ToolChain::CXXStdlibType OHOS::GetCXXStdlibType(const ArgList &Args) const {
   if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
 StringRef Value = A->getValue();
 if (Value != "libc++")
   getDriver().Diag(diag::err_drv_invalid_stdlib_name)
-<< A->getAsString(Args);
+  << A->getAsString(Args);
   }
 
   return ToolChain::CST_Libcxx;
 }
 
 void OHOS::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
-ArgStringList &CC1Args) const {
+ ArgStringList &CC1Args) const {
   const Driver &D = getDriver();
   const llvm::Triple &Triple = getTriple();
   std::string SysRoot = computeSysRoot();
@@ -258,7 +254,7 @@ void OHOS::AddClangCXXStdlibIncludeArgs(const ArgList 
&DriverArgs,
 }
 
 void OHOS::AddCXXStdlibLibArgs(const ArgList &Args,
-  ArgStringList &CmdArgs) const {
+   ArgStringList &CmdArgs) const {
   switch (GetCXXStdlibType(Args)) {
   case ToolChain::CST_Libcxx:
 CmdArgs.push_back("-lc++");
@@ -291,7 +287,8 @@ ToolChain::path_list OHOS::getRuntimePaths() const {
 
   // First try the triple passed to driver as --target=.
   P.assign(D.ResourceDir);
-  llvm::sys::path::append(P, "lib", D.getTargetTriple(), 
SelectedMultilib.gccSuffix());
+  llvm::sys::path::append(P, "lib", D.getTargetTriple(),
+  SelectedMultilib.gccSuffix());
   Paths.push_back(P.c_str());
 
   // Second try the normalized triple.
@@ -340,26 +337,20 @@ std::string OHOS::getDynamicLinker(const ArgList &Args) 
const {
 
 std::string OHOS::getCompilerRT(const ArgList &Args, StringRef Component,
 FileType Type) const {
+  std::string CRTBasename =
+  buildCompilerRTBasename(Args, Component, Type, /*AddArch=*/false);
+
   SmallString<128> Path(getDriver().ResourceDir);
   llvm::sys::path::append(Path, "lib", getMultiarchTriple(getTriple()),
-  SelectedMultilib.gccSuffix());
-  const char *Prefix =
-  Type == ToolChain::FT_Object ? "" : "lib";
-  const char *Suffix;
-  switch (Type) {
-  case ToolChain::FT_Object:
-Suffix = ".o";
-break;
-  case ToolChain::FT

[clang] Reapply "[Driver][OHOS] Fix lld link issue for OHOS (#118192)" (PR #120159)

2025-01-01 Thread Fangrui Song via cfe-commits

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


[clang] Reapply "[Driver][OHOS] Fix lld link issue for OHOS (#118192)" (PR #120159)

2025-01-01 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `openmp-s390x-linux` 
running on `systemz-1` while building `clang` at step 6 "test-openmp".

Full details are available at: 
https://lab.llvm.org/buildbot/#/builders/88/builds/6297


Here is the relevant piece of the build log for the reference

```
Step 6 (test-openmp) failure: test (failure)
 TEST 'libomp :: tasking/issue-94260-2.c' FAILED 

Exit Code: -11

Command Output (stdout):
--
# RUN: at line 1
/home/uweigand/sandbox/buildbot/openmp-s390x-linux/llvm.build/./bin/clang 
-fopenmp   -I 
/home/uweigand/sandbox/buildbot/openmp-s390x-linux/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 -I 
/home/uweigand/sandbox/buildbot/openmp-s390x-linux/llvm.src/openmp/runtime/test 
-L 
/home/uweigand/sandbox/buildbot/openmp-s390x-linux/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
  -fno-omit-frame-pointer -mbackchain -I 
/home/uweigand/sandbox/buildbot/openmp-s390x-linux/llvm.src/openmp/runtime/test/ompt
 
/home/uweigand/sandbox/buildbot/openmp-s390x-linux/llvm.src/openmp/runtime/test/tasking/issue-94260-2.c
 -o 
/home/uweigand/sandbox/buildbot/openmp-s390x-linux/llvm.build/runtimes/runtimes-bins/openmp/runtime/test/tasking/Output/issue-94260-2.c.tmp
 -lm -latomic && 
/home/uweigand/sandbox/buildbot/openmp-s390x-linux/llvm.build/runtimes/runtimes-bins/openmp/runtime/test/tasking/Output/issue-94260-2.c.tmp
# executed command: 
/home/uweigand/sandbox/buildbot/openmp-s390x-linux/llvm.build/./bin/clang 
-fopenmp -I 
/home/uweigand/sandbox/buildbot/openmp-s390x-linux/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 -I 
/home/uweigand/sandbox/buildbot/openmp-s390x-linux/llvm.src/openmp/runtime/test 
-L 
/home/uweigand/sandbox/buildbot/openmp-s390x-linux/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 -fno-omit-frame-pointer -mbackchain -I 
/home/uweigand/sandbox/buildbot/openmp-s390x-linux/llvm.src/openmp/runtime/test/ompt
 
/home/uweigand/sandbox/buildbot/openmp-s390x-linux/llvm.src/openmp/runtime/test/tasking/issue-94260-2.c
 -o 
/home/uweigand/sandbox/buildbot/openmp-s390x-linux/llvm.build/runtimes/runtimes-bins/openmp/runtime/test/tasking/Output/issue-94260-2.c.tmp
 -lm -latomic
# executed command: 
/home/uweigand/sandbox/buildbot/openmp-s390x-linux/llvm.build/runtimes/runtimes-bins/openmp/runtime/test/tasking/Output/issue-94260-2.c.tmp
# note: command had no output on stdout or stderr
# error: command failed with exit status: -11

--




```



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


[clang] [llvm] [ARM] Emit an error when the hard-float ABI is enabled but can't be used. (PR #111334)

2025-01-01 Thread Chris Copeland via cfe-commits


@@ -311,11 +311,15 @@ ARMBaseTargetMachine::getSubtargetImpl(const Function &F) 
const {
 // function that reside in TargetOptions.
 resetTargetOptions(F);
 I = std::make_unique(TargetTriple, CPU, FS, *this, isLittle,
-F.hasMinSize());
+   F.hasMinSize());
 
 if (!I->isThumb() && !I->hasARMOps())
   F.getContext().emitError("Function '" + F.getName() + "' uses ARM "
   "instructions, but the target does not support ARM mode execution.");
+
+if (I->isTargetHardFloat() && !I->hasFPRegs())
+  F.getContext().emitError("The hard-float ABI is enabled, but the target "
+   "lacks floating-point registers.");

chrisnc wrote:

I think you are right. I initially avoided that because one of the values is 
`Default` which is meant to defer to the triple, but in the constructor of 
`ARMBaseTargetMachine` it sets the internal `Options.FloatABIType` to one or 
the other based on the passed in option and the triple, so it should be correct 
to just use that. I was testing with things like `--target=arm-none-eabi 
-mcpu=cortex-m0 -mfloat-abi=hard` and seeing the error trigger, so something 
else in the frontend may be generating a different triple that makes this 
"work".

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


[clang] [llvm] [ARM] Emit an error when the hard-float ABI is enabled but can't be used. (PR #111334)

2025-01-01 Thread Chris Copeland via cfe-commits


@@ -311,11 +311,15 @@ ARMBaseTargetMachine::getSubtargetImpl(const Function &F) 
const {
 // function that reside in TargetOptions.
 resetTargetOptions(F);
 I = std::make_unique(TargetTriple, CPU, FS, *this, isLittle,
-F.hasMinSize());
+   F.hasMinSize());
 
 if (!I->isThumb() && !I->hasARMOps())
   F.getContext().emitError("Function '" + F.getName() + "' uses ARM "
   "instructions, but the target does not support ARM mode execution.");
+
+if (I->isTargetHardFloat() && !I->hasFPRegs())
+  F.getContext().emitError("The hard-float ABI is enabled, but the target "
+   "lacks floating-point registers.");

chrisnc wrote:

Ah, I remember now where I got stuck on this before. I need to obtain this 
property on the `ARMSubtarget` rather than the `ARMBaseTargetMachine`, but 
neither of them expose `Options` publicly, and `ARMSubtarget` just invokes 
`isTargetHardFloat` on its `TM` member, without accounting for its own 
`Options`, even though they are copied from the `ARMBaseTargetMachine` when the 
subtarget is created.

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


[clang] [Clang][P1061] Add stuctured binding packs (PR #121417)

2025-01-01 Thread Jason Rice via cfe-commits


@@ -3395,26 +3395,37 @@ VarDecl *ValueDecl::getPotentiallyDecomposedVarDecl() {
   if (auto *Var = llvm::dyn_cast(this))
 return Var;
   if (auto *BD = llvm::dyn_cast(this))
-return llvm::dyn_cast(BD->getDecomposedDecl());
+return llvm::dyn_cast_or_null(BD->getDecomposedDecl());
   return nullptr;
 }
 
 void BindingDecl::anchor() {}
 
 BindingDecl *BindingDecl::Create(ASTContext &C, DeclContext *DC,
- SourceLocation IdLoc, IdentifierInfo *Id) {
-  return new (C, DC) BindingDecl(DC, IdLoc, Id);
+ SourceLocation IdLoc, IdentifierInfo *Id,
+ QualType T) {
+  return new (C, DC) BindingDecl(DC, IdLoc, Id, T);
 }
 
 BindingDecl *BindingDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
-  return new (C, ID) BindingDecl(nullptr, SourceLocation(), nullptr);
+  return new (C, ID)
+  BindingDecl(nullptr, SourceLocation(), nullptr, QualType());
 }
 
 VarDecl *BindingDecl::getHoldingVar() const {
   Expr *B = getBinding();
   if (!B)
 return nullptr;
-  auto *DRE = dyn_cast(B->IgnoreImplicit());
+  return getHoldingVar(B);
+}
+
+VarDecl *BindingDecl::getHoldingVar(Expr *E) {
+  auto *DRE = dyn_cast(E->IgnoreImplicit());

ricejasonf wrote:

This one was like this before. Looking around I see that we call setBinding 
with a call to BuildFieldReferenceExpr which may return a MemberExpr.

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


[clang] [llvm] [ARM] Emit an error when the hard-float ABI is enabled but can't be used. (PR #111334)

2025-01-01 Thread Chris Copeland via cfe-commits

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


[clang-tools-extra] [clangd] Implement simple folding of preprocessor branches (rebased) (PR #121449)

2025-01-01 Thread via cfe-commits

llvmbot wrote:




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

Author: SR_team (sr-tream)


Changes

It's a rebased PR #80592 without pseudo-parser usage.

Extract directive branches information from DirectiveTree, fold branches that 
don't end with eof.

Fixes https://github.com/clangd/clangd/issues/1661

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


3 Files Affected:

- (modified) clang-tools-extra/clangd/SemanticSelection.cpp (+18) 
- (modified) clang-tools-extra/clangd/support/DirectiveTree.cpp (+54) 
- (modified) clang-tools-extra/clangd/support/DirectiveTree.h (+3) 


``diff
diff --git a/clang-tools-extra/clangd/SemanticSelection.cpp 
b/clang-tools-extra/clangd/SemanticSelection.cpp
index dd7116e619e6d0..57e7ff8b97c658 100644
--- a/clang-tools-extra/clangd/SemanticSelection.cpp
+++ b/clang-tools-extra/clangd/SemanticSelection.cpp
@@ -220,6 +220,24 @@ getFoldingRanges(const std::string &Code, bool 
LineFoldingOnly) {
   auto EndPosition = [&](const Token &T) {
 return offsetToPosition(Code, EndOffset(T));
   };
+
+  // Preprocessor directives
+  auto PPRanges = pairDirectiveRanges(DirectiveStructure, OrigStream);
+  for (const auto &R : PPRanges) {
+auto BTok = OrigStream.tokens()[R.Begin];
+auto ETok = OrigStream.tokens()[R.End];
+if (ETok.Kind == tok::eof)
+  continue;
+if (BTok.Line >= ETok.Line)
+  continue;
+
+Position Start = EndPosition(BTok);
+Position End = StartPosition(ETok);
+if (LineFoldingOnly)
+  End.line--;
+AddFoldingRange(Start, End, FoldingRange::REGION_KIND);
+  }
+
   auto Tokens = ParseableStream.tokens();
   // Brackets.
   for (const auto &Tok : Tokens) {
diff --git a/clang-tools-extra/clangd/support/DirectiveTree.cpp 
b/clang-tools-extra/clangd/support/DirectiveTree.cpp
index 7ea08add7a107e..2a4448902df539 100644
--- a/clang-tools-extra/clangd/support/DirectiveTree.cpp
+++ b/clang-tools-extra/clangd/support/DirectiveTree.cpp
@@ -356,5 +356,59 @@ TokenStream DirectiveTree::stripDirectives(const 
TokenStream &In) const {
   return Out;
 }
 
+namespace {
+class RangePairer {
+  std::vector &Ranges;
+
+public:
+  RangePairer(std::vector &Ranges) : Ranges(Ranges) {}
+
+  void walk(const DirectiveTree &T) {
+for (const auto &C : T.Chunks)
+  std::visit(*this, C);
+  }
+
+  void operator()(const DirectiveTree::Code &C) {}
+
+  void operator()(const DirectiveTree::Directive &) {}
+
+  void operator()(const DirectiveTree::Conditional &C) {
+Token::Range Range;
+Token::Index Last;
+auto First = true;
+for (const auto &B : C.Branches) {
+  if (First) {
+First = false;
+  } else {
+Range = {Last, B.first.Tokens.Begin};
+Ranges.push_back(Range);
+  }
+  Last = B.first.Tokens.Begin;
+}
+Range = {Last, C.End.Tokens.Begin};
+Ranges.push_back(Range);
+
+for (const auto &B : C.Branches)
+  walk(B.second);
+  }
+};
+} // namespace
+
+std::vector pairDirectiveRanges(const DirectiveTree &Tree,
+  const TokenStream &Code) {
+  std::vector Ranges;
+  RangePairer(Ranges).walk(Tree);
+
+  // Transform paired ranges to start with last token in its logical line
+  for (auto &R : Ranges) {
+const Token *Tok = &Code.tokens()[R.Begin + 1];
+while (Tok->Kind != tok::eof && !Tok->flag(LexFlags::StartsPPLine))
+  ++Tok;
+Tok = Tok - 1;
+R.Begin = Tok->OriginalIndex;
+  }
+  return std::move(Ranges);
+}
+
 } // namespace clangd
 } // namespace clang
diff --git a/clang-tools-extra/clangd/support/DirectiveTree.h 
b/clang-tools-extra/clangd/support/DirectiveTree.h
index 34f5a63f26..1a377f5e0640ca 100644
--- a/clang-tools-extra/clangd/support/DirectiveTree.h
+++ b/clang-tools-extra/clangd/support/DirectiveTree.h
@@ -124,6 +124,9 @@ llvm::raw_ostream &operator<<(llvm::raw_ostream &,
 /// The choices are stored in Conditional::Taken nodes.
 void chooseConditionalBranches(DirectiveTree &, const TokenStream &Code);
 
+std::vector pairDirectiveRanges(const DirectiveTree &Tree,
+  const TokenStream &Code);
+
 } // namespace clangd
 } // namespace clang
 

``




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


[clang-tools-extra] [clangd] Implement simple folding of preprocessor branches (rebased) (PR #121449)

2025-01-01 Thread via cfe-commits

https://github.com/sr-tream created 
https://github.com/llvm/llvm-project/pull/121449

It's a rebased PR #80592 without pseudo-parser usage.

Extract directive branches information from DirectiveTree, fold branches that 
don't end with eof.

Fixes https://github.com/clangd/clangd/issues/1661

>From 86b90564cfda97dfacd6e04c782d9c93a87ac2b2 Mon Sep 17 00:00:00 2001
From: Ruihua Dong 
Date: Thu, 2 Jan 2025 08:27:33 +0500
Subject: [PATCH] [clangd] Implement simple folding of preprocessor branches

Extract directive branches information from DirectiveTree, fold branches
that don't end with eof.

Fixes https://github.com/clangd/clangd/issues/1661
---
 .../clangd/SemanticSelection.cpp  | 18 +++
 .../clangd/support/DirectiveTree.cpp  | 54 +++
 .../clangd/support/DirectiveTree.h|  3 ++
 3 files changed, 75 insertions(+)

diff --git a/clang-tools-extra/clangd/SemanticSelection.cpp 
b/clang-tools-extra/clangd/SemanticSelection.cpp
index dd7116e619e6d0..57e7ff8b97c658 100644
--- a/clang-tools-extra/clangd/SemanticSelection.cpp
+++ b/clang-tools-extra/clangd/SemanticSelection.cpp
@@ -220,6 +220,24 @@ getFoldingRanges(const std::string &Code, bool 
LineFoldingOnly) {
   auto EndPosition = [&](const Token &T) {
 return offsetToPosition(Code, EndOffset(T));
   };
+
+  // Preprocessor directives
+  auto PPRanges = pairDirectiveRanges(DirectiveStructure, OrigStream);
+  for (const auto &R : PPRanges) {
+auto BTok = OrigStream.tokens()[R.Begin];
+auto ETok = OrigStream.tokens()[R.End];
+if (ETok.Kind == tok::eof)
+  continue;
+if (BTok.Line >= ETok.Line)
+  continue;
+
+Position Start = EndPosition(BTok);
+Position End = StartPosition(ETok);
+if (LineFoldingOnly)
+  End.line--;
+AddFoldingRange(Start, End, FoldingRange::REGION_KIND);
+  }
+
   auto Tokens = ParseableStream.tokens();
   // Brackets.
   for (const auto &Tok : Tokens) {
diff --git a/clang-tools-extra/clangd/support/DirectiveTree.cpp 
b/clang-tools-extra/clangd/support/DirectiveTree.cpp
index 7ea08add7a107e..2a4448902df539 100644
--- a/clang-tools-extra/clangd/support/DirectiveTree.cpp
+++ b/clang-tools-extra/clangd/support/DirectiveTree.cpp
@@ -356,5 +356,59 @@ TokenStream DirectiveTree::stripDirectives(const 
TokenStream &In) const {
   return Out;
 }
 
+namespace {
+class RangePairer {
+  std::vector &Ranges;
+
+public:
+  RangePairer(std::vector &Ranges) : Ranges(Ranges) {}
+
+  void walk(const DirectiveTree &T) {
+for (const auto &C : T.Chunks)
+  std::visit(*this, C);
+  }
+
+  void operator()(const DirectiveTree::Code &C) {}
+
+  void operator()(const DirectiveTree::Directive &) {}
+
+  void operator()(const DirectiveTree::Conditional &C) {
+Token::Range Range;
+Token::Index Last;
+auto First = true;
+for (const auto &B : C.Branches) {
+  if (First) {
+First = false;
+  } else {
+Range = {Last, B.first.Tokens.Begin};
+Ranges.push_back(Range);
+  }
+  Last = B.first.Tokens.Begin;
+}
+Range = {Last, C.End.Tokens.Begin};
+Ranges.push_back(Range);
+
+for (const auto &B : C.Branches)
+  walk(B.second);
+  }
+};
+} // namespace
+
+std::vector pairDirectiveRanges(const DirectiveTree &Tree,
+  const TokenStream &Code) {
+  std::vector Ranges;
+  RangePairer(Ranges).walk(Tree);
+
+  // Transform paired ranges to start with last token in its logical line
+  for (auto &R : Ranges) {
+const Token *Tok = &Code.tokens()[R.Begin + 1];
+while (Tok->Kind != tok::eof && !Tok->flag(LexFlags::StartsPPLine))
+  ++Tok;
+Tok = Tok - 1;
+R.Begin = Tok->OriginalIndex;
+  }
+  return std::move(Ranges);
+}
+
 } // namespace clangd
 } // namespace clang
diff --git a/clang-tools-extra/clangd/support/DirectiveTree.h 
b/clang-tools-extra/clangd/support/DirectiveTree.h
index 34f5a63f26..1a377f5e0640ca 100644
--- a/clang-tools-extra/clangd/support/DirectiveTree.h
+++ b/clang-tools-extra/clangd/support/DirectiveTree.h
@@ -124,6 +124,9 @@ llvm::raw_ostream &operator<<(llvm::raw_ostream &,
 /// The choices are stored in Conditional::Taken nodes.
 void chooseConditionalBranches(DirectiveTree &, const TokenStream &Code);
 
+std::vector pairDirectiveRanges(const DirectiveTree &Tree,
+  const TokenStream &Code);
+
 } // namespace clangd
 } // namespace clang
 

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


[clang-tools-extra] [clangd] Implement simple folding of preprocessor branches (rebased) (PR #121449)

2025-01-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clangd

Author: SR_team (sr-tream)


Changes

It's a rebased PR #80592 without pseudo-parser usage.

Extract directive branches information from DirectiveTree, fold branches that 
don't end with eof.

Fixes https://github.com/clangd/clangd/issues/1661

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


3 Files Affected:

- (modified) clang-tools-extra/clangd/SemanticSelection.cpp (+18) 
- (modified) clang-tools-extra/clangd/support/DirectiveTree.cpp (+54) 
- (modified) clang-tools-extra/clangd/support/DirectiveTree.h (+3) 


``diff
diff --git a/clang-tools-extra/clangd/SemanticSelection.cpp 
b/clang-tools-extra/clangd/SemanticSelection.cpp
index dd7116e619e6d0..57e7ff8b97c658 100644
--- a/clang-tools-extra/clangd/SemanticSelection.cpp
+++ b/clang-tools-extra/clangd/SemanticSelection.cpp
@@ -220,6 +220,24 @@ getFoldingRanges(const std::string &Code, bool 
LineFoldingOnly) {
   auto EndPosition = [&](const Token &T) {
 return offsetToPosition(Code, EndOffset(T));
   };
+
+  // Preprocessor directives
+  auto PPRanges = pairDirectiveRanges(DirectiveStructure, OrigStream);
+  for (const auto &R : PPRanges) {
+auto BTok = OrigStream.tokens()[R.Begin];
+auto ETok = OrigStream.tokens()[R.End];
+if (ETok.Kind == tok::eof)
+  continue;
+if (BTok.Line >= ETok.Line)
+  continue;
+
+Position Start = EndPosition(BTok);
+Position End = StartPosition(ETok);
+if (LineFoldingOnly)
+  End.line--;
+AddFoldingRange(Start, End, FoldingRange::REGION_KIND);
+  }
+
   auto Tokens = ParseableStream.tokens();
   // Brackets.
   for (const auto &Tok : Tokens) {
diff --git a/clang-tools-extra/clangd/support/DirectiveTree.cpp 
b/clang-tools-extra/clangd/support/DirectiveTree.cpp
index 7ea08add7a107e..2a4448902df539 100644
--- a/clang-tools-extra/clangd/support/DirectiveTree.cpp
+++ b/clang-tools-extra/clangd/support/DirectiveTree.cpp
@@ -356,5 +356,59 @@ TokenStream DirectiveTree::stripDirectives(const 
TokenStream &In) const {
   return Out;
 }
 
+namespace {
+class RangePairer {
+  std::vector &Ranges;
+
+public:
+  RangePairer(std::vector &Ranges) : Ranges(Ranges) {}
+
+  void walk(const DirectiveTree &T) {
+for (const auto &C : T.Chunks)
+  std::visit(*this, C);
+  }
+
+  void operator()(const DirectiveTree::Code &C) {}
+
+  void operator()(const DirectiveTree::Directive &) {}
+
+  void operator()(const DirectiveTree::Conditional &C) {
+Token::Range Range;
+Token::Index Last;
+auto First = true;
+for (const auto &B : C.Branches) {
+  if (First) {
+First = false;
+  } else {
+Range = {Last, B.first.Tokens.Begin};
+Ranges.push_back(Range);
+  }
+  Last = B.first.Tokens.Begin;
+}
+Range = {Last, C.End.Tokens.Begin};
+Ranges.push_back(Range);
+
+for (const auto &B : C.Branches)
+  walk(B.second);
+  }
+};
+} // namespace
+
+std::vector pairDirectiveRanges(const DirectiveTree &Tree,
+  const TokenStream &Code) {
+  std::vector Ranges;
+  RangePairer(Ranges).walk(Tree);
+
+  // Transform paired ranges to start with last token in its logical line
+  for (auto &R : Ranges) {
+const Token *Tok = &Code.tokens()[R.Begin + 1];
+while (Tok->Kind != tok::eof && !Tok->flag(LexFlags::StartsPPLine))
+  ++Tok;
+Tok = Tok - 1;
+R.Begin = Tok->OriginalIndex;
+  }
+  return std::move(Ranges);
+}
+
 } // namespace clangd
 } // namespace clang
diff --git a/clang-tools-extra/clangd/support/DirectiveTree.h 
b/clang-tools-extra/clangd/support/DirectiveTree.h
index 34f5a63f26..1a377f5e0640ca 100644
--- a/clang-tools-extra/clangd/support/DirectiveTree.h
+++ b/clang-tools-extra/clangd/support/DirectiveTree.h
@@ -124,6 +124,9 @@ llvm::raw_ostream &operator<<(llvm::raw_ostream &,
 /// The choices are stored in Conditional::Taken nodes.
 void chooseConditionalBranches(DirectiveTree &, const TokenStream &Code);
 
+std::vector pairDirectiveRanges(const DirectiveTree &Tree,
+  const TokenStream &Code);
+
 } // namespace clangd
 } // namespace clang
 

``




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


[clang] [clang] Use a Worklist for some CodeGenFunctions (PR #115395)

2025-01-01 Thread John McCall via cfe-commits


@@ -0,0 +1,37 @@
+// RUN: split-file %s %t
+// RUN: python %t/gen.py %t/switch-overflow.c %t/tmp.c && %clang_cc1 
-emit-llvm %t/tmp.c -o - | FileCheck %t/tmp.c
+
+//--- gen.py

rjmccall wrote:

If you don't mind working on the representation issue, I think that would be a 
reasonable path forward. I can sympathize if you'd rather fix the narrow issue, 
though.

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


[clang] [clang-format] Add `VariableTemplates` option (PR #121318)

2025-01-01 Thread Owen Pan via cfe-commits

owenca wrote:

> Should there be a parse test?

About half of the `List of Strings` options don't have a `CHECK_PARSE` test. 
I'll fix that in a separate patch.

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


[clang] [Clang] Repair the function "rParenEndsCast" to make incorrect judgments in template variable cases (PR #120904)

2025-01-01 Thread Owen Pan via cfe-commits

owenca wrote:

See #121318.

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


[clang] [clang-format] extend clang-format directive with options to prevent formatting for one line (PR #118566)

2025-01-01 Thread Owen Pan via cfe-commits

owenca wrote:

> > If we were to add // clang-format off-next-line, would "next line" mean the 
> > next physical or logical/unwrapped line?
> 
> I would expect it to apply only to the physical line, similar to how other 
> formatters work. However, the main concern doesn’t seem to be about its 
> behavior but rather about extending clang-format directive with new options 
> at all.

This is an essential detail missing from the description of the proposed option 
for us to accept a new option and review the patch.

> From my perspective, these options are just additional ways to control 
> formatting and give users more flexibility. These options aren’t intended to 
> eliminate `clang-format` usage, and based on user feedback on the issue, it 
> seems there are cases in which these options are useful. For 
> [instance](https://github.com/athomps/lammps/blob/ceb9466172398e9a20cb510528b4b17f719c7cf2/src/set.h#L15-L17),
> 
> ```c++
> // clang-format off
> CommandStyle(set,Set);
> // clang-format on
> ```
> 
> vs
> 
> ```c++
> CommandStyle(set,Set); // clang-format off-line
> ```

For simplicity and clarify, I might accept a lone comment above the (physical) 
line to be skipped by clang-format, but not a trailing comment.

> If these options introduce significant complexity that could lead to 
> regressions without improving the development experience, I believe the 
> discussion should be wrapped up, and both the PR and issue should be closed. 
> Otherwise, it would be helpful to continue the discussion in the issue to 
> gather more insights into why users need these changes. Does that make sense?

I’m fine with continuing the discussion in the GitHub issue, but I’m still with 
@mydeveloperday on this one.

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


[clang] [Clang][P1061] Add stuctured binding packs (PR #121417)

2025-01-01 Thread via cfe-commits

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


[clang] [Clang][P1061] Add stuctured binding packs (PR #121417)

2025-01-01 Thread via cfe-commits


@@ -3395,26 +3395,37 @@ VarDecl *ValueDecl::getPotentiallyDecomposedVarDecl() {
   if (auto *Var = llvm::dyn_cast(this))
 return Var;
   if (auto *BD = llvm::dyn_cast(this))
-return llvm::dyn_cast(BD->getDecomposedDecl());
+return llvm::dyn_cast_or_null(BD->getDecomposedDecl());
   return nullptr;
 }
 
 void BindingDecl::anchor() {}
 
 BindingDecl *BindingDecl::Create(ASTContext &C, DeclContext *DC,
- SourceLocation IdLoc, IdentifierInfo *Id) {
-  return new (C, DC) BindingDecl(DC, IdLoc, Id);
+ SourceLocation IdLoc, IdentifierInfo *Id,
+ QualType T) {
+  return new (C, DC) BindingDecl(DC, IdLoc, Id, T);
 }
 
 BindingDecl *BindingDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
-  return new (C, ID) BindingDecl(nullptr, SourceLocation(), nullptr);
+  return new (C, ID)
+  BindingDecl(nullptr, SourceLocation(), nullptr, QualType());
 }
 
 VarDecl *BindingDecl::getHoldingVar() const {
   Expr *B = getBinding();
   if (!B)
 return nullptr;
-  auto *DRE = dyn_cast(B->IgnoreImplicit());
+  return getHoldingVar(B);
+}
+
+VarDecl *BindingDecl::getHoldingVar(Expr *E) {

cor3ntin wrote:

This is only used one, it could be a non-member function.

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


[clang] [Clang][P1061] Add stuctured binding packs (PR #121417)

2025-01-01 Thread via cfe-commits


@@ -3395,26 +3395,37 @@ VarDecl *ValueDecl::getPotentiallyDecomposedVarDecl() {
   if (auto *Var = llvm::dyn_cast(this))
 return Var;
   if (auto *BD = llvm::dyn_cast(this))
-return llvm::dyn_cast(BD->getDecomposedDecl());
+return llvm::dyn_cast_or_null(BD->getDecomposedDecl());

cor3ntin wrote:

```suggestion
return llvm::dyn_cast_if_present(BD->getDecomposedDecl());
```

Same change here and everywhere

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


[clang] [Clang][P1061] Add stuctured binding packs (PR #121417)

2025-01-01 Thread via cfe-commits


@@ -4219,6 +4220,13 @@ class DecompositionDecl final
 
   void printName(raw_ostream &OS, const PrintingPolicy &Policy) const override;
 
+  /// Visit the variables (if any) that hold the values of evaluating the
+  /// binding. Only present for user-defined bindings for tuple-like types.
+  void VisitHoldingVars(llvm::function_ref F) const;
+
+  // Visit the concrete bindings. (workaround)

cor3ntin wrote:

Can you explain why it is a workaround?

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


[clang] [Clang][P1061] Add stuctured binding packs (PR #121417)

2025-01-01 Thread via cfe-commits


@@ -5397,6 +5393,13 @@ bool ValueDecl::isInitCapture() const {
   return false;
 }
 
+bool ValueDecl::isParameterPack() const {
+  if (const auto *NTTP = dyn_cast(this))
+return NTTP->isParameterPack();
+
+  return isa_and_nonnull(getType().getTypePtrOrNull());

cor3ntin wrote:

Can we assert `this` is a bindingdecl or a vardecl?

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


[clang] [Clang][P1061] Add stuctured binding packs (PR #121417)

2025-01-01 Thread via cfe-commits


@@ -3395,26 +3395,37 @@ VarDecl *ValueDecl::getPotentiallyDecomposedVarDecl() {
   if (auto *Var = llvm::dyn_cast(this))
 return Var;
   if (auto *BD = llvm::dyn_cast(this))
-return llvm::dyn_cast(BD->getDecomposedDecl());
+return llvm::dyn_cast_or_null(BD->getDecomposedDecl());
   return nullptr;
 }
 
 void BindingDecl::anchor() {}
 
 BindingDecl *BindingDecl::Create(ASTContext &C, DeclContext *DC,
- SourceLocation IdLoc, IdentifierInfo *Id) {
-  return new (C, DC) BindingDecl(DC, IdLoc, Id);
+ SourceLocation IdLoc, IdentifierInfo *Id,
+ QualType T) {
+  return new (C, DC) BindingDecl(DC, IdLoc, Id, T);
 }
 
 BindingDecl *BindingDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
-  return new (C, ID) BindingDecl(nullptr, SourceLocation(), nullptr);
+  return new (C, ID)
+  BindingDecl(nullptr, SourceLocation(), nullptr, QualType());
 }
 
 VarDecl *BindingDecl::getHoldingVar() const {
   Expr *B = getBinding();
   if (!B)
 return nullptr;
-  auto *DRE = dyn_cast(B->IgnoreImplicit());
+  return getHoldingVar(B);
+}
+
+VarDecl *BindingDecl::getHoldingVar(Expr *E) {
+  auto *DRE = dyn_cast(E->IgnoreImplicit());

cor3ntin wrote:

this could be a (non-dynamic) cast right?

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


[clang] [Clang][P1061] Add stuctured binding packs (PR #121417)

2025-01-01 Thread via cfe-commits


@@ -237,10 +237,12 @@ bool Decl::isTemplateParameterPack() const {
 }
 
 bool Decl::isParameterPack() const {
-  if (const auto *Var = dyn_cast(this))
+  if (isTemplateParameterPack())
+return true;
+  if (const auto *Var = dyn_cast(this))
 return Var->isParameterPack();
 
-  return isTemplateParameterPack();
+  return false;

cor3ntin wrote:

Can we keep the original form? (ie, we should keep the common case first)

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


[clang] [Clang][P1061] Add stuctured binding packs (PR #121417)

2025-01-01 Thread via cfe-commits


@@ -1965,3 +1965,51 @@ CXXFoldExpr::CXXFoldExpr(QualType T, 
UnresolvedLookupExpr *Callee,
   SubExprs[SubExpr::RHS] = RHS;
   setDependence(computeDependence(this));
 }
+
+ResolvedUnexpandedPackExpr::ResolvedUnexpandedPackExpr(SourceLocation BL,
+   QualType QT,
+   unsigned NumExprs)
+: Expr(ResolvedUnexpandedPackExprClass, QT, VK_PRValue, OK_Ordinary),
+  BeginLoc(BL), NumExprs(NumExprs) {
+  setDependence(ExprDependence::TypeValueInstantiation |
+ExprDependence::UnexpandedPack);
+}
+
+ResolvedUnexpandedPackExpr *
+ResolvedUnexpandedPackExpr::CreateDeserialized(ASTContext &Ctx,
+   unsigned NumExprs) {
+  void *Mem = Ctx.Allocate(totalSizeToAlloc(NumExprs),
+   alignof(ResolvedUnexpandedPackExpr));
+  return new (Mem)
+  ResolvedUnexpandedPackExpr(SourceLocation(), QualType(), NumExprs);
+}
+
+ResolvedUnexpandedPackExpr *
+ResolvedUnexpandedPackExpr::Create(ASTContext &Ctx, SourceLocation BL,
+   QualType T, unsigned NumExprs) {
+  void *Mem = Ctx.Allocate(totalSizeToAlloc(NumExprs),
+   alignof(ResolvedUnexpandedPackExpr));
+  ResolvedUnexpandedPackExpr *New =
+  new (Mem) ResolvedUnexpandedPackExpr(BL, T, NumExprs);
+
+  auto Exprs = llvm::MutableArrayRef(New->getExprs(), New->getNumExprs());
+  std::fill(Exprs.begin(), Exprs.end(), nullptr);
+
+  return New;
+}
+
+ResolvedUnexpandedPackExpr *
+ResolvedUnexpandedPackExpr::Create(ASTContext &Ctx, SourceLocation BL,
+   QualType T, ArrayRef Exprs) {
+  auto *New = Create(Ctx, BL, T, Exprs.size());
+  std::copy(Exprs.begin(), Exprs.end(), New->getExprs());
+  return New;
+}
+
+ResolvedUnexpandedPackExpr *ResolvedUnexpandedPackExpr::getFromDecl(Decl *D) {
+  // TODO P1858: Extend to VarDecls for P1858

cor3ntin wrote:

Remove the comment

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


[clang] [Clang][P1061] Add stuctured binding packs (PR #121417)

2025-01-01 Thread via cfe-commits


@@ -3656,6 +3656,11 @@ bool Expr::HasSideEffects(const ASTContext &Ctx,
 // These never have a side-effect.
 return false;
 
+  // ResolvedUnexpandedPackExpr is currently only used for
+  // structed bindings which have no side effects

cor3ntin wrote:

Even in the future this would not have side effects, rights (at least as long 
as packs are id-expressions)

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


[clang] [Clang][P1061] Add stuctured binding packs (PR #121417)

2025-01-01 Thread via cfe-commits

https://github.com/cor3ntin commented:

Thanks a lot for this PR

First review pass.
I think the changes generally.
I'd like to see more tests. Notably
  - Check it works with pack indexing
  - BitField tests
  - Codegen tests
  - PCH/Module tests

There are unimplemented bits (ASTDumper/JSONDumper)  - you should have warnings 
for unhandled enumerator in switch

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


[clang] [Clang][P1061] Add stuctured binding packs (PR #121417)

2025-01-01 Thread via cfe-commits


@@ -5321,6 +5321,54 @@ class BuiltinBitCastExpr final
   }
 };
 
+class ResolvedUnexpandedPackExpr final

cor3ntin wrote:

Can you add a comment describing this class?

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


[clang] [Clang][P1061] Add stuctured binding packs (PR #121417)

2025-01-01 Thread via cfe-commits


@@ -951,28 +959,130 @@ Sema::ActOnDecompositionDeclarator(Scope *S, Declarator 
&D,
   return New;
 }
 
+namespace {
+// CheckBindingsCount
+//  - Checks the arity of the structured bindings
+//  - Creates the resolved pack expr if there is
+//one
+bool CheckBindingsCount(Sema &S, DecompositionDecl *DD, QualType DecompType,
+ArrayRef Bindings,
+unsigned MemberCount) {
+  auto BindingWithPackItr =
+  std::find_if(Bindings.begin(), Bindings.end(),
+   [](BindingDecl *D) -> bool { return D->isParameterPack(); 
});
+  bool HasPack = BindingWithPackItr != Bindings.end();
+  bool IsValid;
+  if (!HasPack) {
+IsValid = Bindings.size() == MemberCount;
+  } else {
+// there may not be more members than non-pack bindings
+IsValid = MemberCount >= Bindings.size() - 1;
+  }
+
+  if (IsValid && HasPack) {
+TemplateTypeParmDecl *DummyTemplateParam = TemplateTypeParmDecl::Create(
+S.Context, S.Context.getTranslationUnitDecl(),
+/*KeyLoc*/ SourceLocation(), /*NameLoc*/ SourceLocation(),
+/*TemplateDepth*/ 0, /*AutoParameterPosition*/ 0,
+/*Identifier*/ nullptr, false, /*IsParameterPack*/ true);
+
+// create the pack expr and assign it to the binding
+unsigned PackSize = MemberCount - Bindings.size() + 1;
+QualType PackType = S.Context.getPackExpansionType(
+QualType(DummyTemplateParam->getTypeForDecl(), 0), PackSize);
+(*BindingWithPackItr)
+->setBinding(PackType,
+ ResolvedUnexpandedPackExpr::Create(
+ S.Context, DD->getBeginLoc(), DecompType, PackSize));
+  }
+
+  if (IsValid)
+return false;
+
+  S.Diag(DD->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
+  << DecompType << (unsigned)Bindings.size() << MemberCount << MemberCount
+  << (MemberCount < Bindings.size());
+  return true;
+}
+
+// BindingInitWalker
+//  - This implements a forward iterating flattened view
+//of structured bindings that may have a nested pack.
+//It allows the user to set the init expr for either the
+//BindingDecl or its ResolvedUnexpandedPackExpr

cor3ntin wrote:

I think it would be cleaner to separate
 - creating the bindings (immediately after CheckBindingsCount)
 - setting their value

Doing that would let us have a proper range interface over all bindings


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


[clang] [Clang][P1061] Add stuctured binding packs (PR #121417)

2025-01-01 Thread via cfe-commits


@@ -3395,26 +3395,37 @@ VarDecl *ValueDecl::getPotentiallyDecomposedVarDecl() {
   if (auto *Var = llvm::dyn_cast(this))
 return Var;
   if (auto *BD = llvm::dyn_cast(this))
-return llvm::dyn_cast(BD->getDecomposedDecl());
+return llvm::dyn_cast_or_null(BD->getDecomposedDecl());
   return nullptr;
 }
 
 void BindingDecl::anchor() {}
 
 BindingDecl *BindingDecl::Create(ASTContext &C, DeclContext *DC,
- SourceLocation IdLoc, IdentifierInfo *Id) {
-  return new (C, DC) BindingDecl(DC, IdLoc, Id);
+ SourceLocation IdLoc, IdentifierInfo *Id,
+ QualType T) {
+  return new (C, DC) BindingDecl(DC, IdLoc, Id, T);
 }
 
 BindingDecl *BindingDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {
-  return new (C, ID) BindingDecl(nullptr, SourceLocation(), nullptr);
+  return new (C, ID)
+  BindingDecl(nullptr, SourceLocation(), nullptr, QualType());
 }
 
 VarDecl *BindingDecl::getHoldingVar() const {
   Expr *B = getBinding();
   if (!B)
 return nullptr;
-  auto *DRE = dyn_cast(B->IgnoreImplicit());
+  return getHoldingVar(B);
+}
+
+VarDecl *BindingDecl::getHoldingVar(Expr *E) {
+  auto *DRE = dyn_cast(E->IgnoreImplicit());
+  if (!DRE)
+return nullptr;
+  if (auto *BD = dyn_cast(DRE->getDecl())) {

cor3ntin wrote:

ditto

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


[clang] [Clang][P1061] Add stuctured binding packs (PR #121417)

2025-01-01 Thread via cfe-commits


@@ -951,28 +959,130 @@ Sema::ActOnDecompositionDeclarator(Scope *S, Declarator 
&D,
   return New;
 }
 
+namespace {
+// CheckBindingsCount
+//  - Checks the arity of the structured bindings
+//  - Creates the resolved pack expr if there is
+//one
+bool CheckBindingsCount(Sema &S, DecompositionDecl *DD, QualType DecompType,
+ArrayRef Bindings,
+unsigned MemberCount) {
+  auto BindingWithPackItr =
+  std::find_if(Bindings.begin(), Bindings.end(),
+   [](BindingDecl *D) -> bool { return D->isParameterPack(); 
});
+  bool HasPack = BindingWithPackItr != Bindings.end();
+  bool IsValid;
+  if (!HasPack) {
+IsValid = Bindings.size() == MemberCount;
+  } else {
+// there may not be more members than non-pack bindings
+IsValid = MemberCount >= Bindings.size() - 1;
+  }
+
+  if (IsValid && HasPack) {
+TemplateTypeParmDecl *DummyTemplateParam = TemplateTypeParmDecl::Create(
+S.Context, S.Context.getTranslationUnitDecl(),
+/*KeyLoc*/ SourceLocation(), /*NameLoc*/ SourceLocation(),
+/*TemplateDepth*/ 0, /*AutoParameterPosition*/ 0,
+/*Identifier*/ nullptr, false, /*IsParameterPack*/ true);

cor3ntin wrote:

Can you explain the logic here?

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


[clang] [Clang][P1061] Add stuctured binding packs (PR #121417)

2025-01-01 Thread via cfe-commits


@@ -1965,3 +1965,51 @@ CXXFoldExpr::CXXFoldExpr(QualType T, 
UnresolvedLookupExpr *Callee,
   SubExprs[SubExpr::RHS] = RHS;
   setDependence(computeDependence(this));
 }
+
+ResolvedUnexpandedPackExpr::ResolvedUnexpandedPackExpr(SourceLocation BL,
+   QualType QT,
+   unsigned NumExprs)
+: Expr(ResolvedUnexpandedPackExprClass, QT, VK_PRValue, OK_Ordinary),
+  BeginLoc(BL), NumExprs(NumExprs) {
+  setDependence(ExprDependence::TypeValueInstantiation |
+ExprDependence::UnexpandedPack);

cor3ntin wrote:

Can you add a comment referencing [temp.dep.expr] (this initially confused me)

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


[clang] [Clang][P1061] Add stuctured binding packs (PR #121417)

2025-01-01 Thread via cfe-commits


@@ -19,6 +19,7 @@
 #include "clang/Sema/Sema.h"
 #include "clang/Sema/SemaInternal.h"
 #include "clang/Sema/Template.h"
+#include "llvm/ADT/ScopeExit.h"

cor3ntin wrote:

Unrelated change?

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


[clang] [Clang][P1061] Add stuctured binding packs (PR #121417)

2025-01-01 Thread via cfe-commits


@@ -7331,18 +7332,33 @@ void Parser::ParseDecompositionDeclarator(Declarator 
&D) {
   Diag(Tok, diag::err_expected_comma_or_rsquare);
 }
 
-SkipUntil(tok::r_square, tok::comma, tok::identifier,
-  StopAtSemi | StopBeforeMatch);
+// I don't know why this skipping was here
+// SkipUntil(tok::r_square, tok::comma, tok::identifier,
+//  StopAtSemi | StopBeforeMatch);
 if (Tok.is(tok::comma))
   ConsumeToken();
-else if (Tok.isNot(tok::identifier))
+else if (Tok.is(tok::r_square))
   break;
   }
 }
 
 if (isCXX11AttributeSpecifier())
   DiagnoseAndSkipCXX11Attributes();
 
+SourceLocation EllipsisLoc = {};
+
+if (Tok.is(tok::ellipsis)) {
+  if (!getLangOpts().CPlusPlus26)
+Diag(Tok, diag::warn_cxx2c_binding_pack);

cor3ntin wrote:

We should have an extension warning in c++26 mode (search for `diag::ext_cxx` 
for examples)

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


[clang] [Clang][P1061] Add stuctured binding packs (PR #121417)

2025-01-01 Thread via cfe-commits


@@ -1965,3 +1965,51 @@ CXXFoldExpr::CXXFoldExpr(QualType T, 
UnresolvedLookupExpr *Callee,
   SubExprs[SubExpr::RHS] = RHS;
   setDependence(computeDependence(this));
 }
+
+ResolvedUnexpandedPackExpr::ResolvedUnexpandedPackExpr(SourceLocation BL,
+   QualType QT,
+   unsigned NumExprs)
+: Expr(ResolvedUnexpandedPackExprClass, QT, VK_PRValue, OK_Ordinary),
+  BeginLoc(BL), NumExprs(NumExprs) {
+  setDependence(ExprDependence::TypeValueInstantiation |
+ExprDependence::UnexpandedPack);
+}
+
+ResolvedUnexpandedPackExpr *
+ResolvedUnexpandedPackExpr::CreateDeserialized(ASTContext &Ctx,
+   unsigned NumExprs) {
+  void *Mem = Ctx.Allocate(totalSizeToAlloc(NumExprs),
+   alignof(ResolvedUnexpandedPackExpr));
+  return new (Mem)
+  ResolvedUnexpandedPackExpr(SourceLocation(), QualType(), NumExprs);
+}
+
+ResolvedUnexpandedPackExpr *
+ResolvedUnexpandedPackExpr::Create(ASTContext &Ctx, SourceLocation BL,
+   QualType T, unsigned NumExprs) {
+  void *Mem = Ctx.Allocate(totalSizeToAlloc(NumExprs),
+   alignof(ResolvedUnexpandedPackExpr));
+  ResolvedUnexpandedPackExpr *New =
+  new (Mem) ResolvedUnexpandedPackExpr(BL, T, NumExprs);
+
+  auto Exprs = llvm::MutableArrayRef(New->getExprs(), New->getNumExprs());
+  std::fill(Exprs.begin(), Exprs.end(), nullptr);
+
+  return New;
+}
+
+ResolvedUnexpandedPackExpr *
+ResolvedUnexpandedPackExpr::Create(ASTContext &Ctx, SourceLocation BL,
+   QualType T, ArrayRef Exprs) {
+  auto *New = Create(Ctx, BL, T, Exprs.size());
+  std::copy(Exprs.begin(), Exprs.end(), New->getExprs());
+  return New;
+}
+
+ResolvedUnexpandedPackExpr *ResolvedUnexpandedPackExpr::getFromDecl(Decl *D) {
+  // TODO P1858: Extend to VarDecls for P1858
+  if (auto *BD = dyn_cast(D)) {
+return dyn_cast_or_null(BD->getBinding());

cor3ntin wrote:

```suggestion
return dyn_cast_if_present(BD->getBinding());
```

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


[clang-tools-extra] [clang-tidy] Create bugprone-incorrect-enable-shared-from-this check (PR #102299)

2025-01-01 Thread via cfe-commits

MichelleCDjunaidi wrote:

@5chmidti @EugeneZelenko Happy New Year! Is there anything left I need to do to 
get this merged?

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


[clang] [Clang] Repair the function "rParenEndsCast" to make incorrect judgments in template variable cases (PR #120904)

2025-01-01 Thread via cfe-commits


@@ -2831,8 +2842,21 @@ class AnnotatingParser {
 IsQualifiedPointerOrReference(BeforeRParen, LangOpts);
 bool ParensCouldEndDecl =
 AfterRParen->isOneOf(tok::equal, tok::semi, tok::l_brace, 
tok::greater);
-if (ParensAreType && !ParensCouldEndDecl)
+if (ParensAreType && !ParensCouldEndDecl) {
+  if (BeforeRParen->is(TT_TemplateCloser)) {
+if (determineUnaryOperatorByUsage(*AfterRParen))
+  return true;
+if (AfterRParen->isOneOf(tok::plus, tok::minus, tok::star, 
tok::exclaim,
+ tok::amp)) {
+  auto *Prev = BeforeRParen->MatchingParen->getPreviousNonComment();
+  for (auto &name : castIdentifiers)
+if (Prev->TokenText == name)
+  return true;
+  return false;

dty2 wrote:

You are right, but I would use the llvm alternative version of std::find which 
is in STLExtras.h, You're right, but I would use the llvm alternative version 
of std::find, which is in STLExtras.h.

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


[clang] [llvm] [RISCV] Add MIPS extensions (PR #121394)

2025-01-01 Thread Sam Elliott via cfe-commits


@@ -4963,6 +4963,10 @@ def msave_restore : Flag<["-"], "msave-restore">, 
Group,
 def mno_save_restore : Flag<["-"], "mno-save-restore">, 
Group,
   HelpText<"Disable using library calls for save and restore">;
 } // let Flags = [TargetSpecific]
+def mload_store_pairs : Flag<["-"], "mload-store-pairs">, 
Group;
+def mno_load_store_pairs : Flag<["-"], "mno-load-store-pairs">, 
Group;
+def mccmov : Flag<["-"], "mccmov">, Group;
+def mno_ccmov : Flag<["-"], "mno-ccmov">, Group;

lenary wrote:

The RISC-V backend has not added additional options (i.e. those not in the list 
`-march=`/`-mcpu=`/`-mabi=`) that change the target architecture extensions, 
and my understanding is this is on purpose (unlike in other targets). I think 
these would need more discussion before they are added.

I could understand gating optimisations to introduce these instructions behind 
additional arguments, but these seem to control whether specific instructions 
are or are not legal. 

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


[clang] [Clang][ASTMatcher] Add `dependentTemplateSpecializationType` AST mat… (PR #121435)

2025-01-01 Thread Amr Hesham via cfe-commits


@@ -2546,6 +2546,17 @@ Node Matchers
   };
 
 
+MatcherType>dependentTemplateSpecializationTypeMatcherDependentTemplateSpecializationType>...
+Matches dependent template 
specialization types.
+
+Example matches  A::template B

AmrDeveloper wrote:

```suggestion
Example matches A::template B
```

The same in `clang/include/clang/ASTMatchers/ASTMatchers.h`

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


[clang] [Clang][ASTMatcher] Add `dependentTemplateSpecializationType` AST mat… (PR #121435)

2025-01-01 Thread Amr Hesham via cfe-commits

https://github.com/AmrDeveloper requested changes to this pull request.


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


[clang] [Clang][ASTMatcher] Add `dependentTemplateSpecializationType` AST mat… (PR #121435)

2025-01-01 Thread Amr Hesham via cfe-commits


@@ -1113,6 +1113,8 @@ AST Matchers
 
 - Add ``dependentNameType`` matcher to match a dependent name type.
 
+- Add ``dependentTemplateSpecializationType`` matcher to match dependent 
template specialization types.

AmrDeveloper wrote:

```suggestion
- Add ``dependentTemplateSpecializationType`` matcher to match a dependent 
template specialization type.
```

The same in `clang/docs/LibASTMatchersReference.html` and 
`clang/include/clang/ASTMatchers/ASTMatchers.h`

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


[clang] [llvm] [ARM] Emit an error when the hard-float ABI is enabled but can't be used. (PR #111334)

2025-01-01 Thread Chris Copeland via cfe-commits

chrisnc wrote:

> RISC-V has similar checks here:
> 
> https://github.com/llvm/llvm-project/blob/ed572f2003275da8e06a634b4d6658b7921e8334/llvm/lib/Target/RISCV/RISCVISelLowering.cpp#L88-L100
> 
> So maybe the ARM checks could be added in a similar place? RISC-V handles ABI 
> variants in a very clean way, and it does seem to work in practice too, so 
> it'd be a good model for other architectures to follow.

I could try this approach here and see how it goes.

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


[clang] Make armv6 iOS by default instead of macOS when targeting Darwin (PR #117243)

2025-01-01 Thread via cfe-commits

https://github.com/Un1q32 updated 
https://github.com/llvm/llvm-project/pull/117243

>From 4a746cbe467f4ad22436dc206a8966ecaa77892f Mon Sep 17 00:00:00 2001
From: Un1q32 
Date: Thu, 21 Nov 2024 17:31:07 -0500
Subject: [PATCH] make armv6-darwin iOS by default

---
 clang/lib/Driver/ToolChains/Darwin.cpp | 3 ++-
 clang/test/Driver/darwin-version.c | 4 ++--
 2 files changed, 4 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 87380869f6fdab..3b858577ce625b 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -2145,7 +2145,8 @@ inferDeploymentTargetFromArch(DerivedArgList &Args, const 
Darwin &Toolchain,
   StringRef MachOArchName = Toolchain.getMachOArchName(Args);
   if (MachOArchName == "arm64" || MachOArchName == "arm64e")
 OSTy = llvm::Triple::MacOSX;
-  else if (MachOArchName == "armv7" || MachOArchName == "armv7s")
+  else if (MachOArchName == "armv7" || MachOArchName == "armv7s" ||
+   MachOArchName == "armv6")
 OSTy = llvm::Triple::IOS;
   else if (MachOArchName == "armv7k" || MachOArchName == "arm64_32")
 OSTy = llvm::Triple::WatchOS;
diff --git a/clang/test/Driver/darwin-version.c 
b/clang/test/Driver/darwin-version.c
index ff05d4c10c4877..a00bd832dc8028 100644
--- a/clang/test/Driver/darwin-version.c
+++ b/clang/test/Driver/darwin-version.c
@@ -1,6 +1,6 @@
 // RUN: %clang -target armv6-apple-darwin9 -c %s -### 2>&1 | \
-// RUN:   FileCheck --check-prefix=CHECK-VERSION-OSX %s
-// CHECK-VERSION-OSX: "armv6k-apple-macosx10.5.0"
+// RUN:   FileCheck --check-prefix=CHECK-VERSION-IOS %s
+// CHECK-VERSION-IOS: "armv6k-apple-ios5.0.0"
 // RUN: %clang -target armv6-apple-darwin9 -miphoneos-version-min=2.0 -c %s 
-### 2>&1 | \
 // RUN:   FileCheck --check-prefix=CHECK-VERSION-IOS2 %s
 // CHECK-VERSION-IOS2: "armv6k-apple-ios2.0.0"

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


[clang-tools-extra] [clangd] Remove clangd's HasValue GMock matcher (PR #121309)

2025-01-01 Thread Chris B via cfe-commits

https://github.com/llvm-beanz approved this pull request.


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


[clang] [clang][bytecode] Check for memcpy/memmove dummy pointers earlier (PR #121453)

2025-01-01 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr created 
https://github.com/llvm/llvm-project/pull/121453

None

>From 9aeae2efcfb038af30f01a07eb8960a4a59929f9 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Thu, 2 Jan 2025 06:28:08 +0100
Subject: [PATCH] [clang][bytecode] Check for memcpy/memmove dummy pointers
 earlier

---
 clang/lib/AST/ByteCode/InterpBuiltin.cpp | 7 ---
 clang/test/CodeGen/builtin-memfns.c  | 1 +
 2 files changed, 5 insertions(+), 3 deletions(-)

diff --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp 
b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index d0d8b03deab268..e9f3303f958d3e 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -1863,6 +1863,10 @@ static bool interp__builtin_memcpy(InterpState &S, 
CodePtr OpPC,
 return false;
   }
 
+  // Can't read from dummy pointers.
+  if (DestPtr.isDummy() || SrcPtr.isDummy())
+return false;
+
   QualType DestElemType;
   size_t RemainingDestElems;
   if (DestPtr.getFieldDesc()->isArray()) {
@@ -1925,9 +1929,6 @@ static bool interp__builtin_memcpy(InterpState &S, 
CodePtr OpPC,
 }
   }
 
-  // As a last resort, reject dummy pointers.
-  if (DestPtr.isDummy() || SrcPtr.isDummy())
-return false;
   assert(Size.getZExtValue() % DestElemSize == 0);
   if (!DoMemcpy(S, OpPC, SrcPtr, DestPtr, Bytes(Size.getZExtValue()).toBits()))
 return false;
diff --git a/clang/test/CodeGen/builtin-memfns.c 
b/clang/test/CodeGen/builtin-memfns.c
index 23c3c60b779b37..581eb85eb28e69 100644
--- a/clang/test/CodeGen/builtin-memfns.c
+++ b/clang/test/CodeGen/builtin-memfns.c
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -triple i386-pc-linux-gnu -emit-llvm < %s| FileCheck %s
+// RUN: %clang_cc1 -triple i386-pc-linux-gnu -emit-llvm 
-fexperimental-new-constant-interpreter < %s| FileCheck %s
 
 typedef __WCHAR_TYPE__ wchar_t;
 typedef __SIZE_TYPE__ size_t;

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


[clang] [clang][bytecode] Check for memcpy/memmove dummy pointers earlier (PR #121453)

2025-01-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes



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


2 Files Affected:

- (modified) clang/lib/AST/ByteCode/InterpBuiltin.cpp (+4-3) 
- (modified) clang/test/CodeGen/builtin-memfns.c (+1) 


``diff
diff --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp 
b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index d0d8b03deab268..e9f3303f958d3e 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -1863,6 +1863,10 @@ static bool interp__builtin_memcpy(InterpState &S, 
CodePtr OpPC,
 return false;
   }
 
+  // Can't read from dummy pointers.
+  if (DestPtr.isDummy() || SrcPtr.isDummy())
+return false;
+
   QualType DestElemType;
   size_t RemainingDestElems;
   if (DestPtr.getFieldDesc()->isArray()) {
@@ -1925,9 +1929,6 @@ static bool interp__builtin_memcpy(InterpState &S, 
CodePtr OpPC,
 }
   }
 
-  // As a last resort, reject dummy pointers.
-  if (DestPtr.isDummy() || SrcPtr.isDummy())
-return false;
   assert(Size.getZExtValue() % DestElemSize == 0);
   if (!DoMemcpy(S, OpPC, SrcPtr, DestPtr, Bytes(Size.getZExtValue()).toBits()))
 return false;
diff --git a/clang/test/CodeGen/builtin-memfns.c 
b/clang/test/CodeGen/builtin-memfns.c
index 23c3c60b779b37..581eb85eb28e69 100644
--- a/clang/test/CodeGen/builtin-memfns.c
+++ b/clang/test/CodeGen/builtin-memfns.c
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -triple i386-pc-linux-gnu -emit-llvm < %s| FileCheck %s
+// RUN: %clang_cc1 -triple i386-pc-linux-gnu -emit-llvm 
-fexperimental-new-constant-interpreter < %s| FileCheck %s
 
 typedef __WCHAR_TYPE__ wchar_t;
 typedef __SIZE_TYPE__ size_t;

``




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


[clang-tools-extra] [clangd] Add a unit test suite for HeuristicResolver (PR #121313)

2025-01-01 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 updated 
https://github.com/llvm/llvm-project/pull/121313

>From 9bb43932c38558741f5b26a29b7cadd9958b9eb7 Mon Sep 17 00:00:00 2001
From: Nathan Ridge 
Date: Sun, 6 Oct 2024 00:41:48 -0400
Subject: [PATCH] [clangd] Add a unit test suite for HeuristicResolver

Fixes https://github.com/clangd/clangd/issues/2154
---
 clang-tools-extra/clangd/HeuristicResolver.h  |   5 +-
 .../clangd/unittests/CMakeLists.txt   |   1 +
 .../unittests/HeuristicResolverTests.cpp  | 533 ++
 3 files changed, 537 insertions(+), 2 deletions(-)
 create mode 100644 
clang-tools-extra/clangd/unittests/HeuristicResolverTests.cpp

diff --git a/clang-tools-extra/clangd/HeuristicResolver.h 
b/clang-tools-extra/clangd/HeuristicResolver.h
index dcc063bbc4adc0..c130e0677e86dd 100644
--- a/clang-tools-extra/clangd/HeuristicResolver.h
+++ b/clang-tools-extra/clangd/HeuristicResolver.h
@@ -26,13 +26,14 @@ class UnresolvedUsingValueDecl;
 
 namespace clangd {
 
-// This class heuristic resolution of declarations and types in template code.
+// This class handles heuristic resolution of declarations and types in 
template
+// code.
 //
 // As a compiler, clang only needs to perform certain types of processing on
 // template code (such as resolving dependent names to declarations, or
 // resolving the type of a dependent expression) after instantiation. Indeed,
 // C++ language features such as template specialization mean such resolution
-// cannot be done accurately before instantiation
+// cannot be done accurately before instantiation.
 //
 // However, template code is written and read in uninstantiated form, and 
clangd
 // would like to provide editor features like go-to-definition in template code
diff --git a/clang-tools-extra/clangd/unittests/CMakeLists.txt 
b/clang-tools-extra/clangd/unittests/CMakeLists.txt
index dffdcd5d014ca9..8dba8088908d5e 100644
--- a/clang-tools-extra/clangd/unittests/CMakeLists.txt
+++ b/clang-tools-extra/clangd/unittests/CMakeLists.txt
@@ -64,6 +64,7 @@ add_unittest(ClangdUnitTests ClangdTests
   GlobalCompilationDatabaseTests.cpp
   HeadersTests.cpp
   HeaderSourceSwitchTests.cpp
+  HeuristicResolverTests.cpp
   HoverTests.cpp
   IncludeCleanerTests.cpp
   IndexActionTests.cpp
diff --git a/clang-tools-extra/clangd/unittests/HeuristicResolverTests.cpp 
b/clang-tools-extra/clangd/unittests/HeuristicResolverTests.cpp
new file mode 100644
index 00..f1d7fdee3bd87d
--- /dev/null
+++ b/clang-tools-extra/clangd/unittests/HeuristicResolverTests.cpp
@@ -0,0 +1,533 @@
+//===-- HeuristicResolverTests.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 "HeuristicResolver.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/Tooling.h"
+#include "gmock/gmock-matchers.h"
+#include "gtest/gtest.h"
+
+using namespace clang::ast_matchers;
+using clang::clangd::HeuristicResolver;
+using testing::ElementsAre;
+
+namespace clang {
+namespace {
+
+// Helper for matching a sequence of elements with a variadic list of matchers.
+// Usage: `ElementsAre(matchAdapter(Vs, MatchFunction)...)`, where `Vs...` is
+//a variadic list of matchers.
+// For each `V` in `Vs`, this will match the corresponding element `E` if
+// `MatchFunction(V, E)` is true.
+MATCHER_P2(matchAdapter, MatcherForElement, MatchFunction, "matchAdapter") {
+  return MatchFunction(MatcherForElement, arg);
+}
+
+template 
+using ResolveFnT = std::function(
+const HeuristicResolver *, const InputNode *)>;
+
+// Test heuristic resolution on `Code` using the resolution procedure
+// `ResolveFn`, which takes a `HeuristicResolver` and an input AST node of type
+// `InputNode` and returns a `std::vector`.
+// `InputMatcher` should be an AST matcher that matches a single node to pass 
as
+// input to `ResolveFn`, bound to the ID "input". `OutputMatchers` should be 
AST
+// matchers that each match a single node, bound to the ID "output".
+template 
+void expectResolution(llvm::StringRef Code, ResolveFnT ResolveFn,
+  const InputMatcher &IM, const OutputMatchers &...OMS) {
+  auto TU = tooling::buildASTFromCodeWithArgs(Code, {"-std=c++20"});
+  auto &Ctx = TU->getASTContext();
+  auto InputMatches = match(IM, Ctx);
+  ASSERT_EQ(1u, InputMatches.size());
+  const auto *Input = InputMatches[0].template getNodeAs("input");
+  ASSERT_TRUE(Input);
+
+  auto OutputNodeMatches = [&](auto &OutputMatcher, auto &Actual) {
+auto OutputMatches = match(OutputMatcher, Ctx);
+if (OutputMatches.size() != 1u)
+  return false;
+const auto *ExpectedOutput =
+OutputMatches[0].template getNodeAs("output");
+

[clang-tools-extra] [clangd] Add a unit test suite for HeuristicResolver (PR #121313)

2025-01-01 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 updated 
https://github.com/llvm/llvm-project/pull/121313

>From 052d67acf9d1f28ba487557d8bba6732fbab538f Mon Sep 17 00:00:00 2001
From: Nathan Ridge 
Date: Sun, 6 Oct 2024 00:41:48 -0400
Subject: [PATCH] [clangd] Add a unit test suite for HeuristicResolver

Fixes https://github.com/clangd/clangd/issues/2154
---
 clang-tools-extra/clangd/HeuristicResolver.h  |   5 +-
 .../clangd/unittests/CMakeLists.txt   |   1 +
 .../unittests/HeuristicResolverTests.cpp  | 535 ++
 3 files changed, 539 insertions(+), 2 deletions(-)
 create mode 100644 
clang-tools-extra/clangd/unittests/HeuristicResolverTests.cpp

diff --git a/clang-tools-extra/clangd/HeuristicResolver.h 
b/clang-tools-extra/clangd/HeuristicResolver.h
index dcc063bbc4adc0..c130e0677e86dd 100644
--- a/clang-tools-extra/clangd/HeuristicResolver.h
+++ b/clang-tools-extra/clangd/HeuristicResolver.h
@@ -26,13 +26,14 @@ class UnresolvedUsingValueDecl;
 
 namespace clangd {
 
-// This class heuristic resolution of declarations and types in template code.
+// This class handles heuristic resolution of declarations and types in 
template
+// code.
 //
 // As a compiler, clang only needs to perform certain types of processing on
 // template code (such as resolving dependent names to declarations, or
 // resolving the type of a dependent expression) after instantiation. Indeed,
 // C++ language features such as template specialization mean such resolution
-// cannot be done accurately before instantiation
+// cannot be done accurately before instantiation.
 //
 // However, template code is written and read in uninstantiated form, and 
clangd
 // would like to provide editor features like go-to-definition in template code
diff --git a/clang-tools-extra/clangd/unittests/CMakeLists.txt 
b/clang-tools-extra/clangd/unittests/CMakeLists.txt
index dffdcd5d014ca9..8dba8088908d5e 100644
--- a/clang-tools-extra/clangd/unittests/CMakeLists.txt
+++ b/clang-tools-extra/clangd/unittests/CMakeLists.txt
@@ -64,6 +64,7 @@ add_unittest(ClangdUnitTests ClangdTests
   GlobalCompilationDatabaseTests.cpp
   HeadersTests.cpp
   HeaderSourceSwitchTests.cpp
+  HeuristicResolverTests.cpp
   HoverTests.cpp
   IncludeCleanerTests.cpp
   IndexActionTests.cpp
diff --git a/clang-tools-extra/clangd/unittests/HeuristicResolverTests.cpp 
b/clang-tools-extra/clangd/unittests/HeuristicResolverTests.cpp
new file mode 100644
index 00..1655b4066f69ac
--- /dev/null
+++ b/clang-tools-extra/clangd/unittests/HeuristicResolverTests.cpp
@@ -0,0 +1,535 @@
+//===-- HeuristicResolverTests.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 "HeuristicResolver.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/Tooling.h"
+#include "gmock/gmock-matchers.h"
+#include "gtest/gtest.h"
+
+using namespace clang::ast_matchers;
+using clang::clangd::HeuristicResolver;
+using testing::ElementsAre;
+
+namespace clang {
+namespace {
+
+// Helper for matching a sequence of elements with a variadic list of matchers.
+// Usage: `ElementsAre(matchAdapter(Vs, MatchFunction)...)`, where `Vs...` is
+//a variadic list of matchers.
+// For each `V` in `Vs`, this will match the corresponding element `E` if
+// `MatchFunction(V, E)` is true.
+MATCHER_P2(matchAdapter, MatcherForElement, MatchFunction, "matchAdapter") {
+  return MatchFunction(MatcherForElement, arg);
+}
+
+template 
+using ResolveFnT = std::function(
+const HeuristicResolver *, const InputNode *)>;
+
+// Test heuristic resolution on `Code` using the resolution procedure
+// `ResolveFn`, which takes a `HeuristicResolver` and an input AST node of type
+// `InputNode` and returns a `std::vector`.
+// `InputMatcher` should be an AST matcher that matches a single node to pass 
as
+// input to `ResolveFn`, bound to the ID "input". `OutputMatchers` should be 
AST
+// matchers that each match a single node, bound to the ID "output".
+template 
+void expectResolution(llvm::StringRef Code, ResolveFnT ResolveFn,
+  const InputMatcher &IM, const OutputMatchers &...OMS) {
+  auto TU = tooling::buildASTFromCodeWithArgs(Code, {"-std=c++20"});
+  auto &Ctx = TU->getASTContext();
+  auto InputMatches = match(IM, Ctx);
+  ASSERT_EQ(1u, InputMatches.size());
+  const auto *Input = InputMatches[0].template getNodeAs("input");
+  ASSERT_TRUE(Input);
+
+  auto OutputNodeMatches = [&](auto &OutputMatcher, auto &Actual) {
+auto OutputMatches = match(OutputMatcher, Ctx);
+if (OutputMatches.size() != 1u)
+  return false;
+const auto *ExpectedOutput =
+OutputMatches[0].template getNodeAs("output");
+

[clang-tools-extra] [clangd] Add a unit test suite for HeuristicResolver (PR #121313)

2025-01-01 Thread Nathan Ridge via cfe-commits


@@ -0,0 +1,521 @@
+//===-- HeuristicResolverTests.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 "HeuristicResolver.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/Tooling.h"
+#include "gmock/gmock-matchers.h"
+#include "gtest/gtest.h"
+
+using namespace clang::ast_matchers;
+using clang::clangd::HeuristicResolver;
+using testing::ElementsAre;
+
+namespace clang {
+namespace {
+
+// Helper for matching a sequence of elements with a variadic list of matchers.
+// Usage: `ElementsAre(matchAdapter(Vs, MatchFunction)...)`, where `Vs...` is
+//a variadic list of matchers.
+// For each `V` in `Vs`, this will match the corresponding element `E` if
+// `MatchFunction(V, E)` is true.
+MATCHER_P2(matchAdapter, MatcherForElement, MatchFunction, "matchAdapter") {
+  return MatchFunction(MatcherForElement, arg);
+}
+
+template 
+using ResolveFnT = std::function(
+const HeuristicResolver *, const InputNode *)>;
+
+// Test heuristic resolution on `Code` using the resolution procedure
+// `ResolveFn`, which takes a `HeuristicResolver` and an input AST node of type
+// `InputNode` and returns a `std::vector`.
+// `InputMatcher` should be an AST matcher that matches a single node to pass 
as
+// input to `ResolveFn`, bound to the ID "input". `OutputMatchers` should be 
AST
+// matchers that each match a single node, bound to the ID "output".
+template 
+void expectResolution(llvm::StringRef Code, ResolveFnT ResolveFn,
+  const InputMatcher &IM, const OutputMatchers &...OMS) {
+  auto TU = tooling::buildASTFromCodeWithArgs(Code, {"-std=c++20"});
+  auto &Ctx = TU->getASTContext();
+  auto InputMatches = match(IM, Ctx);
+  ASSERT_EQ(1u, InputMatches.size());
+  const auto *Input = InputMatches[0].template getNodeAs("input");
+  ASSERT_TRUE(Input);
+
+  auto OutputNodeMatches = [&](auto &OutputMatcher, auto &Actual) {
+auto OutputMatches = match(OutputMatcher, Ctx);
+if (OutputMatches.size() != 1u)
+  return false;
+const auto *ExpectedOutput =
+OutputMatches[0].template getNodeAs("output");
+if (!ExpectedOutput)
+  return false;
+return ExpectedOutput == Actual;
+  };
+
+  HeuristicResolver H(Ctx);
+  auto Results = ResolveFn(&H, Input);
+  EXPECT_THAT(Results, ElementsAre(matchAdapter(OMS, OutputNodeMatches)...));
+}
+
+// Wrapper for the above that accepts a HeuristicResolver member function
+// pointer directly.
+template 
+void expectResolution(llvm::StringRef Code,
+  std::vector (
+  HeuristicResolver::*ResolveFn)(const InputNode *)
+  const,
+  const InputMatcher &IM, const OutputMatchers &...OMS) {
+  expectResolution(Code, ResolveFnT(std::mem_fn(ResolveFn)), IM,
+   OMS...);
+}
+
+TEST(HeuristicResolver, MemberExpr) {
+  std::string Code = R"cpp(
+template 
+struct S {
+  void bar() {}
+};
+
+template 
+void foo(S arg) {
+  arg.bar();
+}
+  )cpp";
+  // Test resolution of "bar" in "arg.bar()".
+  expectResolution(Code, &HeuristicResolver::resolveMemberExpr,
+   cxxDependentScopeMemberExpr().bind("input"),

HighCommander4 wrote:

Ok, I've updated the patch to make use of `hasMemberName()` for 
`CXXDependentScopeMemberExpr`, and also added more detail to some other 
matchers.

Two exceptions are `dependentScopeDeclRefExpr()` and `dependentNameType()` -- 
these matchers were both added recently, and do not yet have any matchers for 
their properties similar to `hasMemberName()`. I can explore adding some 
(though I'd prefer to do that as a follow-up enhancememnt), or switch to the 
indirect matching approach for these, or I'm open to other ideas.

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


[clang] 1a0d0ae - [clang-format] Add `VariableTemplates` option (#121318)

2025-01-01 Thread via cfe-commits

Author: Owen Pan
Date: 2025-01-01T18:24:56-08:00
New Revision: 1a0d0ae234544dc4978f1e12730408cb83f6b923

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

LOG: [clang-format] Add `VariableTemplates` option (#121318)

Closes #120148.

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/docs/ReleaseNotes.rst
clang/include/clang/Format/Format.h
clang/lib/Format/Format.cpp
clang/lib/Format/FormatToken.h
clang/lib/Format/FormatTokenLexer.cpp
clang/lib/Format/FormatTokenLexer.h
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index c175436a2817a9..d9b3f666df03c0 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -6798,6 +6798,15 @@ the configuration (without a prefix: ``Auto``).
 
 
 
+.. _VariableTemplates:
+
+**VariableTemplates** (``List of Strings``) :versionbadge:`clang-format 20` 
:ref:`¶ `
+  A vector of non-keyword identifiers that should be interpreted as variable
+  template names.
+
+  A ``)`` after a variable template instantiation is **not** annotated as
+  the closing parenthesis of C-style cast operator.
+
 .. _VerilogBreakBetweenInstancePorts:
 
 **VerilogBreakBetweenInstancePorts** (``Boolean``) :versionbadge:`clang-format 
17` :ref:`¶ `

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 662c575bad3e8b..e0aef1af2135cd 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -1125,6 +1125,7 @@ clang-format
 - Adds ``RemoveEmptyLinesInUnwrappedLines`` option.
 - Adds ``KeepFormFeed`` option and set it to ``true`` for ``GNU`` style.
 - Adds ``AllowShortNamespacesOnASingleLine`` option.
+- Adds ``VariableTemplates`` option.
 - Adds support for bash globstar in ``.clang-format-ignore``.
 
 libclang

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index eefaabf9392fd7..bb34f2d33ac15e 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -5103,6 +5103,15 @@ struct FormatStyle {
   /// \version 3.7
   UseTabStyle UseTab;
 
+  /// A vector of non-keyword identifiers that should be interpreted as 
variable
+  /// template names.
+  ///
+  /// A ``)`` after a variable template instantiation is **not** annotated as
+  /// the closing parenthesis of C-style cast operator.
+  ///
+  /// \version 20
+  std::vector VariableTemplates;
+
   /// For Verilog, put each port on its own line in module instantiations.
   /// \code
   ///true:
@@ -5314,7 +5323,7 @@ struct FormatStyle {
TableGenBreakInsideDAGArg == R.TableGenBreakInsideDAGArg &&
TabWidth == R.TabWidth && TemplateNames == R.TemplateNames &&
TypeNames == R.TypeNames && TypenameMacros == R.TypenameMacros &&
-   UseTab == R.UseTab &&
+   UseTab == R.UseTab && VariableTemplates == R.VariableTemplates &&
VerilogBreakBetweenInstancePorts ==
R.VerilogBreakBetweenInstancePorts &&
WhitespaceSensitiveMacros == R.WhitespaceSensitiveMacros;

diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 8f44e9f00212cf..a5657f2d910f68 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1166,6 +1166,7 @@ template <> struct MappingTraits {
 IO.mapOptional("TypeNames", Style.TypeNames);
 IO.mapOptional("TypenameMacros", Style.TypenameMacros);
 IO.mapOptional("UseTab", Style.UseTab);
+IO.mapOptional("VariableTemplates", Style.VariableTemplates);
 IO.mapOptional("VerilogBreakBetweenInstancePorts",
Style.VerilogBreakBetweenInstancePorts);
 IO.mapOptional("WhitespaceSensitiveMacros",

diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index f6bb860a1fea31..8917049cefb865 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -186,6 +186,7 @@ namespace format {
   TYPE(UnionLBrace)
\
   TYPE(UnionRBrace)
\
   TYPE(UntouchableMacroFunc)   
\
+  TYPE(VariableTemplate)   
\
   /* Like in 'assign x = 0, y = 1;' . */   
\
   TYPE(VerilogAssignComma) 
\
   /* like in begin : block */  
\

diff  --git a/clang/lib/Format/FormatTokenLexer.cpp 
b/clang/lib/Format/FormatTokenLexer.cpp
index 7a264bddcdfe19..0f8d4940d

[clang] [clang-format] Add `VariableTemplates` option (PR #121318)

2025-01-01 Thread Owen Pan via cfe-commits

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


[clang-tools-extra] bc87a53 - [clangd] Remove clangd's HasValue GMock matcher (#121309)

2025-01-01 Thread via cfe-commits

Author: Nathan Ridge
Date: 2025-01-02T01:42:21-05:00
New Revision: bc87a537d9b8117cfd63d5d9b798d6017a99097f

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

LOG: [clangd] Remove clangd's HasValue GMock matcher (#121309)

An equivalent matcher under the name Optional has since been added
upstream to GMock.

Fixes https://github.com/llvm/llvm-project/issues/121308

Added: 


Modified: 
clang-tools-extra/clangd/unittests/Matchers.h
clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/unittests/Matchers.h 
b/clang-tools-extra/clangd/unittests/Matchers.h
index 0fbd93b2e68825..17d18dd9b85b65 100644
--- a/clang-tools-extra/clangd/unittests/Matchers.h
+++ b/clang-tools-extra/clangd/unittests/Matchers.h
@@ -127,74 +127,6 @@ PolySubsequenceMatcher HasSubsequence(Args &&... 
M) {
 llvm::consumeError(ComputedValue.takeError()); 
\
   } while (false)
 
-// Implements the HasValue(m) matcher for matching an Optional whose
-// value matches matcher m.
-template  class OptionalMatcher {
-public:
-  explicit OptionalMatcher(const InnerMatcher &matcher) : matcher_(matcher) {}
-  OptionalMatcher(const OptionalMatcher&) = default;
-  OptionalMatcher &operator=(const OptionalMatcher&) = delete;
-
-  // This type conversion operator template allows Optional(m) to be
-  // used as a matcher for any Optional type whose value type is
-  // compatible with the inner matcher.
-  //
-  // The reason we do this instead of relying on
-  // MakePolymorphicMatcher() is that the latter is not flexible
-  // enough for implementing the DescribeTo() method of Optional().
-  template  operator Matcher() const {
-return MakeMatcher(new Impl(matcher_));
-  }
-
-private:
-  // The monomorphic implementation that works for a particular optional type.
-  template 
-  class Impl : public ::testing::MatcherInterface {
-  public:
-using Value = typename std::remove_const<
-typename std::remove_reference::type>::type::value_type;
-
-explicit Impl(const InnerMatcher &matcher)
-: matcher_(::testing::MatcherCast(matcher)) {}
-
-Impl(const Impl&) = default;
-Impl &operator=(const Impl&) = delete;
-
-virtual void DescribeTo(::std::ostream *os) const {
-  *os << "has a value that ";
-  matcher_.DescribeTo(os);
-}
-
-virtual void DescribeNegationTo(::std::ostream *os) const {
-  *os << "does not have a value that ";
-  matcher_.DescribeTo(os);
-}
-
-virtual bool
-MatchAndExplain(Optional optional,
-::testing::MatchResultListener *listener) const {
-  if (!optional)
-return false;
-
-  *listener << "which has a value ";
-  return MatchPrintAndExplain(*optional, matcher_, listener);
-}
-
-  private:
-const Matcher matcher_;
-  };
-
-  const InnerMatcher matcher_;
-};
-
-// Creates a matcher that matches an Optional that has a value
-// that matches inner_matcher.
-template 
-inline OptionalMatcher
-HasValue(const InnerMatcher &inner_matcher) {
-  return OptionalMatcher(inner_matcher);
-}
-
 } // namespace clangd
 } // namespace clang
 #endif

diff  --git a/clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp 
b/clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp
index 15158d8a45ca8b..406a842f5a0081 100644
--- a/clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp
+++ b/clang-tools-extra/clangd/unittests/TypeHierarchyTests.cpp
@@ -28,6 +28,7 @@ using ::testing::ElementsAre;
 using ::testing::Field;
 using ::testing::IsEmpty;
 using ::testing::Matcher;
+using ::testing::Optional;
 using ::testing::SizeIs;
 using ::testing::UnorderedElementsAre;
 
@@ -38,12 +39,12 @@ MATCHER_P(selectionRangeIs, R, "") { return 
arg.selectionRange == R; }
 template 
 ::testing::Matcher parents(ParentMatchers... ParentsM) {
   return Field(&TypeHierarchyItem::parents,
-   HasValue(UnorderedElementsAre(ParentsM...)));
+   Optional(UnorderedElementsAre(ParentsM...)));
 }
 template 
 ::testing::Matcher children(ChildMatchers... ChildrenM) {
   return Field(&TypeHierarchyItem::children,
-   HasValue(UnorderedElementsAre(ChildrenM...)));
+   Optional(UnorderedElementsAre(ChildrenM...)));
 }
 // Note: "not resolved" is 
diff erent from "resolved but empty"!
 MATCHER(parentsNotResolved, "") { return !arg.parents; }
@@ -790,7 +791,7 @@ struct Child : Parent1, Parent2 {};
   Children,
   UnorderedElementsAre(
   AllOf(withName("Child"),
-withResolveParents(HasValue(UnorderedElementsAre(withResolveID(
+withResolveParents(Optional(UnorderedElementsAre(withResolveID(
 getSymbolID(&findDecl(AST, "Parent1")).str(

[clang-tools-extra] [clangd] Remove clangd's HasValue GMock matcher (PR #121309)

2025-01-01 Thread Nathan Ridge via cfe-commits

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


[clang] [clang-format] extend clang-format directive with options to prevent formatting for one line (PR #118566)

2025-01-01 Thread Oleksandr T. via cfe-commits

a-tarasyuk wrote:

> I’m fine with continuing the discussion in the GitHub issue

Ok, let's move the discussion to the issue, and I'll delete the PR. From there, 
we can summarize all the concerns to proceed with a decision on this proposal. 
I think it would be useful to add comments or update the status of the issue to 
avoid anyone spending time on development because before I started working on 
it proposal seemed to have no concerns and was ready for development.


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


[clang] [Clang] Repair the function "rParenEndsCast" to make incorrect judgments in template variable cases (PR #120904)

2025-01-01 Thread via cfe-commits


@@ -2831,8 +2842,21 @@ class AnnotatingParser {
 IsQualifiedPointerOrReference(BeforeRParen, LangOpts);
 bool ParensCouldEndDecl =
 AfterRParen->isOneOf(tok::equal, tok::semi, tok::l_brace, 
tok::greater);
-if (ParensAreType && !ParensCouldEndDecl)
+if (ParensAreType && !ParensCouldEndDecl) {
+  if (BeforeRParen->is(TT_TemplateCloser)) {
+if (determineUnaryOperatorByUsage(*AfterRParen))
+  return true;
+if (AfterRParen->isOneOf(tok::plus, tok::minus, tok::star, 
tok::exclaim,
+ tok::amp)) {
+  auto *Prev = BeforeRParen->MatchingParen->getPreviousNonComment();
+  for (auto &name : castIdentifiers)
+if (Prev->TokenText == name)
+  return true;
+  return false;

dty2 wrote:

You are right, but I would use the llvm alternative version of std::find which 
is in STLExtras.h called "llvm::find".

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


[clang] Make armv6 iOS by default instead of macOS when targeting Darwin (PR #117243)

2025-01-01 Thread via cfe-commits

Un1q32 wrote:

bump

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


[clang] [Clang][P1061] Add stuctured binding packs (PR #121417)

2025-01-01 Thread Jason Rice via cfe-commits


@@ -5397,6 +5393,13 @@ bool ValueDecl::isInitCapture() const {
   return false;
 }
 
+bool ValueDecl::isParameterPack() const {
+  if (const auto *NTTP = dyn_cast(this))
+return NTTP->isParameterPack();
+
+  return isa_and_nonnull(getType().getTypePtrOrNull());

ricejasonf wrote:

Adding the assert had it being triggered from a lot of tests so I am removing 
it for now.

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


[clang] [clang-format] Add BreakBeforeTemplateClose option (PR #118046)

2025-01-01 Thread via cfe-commits

https://github.com/leijurv updated 
https://github.com/llvm/llvm-project/pull/118046

>From 1caf823165b16f6701993d586df51d5cdbf0885e Mon Sep 17 00:00:00 2001
From: Leijurv 
Date: Fri, 29 Nov 2024 21:54:36 -0600
Subject: [PATCH 1/4] [clang-format] Add BreakBeforeTemplateClose option

---
 clang/docs/ClangFormatStyleOptions.rst |  21 
 clang/docs/ReleaseNotes.rst|   1 +
 clang/include/clang/Format/Format.h|  20 
 clang/lib/Format/ContinuationIndenter.cpp  |  11 ++
 clang/lib/Format/ContinuationIndenter.h|  26 ++--
 clang/lib/Format/Format.cpp|   2 +
 clang/lib/Format/TokenAnnotator.cpp|   2 +-
 clang/unittests/Format/ConfigParseTest.cpp |   1 +
 clang/unittests/Format/FormatTest.cpp  | 131 +
 9 files changed, 206 insertions(+), 9 deletions(-)

diff --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 4be448171699ca..84ab1b0a2eff61 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -3416,6 +3416,27 @@ the configuration (without a prefix: ``Auto``).
 
 
 
+.. _BreakBeforeTemplateClose:
+
+**BreakBeforeTemplateClose** (``Boolean``) :versionbadge:`clang-format 20` 
:ref:`¶ `
+  If ``true``, a line break will be placed before the ``>`` in a multiline
+  template declaration.
+
+  .. code-block:: c++
+
+ true:
+ template <
+ typename Foo,
+ typename Bar,
+ typename Baz
+ >
+
+ false:
+ template <
+ typename Foo,
+ typename Bar,
+ typename Baz>
+
 .. _BreakBeforeTernaryOperators:
 
 **BreakBeforeTernaryOperators** (``Boolean``) :versionbadge:`clang-format 3.7` 
:ref:`¶ `
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index e44aefa90ab386..867d4b5d8c3f18 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -976,6 +976,7 @@ clang-format
   ``Never``, and ``true`` to ``Always``.
 - Adds ``RemoveEmptyLinesInUnwrappedLines`` option.
 - Adds ``KeepFormFeed`` option and set it to ``true`` for ``GNU`` style.
+- Adds ``BreakBeforeTemplateClose`` option.
 
 libclang
 
diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 6383934afa2c40..bffd964f6aa8aa 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -2248,6 +2248,25 @@ struct FormatStyle {
   /// \version 16
   BreakBeforeInlineASMColonStyle BreakBeforeInlineASMColon;
 
+  /// If ``true``, a line break will be placed before the ``>`` in a multiline
+  /// template declaration.
+  /// \code
+  ///true:
+  ///template <
+  ///typename Foo,
+  ///typename Bar,
+  ///typename Baz
+  ///>
+  ///
+  ///false:
+  ///template <
+  ///typename Foo,
+  ///typename Bar,
+  ///typename Baz>
+  /// \endcode
+  /// \version 20
+  bool BreakBeforeTemplateClose;
+
   /// If ``true``, ternary operators will be placed after line breaks.
   /// \code
   ///true:
@@ -5184,6 +5203,7 @@ struct FormatStyle {
BreakBeforeBraces == R.BreakBeforeBraces &&
BreakBeforeConceptDeclarations == R.BreakBeforeConceptDeclarations 
&&
BreakBeforeInlineASMColon == R.BreakBeforeInlineASMColon &&
+   BreakBeforeTemplateClose == R.BreakBeforeTemplateClose &&
BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
BreakBinaryOperations == R.BreakBinaryOperations &&
BreakConstructorInitializers == R.BreakConstructorInitializers &&
diff --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index aed86c1fb99551..4c783623afc535 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -406,6 +406,10 @@ bool ContinuationIndenter::mustBreak(const LineState 
&State) {
   }
   if (CurrentState.BreakBeforeClosingParen && Current.is(tok::r_paren))
 return true;
+  if (CurrentState.BreakBeforeClosingAngle &&
+  Current.ClosesTemplateDeclaration && Style.BreakBeforeTemplateClose) {
+return true;
+  }
   if (Style.Language == FormatStyle::LK_ObjC &&
   Style.ObjCBreakBeforeNestedBlockParam &&
   Current.ObjCSelectorNameParts > 1 &&
@@ -1234,6 +1238,9 @@ unsigned 
ContinuationIndenter::addTokenOnNewLine(LineState &State,
 Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent;
   }
 
+  if (PreviousNonComment && PreviousNonComment->is(tok::less))
+CurrentState.BreakBeforeClosingAngle = true;
+
   if (CurrentState.AvoidBinPacking) {
 // If we are breaking after '(', '{', '<', or this is the break after a ':'
 // to start a member initializer list in a constructor, this should not
@@ -1370,6 +1377,10 @@ unsigned ContinuationIndenter::getNewLineColumn(const 
LineState &State) {
   State.Stack.size() > 1) {
 return State.Stack[State.Stack.size() - 2].Last

[clang] [Clang] Repair the function "rParenEndsCast" to make incorrect judgments in template variable cases (PR #120904)

2025-01-01 Thread via cfe-commits

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


[clang] [Clang] Repair the function "rParenEndsCast" to make incorrect judgments in template variable cases (PR #120904)

2025-01-01 Thread via cfe-commits


@@ -2474,6 +2480,11 @@ class AnnotatingParser {
   Current.getNextNonComment()->isOneOf(tok::comma, tok::r_brace)) {
 Current.setType(TT_StringInConcatenation);
   }
+} else if (Style.isCpp() && Current.is(tok::kw_using)) {
+  if (Current.Next && Current.Next->Next && Current.Next->Next->Next) {
+if (Current.Next->Next->Next->isTypeName(LangOpts))

dty2 wrote:

You are right, I would plan to do it using the way you mentioned in #121318.

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


[clang] [clang-format][NFC] Add missing config tests for List of Strings (PR #121451)

2025-01-01 Thread Owen Pan via cfe-commits

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

None

>From 305aacf68126a7827376a0718a774006f10879f4 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Wed, 1 Jan 2025 20:15:26 -0800
Subject: [PATCH] [clang-format][NFC] Add missing config tests for List of
 Strings

---
 clang/unittests/Format/ConfigParseTest.cpp | 17 -
 1 file changed, 12 insertions(+), 5 deletions(-)

diff --git a/clang/unittests/Format/ConfigParseTest.cpp 
b/clang/unittests/Format/ConfigParseTest.cpp
index b249bf073aa453..6e59b687e3a23e 100644
--- a/clang/unittests/Format/ConfigParseTest.cpp
+++ b/clang/unittests/Format/ConfigParseTest.cpp
@@ -144,6 +144,9 @@ TEST(ConfigParseTest, GetsCorrectBasedOnStyle) {
   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());  
\
   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
 
+#define CHECK_PARSE_LIST(FIELD)
\
+  CHECK_PARSE(#FIELD ": [foo]", FIELD, std::vector{"foo"})
+
 #define CHECK_PARSE_NESTED_VALUE(TEXT, STRUCT, FIELD, VALUE)   
\
   EXPECT_NE(VALUE, Style.STRUCT.FIELD) << "Initial value already the same!";   
\
   EXPECT_EQ(0, parseConfiguration(#STRUCT ":\n  " TEXT, &Style).value());  
\
@@ -899,11 +902,15 @@ TEST(ConfigParseTest, ParsesConfiguration) {
   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", 
StatementMacros,
   std::vector({"QUNUSED", "QT_REQUIRE_VERSION"}));
 
-  Style.NamespaceMacros.clear();
-  CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
-  std::vector{"TESTSUITE"});
-  CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
-  std::vector({"TESTSUITE", "SUITE"}));
+  CHECK_PARSE_LIST(JavaImportGroups);
+  CHECK_PARSE_LIST(Macros);
+  CHECK_PARSE_LIST(NamespaceMacros);
+  CHECK_PARSE_LIST(ObjCPropertyAttributeOrder);
+  CHECK_PARSE_LIST(TableGenBreakingDAGArgOperators);
+  CHECK_PARSE_LIST(TemplateNames);
+  CHECK_PARSE_LIST(TypeNames);
+  CHECK_PARSE_LIST(TypenameMacros);
+  CHECK_PARSE_LIST(VariableTemplates);
 
   Style.WhitespaceSensitiveMacros.clear();
   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",

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


[clang] [clang-format][NFC] Add missing config tests for List of Strings (PR #121451)

2025-01-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Owen Pan (owenca)


Changes



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


1 Files Affected:

- (modified) clang/unittests/Format/ConfigParseTest.cpp (+12-5) 


``diff
diff --git a/clang/unittests/Format/ConfigParseTest.cpp 
b/clang/unittests/Format/ConfigParseTest.cpp
index b249bf073aa453..6e59b687e3a23e 100644
--- a/clang/unittests/Format/ConfigParseTest.cpp
+++ b/clang/unittests/Format/ConfigParseTest.cpp
@@ -144,6 +144,9 @@ TEST(ConfigParseTest, GetsCorrectBasedOnStyle) {
   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());  
\
   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
 
+#define CHECK_PARSE_LIST(FIELD)
\
+  CHECK_PARSE(#FIELD ": [foo]", FIELD, std::vector{"foo"})
+
 #define CHECK_PARSE_NESTED_VALUE(TEXT, STRUCT, FIELD, VALUE)   
\
   EXPECT_NE(VALUE, Style.STRUCT.FIELD) << "Initial value already the same!";   
\
   EXPECT_EQ(0, parseConfiguration(#STRUCT ":\n  " TEXT, &Style).value());  
\
@@ -899,11 +902,15 @@ TEST(ConfigParseTest, ParsesConfiguration) {
   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", 
StatementMacros,
   std::vector({"QUNUSED", "QT_REQUIRE_VERSION"}));
 
-  Style.NamespaceMacros.clear();
-  CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
-  std::vector{"TESTSUITE"});
-  CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
-  std::vector({"TESTSUITE", "SUITE"}));
+  CHECK_PARSE_LIST(JavaImportGroups);
+  CHECK_PARSE_LIST(Macros);
+  CHECK_PARSE_LIST(NamespaceMacros);
+  CHECK_PARSE_LIST(ObjCPropertyAttributeOrder);
+  CHECK_PARSE_LIST(TableGenBreakingDAGArgOperators);
+  CHECK_PARSE_LIST(TemplateNames);
+  CHECK_PARSE_LIST(TypeNames);
+  CHECK_PARSE_LIST(TypenameMacros);
+  CHECK_PARSE_LIST(VariableTemplates);
 
   Style.WhitespaceSensitiveMacros.clear();
   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",

``




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


[clang] [clang-format] Add `VariableTemplates` option (PR #121318)

2025-01-01 Thread Owen Pan via cfe-commits

owenca wrote:

> > Should there be a parse test?
> 
> About half of the `List of Strings` options don't have a `CHECK_PARSE` test. 
> I'll fix that in a separate patch.

See #121451.

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


[clang-tools-extra] [clangd] Add a unit test suite for HeuristicResolver (PR #121313)

2025-01-01 Thread Nathan Ridge via cfe-commits


@@ -0,0 +1,521 @@
+//===-- HeuristicResolverTests.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 "HeuristicResolver.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/Tooling.h"
+#include "gmock/gmock-matchers.h"
+#include "gtest/gtest.h"
+
+using namespace clang::ast_matchers;
+using clang::clangd::HeuristicResolver;
+using testing::ElementsAre;
+
+namespace clang {
+namespace {
+
+// Helper for matching a sequence of elements with a variadic list of matchers.
+// Usage: `ElementsAre(matchAdapter(Vs, MatchFunction)...)`, where `Vs...` is
+//a variadic list of matchers.
+// For each `V` in `Vs`, this will match the corresponding element `E` if
+// `MatchFunction(V, E)` is true.
+MATCHER_P2(matchAdapter, MatcherForElement, MatchFunction, "matchAdapter") {
+  return MatchFunction(MatcherForElement, arg);
+}
+
+template 
+using ResolveFnT = std::function(
+const HeuristicResolver *, const InputNode *)>;
+
+// Test heuristic resolution on `Code` using the resolution procedure
+// `ResolveFn`, which takes a `HeuristicResolver` and an input AST node of type
+// `InputNode` and returns a `std::vector`.
+// `InputMatcher` should be an AST matcher that matches a single node to pass 
as
+// input to `ResolveFn`, bound to the ID "input". `OutputMatchers` should be 
AST
+// matchers that each match a single node, bound to the ID "output".
+template 
+void expectResolution(llvm::StringRef Code, ResolveFnT ResolveFn,
+  const InputMatcher &IM, const OutputMatchers &...OMS) {
+  auto TU = tooling::buildASTFromCodeWithArgs(Code, {"-std=c++20"});
+  auto &Ctx = TU->getASTContext();
+  auto InputMatches = match(IM, Ctx);
+  ASSERT_EQ(1u, InputMatches.size());
+  const auto *Input = InputMatches[0].template getNodeAs("input");
+  ASSERT_TRUE(Input);
+
+  auto OutputNodeMatches = [&](auto &OutputMatcher, auto &Actual) {
+auto OutputMatches = match(OutputMatcher, Ctx);
+if (OutputMatches.size() != 1u)
+  return false;
+const auto *ExpectedOutput =
+OutputMatches[0].template getNodeAs("output");
+if (!ExpectedOutput)
+  return false;
+return ExpectedOutput == Actual;
+  };
+
+  HeuristicResolver H(Ctx);
+  auto Results = ResolveFn(&H, Input);
+  EXPECT_THAT(Results, ElementsAre(matchAdapter(OMS, OutputNodeMatches)...));
+}
+
+// Wrapper for the above that accepts a HeuristicResolver member function
+// pointer directly.
+template 
+void expectResolution(llvm::StringRef Code,
+  std::vector (
+  HeuristicResolver::*ResolveFn)(const InputNode *)
+  const,
+  const InputMatcher &IM, const OutputMatchers &...OMS) {
+  expectResolution(Code, ResolveFnT(std::mem_fn(ResolveFn)), IM,
+   OMS...);
+}
+
+TEST(HeuristicResolver, MemberExpr) {
+  std::string Code = R"cpp(
+template 
+struct S {
+  void bar() {}
+};
+
+template 
+void foo(S arg) {
+  arg.bar();
+}
+  )cpp";
+  // Test resolution of "bar" in "arg.bar()".
+  expectResolution(Code, &HeuristicResolver::resolveMemberExpr,
+   cxxDependentScopeMemberExpr().bind("input"),

HighCommander4 wrote:

I'm fairly inexperienced with AST matchers and so may be overlooking something, 
but it looks like `hasName()` only works on matchers for `NamedDecl` nodes.

We could conceivably extend `hasName()` to support 
`CXXDependentScopeMemberExpr` as well, but that seems like an enhancement 
beyond the scope of this patch.

In an earlier local draft of this patch, I used matchers that got at the 
dependent node in a more indirect way (e.g. "the callee of a call expression 
that ..."). Partway through writing the tests this way, I discovered that the 
dependent nodes have their own matchers, and I switched to using them as I 
figured it's neat that e.g. in most testcases exercising 
`HeuristicResolver::resolveMemberExpr()`, the input code has a single 
`CXXDependentScopeMemberExpr` node and I can select it simply with 
`cxxDependentScopeMemberExpr()`.

I suppose I could go back to the earlier indirect approach of matching, if 
you'd prefer?

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


[clang-tools-extra] [clangd] Add a unit test suite for HeuristicResolver (PR #121313)

2025-01-01 Thread Nathan Ridge via cfe-commits


@@ -0,0 +1,521 @@
+//===-- HeuristicResolverTests.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 "HeuristicResolver.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Tooling/Tooling.h"
+#include "gmock/gmock-matchers.h"
+#include "gtest/gtest.h"
+
+using namespace clang::ast_matchers;
+using clang::clangd::HeuristicResolver;
+using testing::ElementsAre;
+
+namespace clang {
+namespace {
+
+// Helper for matching a sequence of elements with a variadic list of matchers.
+// Usage: `ElementsAre(matchAdapter(Vs, MatchFunction)...)`, where `Vs...` is
+//a variadic list of matchers.
+// For each `V` in `Vs`, this will match the corresponding element `E` if
+// `MatchFunction(V, E)` is true.
+MATCHER_P2(matchAdapter, MatcherForElement, MatchFunction, "matchAdapter") {
+  return MatchFunction(MatcherForElement, arg);
+}
+
+template 
+using ResolveFnT = std::function(
+const HeuristicResolver *, const InputNode *)>;
+
+// Test heuristic resolution on `Code` using the resolution procedure
+// `ResolveFn`, which takes a `HeuristicResolver` and an input AST node of type
+// `InputNode` and returns a `std::vector`.
+// `InputMatcher` should be an AST matcher that matches a single node to pass 
as
+// input to `ResolveFn`, bound to the ID "input". `OutputMatchers` should be 
AST
+// matchers that each match a single node, bound to the ID "output".
+template 
+void expectResolution(llvm::StringRef Code, ResolveFnT ResolveFn,
+  const InputMatcher &IM, const OutputMatchers &...OMS) {
+  auto TU = tooling::buildASTFromCodeWithArgs(Code, {"-std=c++20"});
+  auto &Ctx = TU->getASTContext();
+  auto InputMatches = match(IM, Ctx);
+  ASSERT_EQ(1u, InputMatches.size());
+  const auto *Input = InputMatches[0].template getNodeAs("input");
+  ASSERT_TRUE(Input);
+
+  auto OutputNodeMatches = [&](auto &OutputMatcher, auto &Actual) {
+auto OutputMatches = match(OutputMatcher, Ctx);
+if (OutputMatches.size() != 1u)
+  return false;
+const auto *ExpectedOutput =
+OutputMatches[0].template getNodeAs("output");
+if (!ExpectedOutput)
+  return false;
+return ExpectedOutput == Actual;
+  };
+
+  HeuristicResolver H(Ctx);
+  auto Results = ResolveFn(&H, Input);
+  EXPECT_THAT(Results, ElementsAre(matchAdapter(OMS, OutputNodeMatches)...));
+}
+
+// Wrapper for the above that accepts a HeuristicResolver member function
+// pointer directly.
+template 
+void expectResolution(llvm::StringRef Code,
+  std::vector (
+  HeuristicResolver::*ResolveFn)(const InputNode *)
+  const,
+  const InputMatcher &IM, const OutputMatchers &...OMS) {
+  expectResolution(Code, ResolveFnT(std::mem_fn(ResolveFn)), IM,
+   OMS...);
+}
+
+TEST(HeuristicResolver, MemberExpr) {
+  std::string Code = R"cpp(
+template 
+struct S {
+  void bar() {}
+};
+
+template 
+void foo(S arg) {
+  arg.bar();
+}
+  )cpp";
+  // Test resolution of "bar" in "arg.bar()".
+  expectResolution(Code, &HeuristicResolver::resolveMemberExpr,
+   cxxDependentScopeMemberExpr().bind("input"),

HighCommander4 wrote:

Never mind, I _was_ overlooking something: there is a `hasMemberName()` matcher 
that works with `CXXDependentScopeMemberExpr`. I'll look at using that.

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


[clang] [clang][Sema] Fix type of an statement expression ending with an atomic type (PR #119711)

2025-01-01 Thread Alejandro Álvarez Ayllón via cfe-commits

https://github.com/alejandro-alvarez-sonarsource updated 
https://github.com/llvm/llvm-project/pull/119711

From d398fa13c2fa141954c79ca68a59c6ac506b393f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?=
 
Date: Wed, 11 Dec 2024 15:43:58 +0100
Subject: [PATCH 1/4] Add regression test

---
 clang/test/Sema/gh106576.c | 16 
 1 file changed, 16 insertions(+)
 create mode 100644 clang/test/Sema/gh106576.c

diff --git a/clang/test/Sema/gh106576.c b/clang/test/Sema/gh106576.c
new file mode 100644
index 00..792977dea14132
--- /dev/null
+++ b/clang/test/Sema/gh106576.c
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+typedef _Atomic char atomic_char;
+
+typedef _Atomic char atomic_char;
+
+atomic_char counter;
+
+char load_plus_one(void) {
+  return ({counter;}) + 1; // no crash
+}
+
+char type_of_stmt_expr(void) {
+  typeof(({counter;})) y = ""; // expected-error-re {{incompatible pointer to 
integer conversion initializing 'typeof (({{{.*}}}))' (aka 'char') with an 
expression of type 'char[1]'}}
+  return y;
+}

From 296aa35fe32449067c69d2b40031af0dd6822a07 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?=
 
Date: Thu, 12 Dec 2024 15:08:56 +0100
Subject: [PATCH 2/4] Tentative fix

---
 clang/lib/Sema/SemaExpr.cpp | 13 +++--
 1 file changed, 11 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 20bf6f7f6f28ff..165447efb345c5 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -15861,10 +15861,19 @@ ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
 return Cast->getSubExpr();
 
+  auto Ty = E->getType().getUnqualifiedType();
+
+  // If the type is an atomic, the statement type is the underlying type.
+  if (const AtomicType *AT = Ty->getAs()) {
+Ty = AT->getValueType().getUnqualifiedType();
+return ImplicitCastExpr::Create(Context, Ty, CK_AtomicToNonAtomic, E,
+/*base path*/ nullptr, VK_PRValue,
+FPOptionsOverride());
+  }
+
   // FIXME: Provide a better location for the initialization.
   return PerformCopyInitialization(
-  InitializedEntity::InitializeStmtExprResult(
-  E->getBeginLoc(), E->getType().getUnqualifiedType()),
+  InitializedEntity::InitializeStmtExprResult(E->getBeginLoc(), Ty),
   SourceLocation(), E);
 }
 

From d13e1090c641314aae8eef50f1b0fb5c0ec67e39 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?=
 
Date: Thu, 12 Dec 2024 15:30:07 +0100
Subject: [PATCH 3/4] Use PerformImplicitConversion

---
 clang/lib/Sema/SemaExpr.cpp | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)

diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 165447efb345c5..45ae97807c2032 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -15866,9 +15866,7 @@ ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
   // If the type is an atomic, the statement type is the underlying type.
   if (const AtomicType *AT = Ty->getAs()) {
 Ty = AT->getValueType().getUnqualifiedType();
-return ImplicitCastExpr::Create(Context, Ty, CK_AtomicToNonAtomic, E,
-/*base path*/ nullptr, VK_PRValue,
-FPOptionsOverride());
+return PerformImplicitConversion(E, Ty, AssignmentAction::Casting);
   }
 
   // FIXME: Provide a better location for the initialization.

From 02d8385cc0f824ff0436a7b0a42d16555e5ee0c5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?=
 
Date: Wed, 18 Dec 2024 09:19:51 +0100
Subject: [PATCH 4/4] Add release note

---
 clang/docs/ReleaseNotes.rst | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 408b2800f9e79c..24420d9dd49d5e 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -853,6 +853,7 @@ Bug Fixes to AST Handling
 - Clang now uses the location of the begin of the member expression for 
``CallExpr``
   involving deduced ``this``. (#GH116928)
 - Fixed printout of AST that uses pack indexing expression. (#GH116486)
+- Fixed type deduction of an statement expression (a GCC extension) ending 
with an atomic type. (#GH106576)
 
 Miscellaneous Bug Fixes
 ^^^

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


[clang] [Clang] emit -Wignored-qualifiers diagnostic for cv-qualified base classes (PR #121419)

2025-01-01 Thread Oleksandr T. via cfe-commits

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

>From 902d4f0817f46cc746a23569628b654c0c247601 Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Wed, 1 Jan 2025 01:47:17 +0200
Subject: [PATCH] [Clang] emit -Wignored-qualifiers diagnostic for cv-qualified
 base classes

---
 clang/docs/ReleaseNotes.rst  |  1 +
 clang/include/clang/Basic/DiagnosticSemaKinds.td |  4 
 clang/lib/Sema/SemaDeclCXX.cpp   |  9 +
 clang/test/SemaCXX/warn-base-type-qualifiers.cpp | 11 +++
 4 files changed, 25 insertions(+)
 create mode 100644 clang/test/SemaCXX/warn-base-type-qualifiers.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b7da12bcf65818..659f0ebd97fc46 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -733,6 +733,7 @@ Improvements to Clang's diagnostics
   scope.Unlock();
   require(scope); // Warning!  Requires mu1.
 }
+- Clang now emits a ``-Wignored-qualifiers`` diagnostic when a base class 
includes cv-qualifiers (#GH55474).
 
 Improvements to Clang's time-trace
 --
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 330ae045616aba..294cfa24975a73 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -487,6 +487,10 @@ def err_noreturn_non_function : Error<
 def warn_qual_return_type : Warning<
   "'%0' type qualifier%s1 on return type %plural{1:has|:have}1 no effect">,
   InGroup, DefaultIgnore;
+def warn_qual_base_type : Warning<
+  "'%0' qualifier%s1 on base class type %2 have no effect">,
+  InGroup, DefaultIgnore;
+
 def warn_deprecated_redundant_constexpr_static_def : Warning<
   "out-of-line definition of constexpr static data member is redundant "
   "in C++17 and is deprecated">,
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index c5a72cf812ebc9..df0a15fc44e3e3 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -2655,6 +2655,15 @@ CXXBaseSpecifier *Sema::CheckBaseSpecifier(CXXRecordDecl 
*Class,
   return nullptr;
 }
 
+if (BaseType.hasQualifiers()) {
+  auto Quals =
+  BaseType.getQualifiers().getAsString(Context.getPrintingPolicy());
+  Diag(BaseLoc, diag::warn_qual_base_type)
+  << Quals << std::count(Quals.begin(), Quals.end(), ' ') + 1
+  << BaseType;
+  Diag(BaseLoc, diag::note_base_class_specified_here) << BaseType;
+}
+
 // For the MS ABI, propagate DLL attributes to base class templates.
 if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
 Context.getTargetInfo().getTriple().isPS()) {
diff --git a/clang/test/SemaCXX/warn-base-type-qualifiers.cpp 
b/clang/test/SemaCXX/warn-base-type-qualifiers.cpp
new file mode 100644
index 00..5074140700cc36
--- /dev/null
+++ b/clang/test/SemaCXX/warn-base-type-qualifiers.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 %s -std=c++11 -Wignored-qualifiers -verify
+
+class A { };
+
+typedef const A A_Const;
+class B : public A_Const { }; // expected-warning {{'const' qualifier on base 
class type 'A_Const' (aka 'const A') have no effect}} \
+  // expected-note {{base class 'A_Const' (aka 
'const A') specified here}}
+
+typedef const volatile A A_Const_Volatile;
+class C : public A_Const_Volatile { }; // expected-warning {{'const volatile' 
qualifiers on base class type 'A_Const_Volatile' (aka 'const volatile A') have 
no effect}} \
+   // expected-note {{base class 
'A_Const_Volatile' (aka 'const volatile A') specified here}}

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


[clang] Reapply "[Driver][OHOS] Fix lld link issue for OHOS (#118192)" (PR #120159)

2025-01-01 Thread Fangrui Song via cfe-commits

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


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


[clang] [Clang][Driver] Declare win32 threads on Windows (PR #121442)

2025-01-01 Thread Mateusz Mikuła via cfe-commits


@@ -619,7 +619,13 @@ class ToolChain {
   virtual bool SupportsEmbeddedBitcode() const { return false; }
 
   /// getThreadModel() - Which thread model does this target use?
-  virtual std::string getThreadModel() const { return "posix"; }
+  virtual std::string getThreadModel() const {
+#ifdef _WIN32
+return "win32";

mati865 wrote:

Oh, you are right. This change as is is pretty dumb right now.

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


[clang] [Clang][Driver] Declare win32 threads on Windows (PR #121442)

2025-01-01 Thread Mateusz Mikuła via cfe-commits

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


[clang] cd23949 - [clang-format] Support globstar in .clang-format-ignore (#121404)

2025-01-01 Thread via cfe-commits

Author: Owen Pan
Date: 2025-01-01T15:37:59-08:00
New Revision: cd239493c1023cbccfe6b1e9be32e68592a7f304

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

LOG: [clang-format] Support globstar in .clang-format-ignore (#121404)

Closes #110160.
Closes #114969.

Added: 


Modified: 
clang/docs/ClangFormat.rst
clang/docs/ReleaseNotes.rst
clang/lib/Format/MatchFilePath.cpp
clang/unittests/Format/MatchFilePathTest.cpp

Removed: 




diff  --git a/clang/docs/ClangFormat.rst b/clang/docs/ClangFormat.rst
index c8f1d7f5a77581..e1f677178c00ab 100644
--- a/clang/docs/ClangFormat.rst
+++ b/clang/docs/ClangFormat.rst
@@ -150,6 +150,7 @@ names. It has the following format:
 * Patterns follow the rules specified in `POSIX 2.13.1, 2.13.2, and Rule 1 of
   2.13.3 `_.
+* Bash globstar (``**``) is supported.
 * A pattern is negated if it starts with a bang (``!``).
 
 To match all files in a directory, use e.g. ``foo/bar/*``. To match all files 
in

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2a688a677294f8..662c575bad3e8b 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -1125,6 +1125,7 @@ clang-format
 - Adds ``RemoveEmptyLinesInUnwrappedLines`` option.
 - Adds ``KeepFormFeed`` option and set it to ``true`` for ``GNU`` style.
 - Adds ``AllowShortNamespacesOnASingleLine`` option.
+- Adds support for bash globstar in ``.clang-format-ignore``.
 
 libclang
 

diff  --git a/clang/lib/Format/MatchFilePath.cpp 
b/clang/lib/Format/MatchFilePath.cpp
index 062b334dcdd8fd..3d8614838e5356 100644
--- a/clang/lib/Format/MatchFilePath.cpp
+++ b/clang/lib/Format/MatchFilePath.cpp
@@ -25,9 +25,11 @@ bool matchFilePath(StringRef Pattern, StringRef FilePath) {
   assert(!Pattern.empty());
   assert(!FilePath.empty());
 
+  const auto FilePathBack = FilePath.back();
+
   // No match if `Pattern` ends with a non-meta character not equal to the last
   // character of `FilePath`.
-  if (const auto C = Pattern.back(); !strchr("?*]", C) && C != FilePath.back())
+  if (const auto C = Pattern.back(); !strchr("?*]", C) && C != FilePathBack)
 return false;
 
   constexpr auto Separator = '/';
@@ -49,25 +51,37 @@ bool matchFilePath(StringRef Pattern, StringRef FilePath) {
 return false;
   break;
 case '*': {
-  while (++I < EOP && Pattern[I] == '*') { // Skip consecutive stars.
+  bool Globstar = I == 0 || Pattern[I - 1] == Separator;
+  int StarCount = 1;
+  for (; ++I < EOP && Pattern[I] == '*'; ++StarCount) {
+// Skip consecutive stars.
   }
+  if (StarCount != 2)
+Globstar = false;
   const auto K = FilePath.find(Separator, J); // Index of next `Separator`.
   const bool NoMoreSeparatorsInFilePath = K == StringRef::npos;
   if (I == EOP) // `Pattern` ends with a star.
-return NoMoreSeparatorsInFilePath;
-  // `Pattern` ends with a lone backslash.
-  if (Pattern[I] == '\\' && ++I == EOP)
-return false;
+return Globstar || NoMoreSeparatorsInFilePath;
+  if (Pattern[I] != Separator) {
+Globstar = false;
+// `Pattern` ends with a lone backslash.
+if (Pattern[I] == '\\' && ++I == EOP)
+  return false;
+  }
   // The star is followed by a (possibly escaped) `Separator`.
   if (Pattern[I] == Separator) {
-if (NoMoreSeparatorsInFilePath)
-  return false;
-J = K; // Skip to next `Separator` in `FilePath`.
-break;
+if (!Globstar) {
+  if (NoMoreSeparatorsInFilePath)
+return false;
+  J = K; // Skip to next `Separator` in `FilePath`.
+  break;
+}
+if (++I == EOP)
+  return FilePathBack == Separator;
   }
   // Recurse.
-  for (auto Pat = Pattern.substr(I); J < End && FilePath[J] != Separator;
-   ++J) {
+  for (auto Pat = Pattern.substr(I);
+   J < End && (Globstar || FilePath[J] != Separator); ++J) {
 if (matchFilePath(Pat, FilePath.substr(J)))
   return true;
   }

diff  --git a/clang/unittests/Format/MatchFilePathTest.cpp 
b/clang/unittests/Format/MatchFilePathTest.cpp
index 28f665635718e5..346ea7c31e6157 100644
--- a/clang/unittests/Format/MatchFilePathTest.cpp
+++ b/clang/unittests/Format/MatchFilePathTest.cpp
@@ -164,6 +164,41 @@ TEST_F(MatchFilePathTest, Path) {
   EXPECT_FALSE(match("foo\\", R"(foo*\)"));
 }
 
+TEST_F(MatchFilePathTest, Globstar) {
+  EXPECT_TRUE(match("/", "**"));
+  EXPECT_TRUE(match("foo", "**"));
+  EXPECT_TRUE(match("/foo", "**"));
+  EXPECT_TRUE(match("foo/", "**"));
+  EXPECT_TRUE(match("foo/bar", "**"));
+
+  EXPECT_TRUE(match("/", 

[clang] [clang-format] Support globstar in .clang-format-ignore (PR #121404)

2025-01-01 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Add `VariableTemplates` option (PR #121318)

2025-01-01 Thread Owen Pan via cfe-commits

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/121318

>From 7e865d66f147da3afa1ebcd55354e97fdfd8374a Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sun, 29 Dec 2024 20:17:46 -0800
Subject: [PATCH] [clang-format] Add VariableTemplate option

Closes #120148.
---
 clang/docs/ClangFormatStyleOptions.rst|  9 +
 clang/docs/ReleaseNotes.rst   |  1 +
 clang/include/clang/Format/Format.h   | 11 ++-
 clang/lib/Format/Format.cpp   |  1 +
 clang/lib/Format/FormatToken.h|  1 +
 clang/lib/Format/FormatTokenLexer.cpp |  4 
 clang/lib/Format/FormatTokenLexer.h   |  3 ++-
 clang/lib/Format/TokenAnnotator.cpp   | 19 +++
 clang/unittests/Format/TokenAnnotatorTest.cpp | 13 +
 9 files changed, 56 insertions(+), 6 deletions(-)

diff --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 4be448171699ca..fa098c17a9bb31 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -6793,6 +6793,15 @@ the configuration (without a prefix: ``Auto``).
 
 
 
+.. _VariableTemplates:
+
+**VariableTemplates** (``List of Strings``) :versionbadge:`clang-format 20` 
:ref:`¶ `
+  A vector of non-keyword identifiers that should be interpreted as variable
+  template names.
+
+  A ``)`` after a variable template instantiation is **not** annotated as
+  the closing parenthesis of C-style cast operator.
+
 .. _VerilogBreakBetweenInstancePorts:
 
 **VerilogBreakBetweenInstancePorts** (``Boolean``) :versionbadge:`clang-format 
17` :ref:`¶ `
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index d9b0cb815a15db..f05a95e31dc255 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -1118,6 +1118,7 @@ clang-format
   ``Never``, and ``true`` to ``Always``.
 - Adds ``RemoveEmptyLinesInUnwrappedLines`` option.
 - Adds ``KeepFormFeed`` option and set it to ``true`` for ``GNU`` style.
+- Adds ``VariableTemplates`` option.
 
 libclang
 
diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 6383934afa2c40..8c3d184cc71419 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -5099,6 +5099,15 @@ struct FormatStyle {
   /// \version 3.7
   UseTabStyle UseTab;
 
+  /// A vector of non-keyword identifiers that should be interpreted as 
variable
+  /// template names.
+  ///
+  /// A ``)`` after a variable template instantiation is **not** annotated as
+  /// the closing parenthesis of C-style cast operator.
+  ///
+  /// \version 20
+  std::vector VariableTemplates;
+
   /// For Verilog, put each port on its own line in module instantiations.
   /// \code
   ///true:
@@ -5308,7 +5317,7 @@ struct FormatStyle {
TableGenBreakInsideDAGArg == R.TableGenBreakInsideDAGArg &&
TabWidth == R.TabWidth && TemplateNames == R.TemplateNames &&
TypeNames == R.TypeNames && TypenameMacros == R.TypenameMacros &&
-   UseTab == R.UseTab &&
+   UseTab == R.UseTab && VariableTemplates == R.VariableTemplates &&
VerilogBreakBetweenInstancePorts ==
R.VerilogBreakBetweenInstancePorts &&
WhitespaceSensitiveMacros == R.WhitespaceSensitiveMacros;
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 95129a8fe9240c..fe5465ce7b09de 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1164,6 +1164,7 @@ template <> struct MappingTraits {
 IO.mapOptional("TypeNames", Style.TypeNames);
 IO.mapOptional("TypenameMacros", Style.TypenameMacros);
 IO.mapOptional("UseTab", Style.UseTab);
+IO.mapOptional("VariableTemplates", Style.VariableTemplates);
 IO.mapOptional("VerilogBreakBetweenInstancePorts",
Style.VerilogBreakBetweenInstancePorts);
 IO.mapOptional("WhitespaceSensitiveMacros",
diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index f6bb860a1fea31..8917049cefb865 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -186,6 +186,7 @@ namespace format {
   TYPE(UnionLBrace)
\
   TYPE(UnionRBrace)
\
   TYPE(UntouchableMacroFunc)   
\
+  TYPE(VariableTemplate)   
\
   /* Like in 'assign x = 0, y = 1;' . */   
\
   TYPE(VerilogAssignComma) 
\
   /* like in begin : block */  
\
diff --git a/clang/lib/Format/FormatTokenLexer.cpp 
b/clang/lib/Format/FormatTokenLexer.cpp
index 7a264bddcdfe19..0f8d4940d4369a 100644
--- a/clang/lib/Format/FormatTo

[clang] [clang-format] Support globstar in .clang-format-ignore (PR #121404)

2025-01-01 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder 
`openmp-clang-x86_64-linux-debian` running on `gribozavr4` while building 
`clang` at step 6 "test-openmp".

Full details are available at: 
https://lab.llvm.org/buildbot/#/builders/6/builds/5457


Here is the relevant piece of the build log for the reference

```
Step 6 (test-openmp) failure: test (failure)
 TEST 'libomp :: ompt/parallel/nested.c' FAILED 

Exit Code: 1

Command Output (stdout):
--
# RUN: at line 1
/b/1/openmp-clang-x86_64-linux-debian/llvm.build/./bin/clang -fopenmp   -I 
/b/1/openmp-clang-x86_64-linux-debian/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 -I /b/1/openmp-clang-x86_64-linux-debian/llvm.src/openmp/runtime/test -L 
/b/1/openmp-clang-x86_64-linux-debian/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
  -fno-omit-frame-pointer -I 
/b/1/openmp-clang-x86_64-linux-debian/llvm.src/openmp/runtime/test/ompt 
/b/1/openmp-clang-x86_64-linux-debian/llvm.src/openmp/runtime/test/ompt/parallel/nested.c
 -o 
/b/1/openmp-clang-x86_64-linux-debian/llvm.build/runtimes/runtimes-bins/openmp/runtime/test/ompt/parallel/Output/nested.c.tmp
 -lm -latomic && 
/b/1/openmp-clang-x86_64-linux-debian/llvm.build/runtimes/runtimes-bins/openmp/runtime/test/ompt/parallel/Output/nested.c.tmp
 | tee 
/b/1/openmp-clang-x86_64-linux-debian/llvm.build/runtimes/runtimes-bins/openmp/runtime/test/ompt/parallel/Output/nested.c.tmp.out
 | /b/1/openmp-clang-x86_64-linux-debian/llvm.build/./bin/FileCheck 
/b/1/openmp-clang-x86_64-linux-debian/llvm.src/openmp/runtime/test/ompt/parallel/nested.c
# executed command: 
/b/1/openmp-clang-x86_64-linux-debian/llvm.build/./bin/clang -fopenmp -I 
/b/1/openmp-clang-x86_64-linux-debian/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 -I /b/1/openmp-clang-x86_64-linux-debian/llvm.src/openmp/runtime/test -L 
/b/1/openmp-clang-x86_64-linux-debian/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 -fno-omit-frame-pointer -I 
/b/1/openmp-clang-x86_64-linux-debian/llvm.src/openmp/runtime/test/ompt 
/b/1/openmp-clang-x86_64-linux-debian/llvm.src/openmp/runtime/test/ompt/parallel/nested.c
 -o 
/b/1/openmp-clang-x86_64-linux-debian/llvm.build/runtimes/runtimes-bins/openmp/runtime/test/ompt/parallel/Output/nested.c.tmp
 -lm -latomic
# .---command stderr
# | In file included from 
/b/1/openmp-clang-x86_64-linux-debian/llvm.src/openmp/runtime/test/ompt/parallel/nested.c:6:
# | 
/b/1/openmp-clang-x86_64-linux-debian/llvm.src/openmp/runtime/test/ompt/callback.h:185:6:
 warning: "Clang 5.0 and later add an additional wrapper for outlined functions 
when compiling with debug information." [-W#warnings]
# |   185 | #warning "Clang 5.0 and later add an additional wrapper for 
outlined functions when compiling with debug information."
# |   |  ^
# | 
/b/1/openmp-clang-x86_64-linux-debian/llvm.src/openmp/runtime/test/ompt/callback.h:186:6:
 warning: "Please define -DDEBUG iff you manually pass in -g to make the tests 
succeed!" [-W#warnings]
# |   186 | #warning "Please define -DDEBUG iff you manually pass in -g to 
make the tests succeed!"
# |   |  ^
# | 2 warnings generated.
# `-
# executed command: 
/b/1/openmp-clang-x86_64-linux-debian/llvm.build/runtimes/runtimes-bins/openmp/runtime/test/ompt/parallel/Output/nested.c.tmp
# .---command stderr
# | OMP: Info #276: omp_set_nested routine deprecated, please use 
omp_set_max_active_levels instead.
# `-
# executed command: tee 
/b/1/openmp-clang-x86_64-linux-debian/llvm.build/runtimes/runtimes-bins/openmp/runtime/test/ompt/parallel/Output/nested.c.tmp.out
# executed command: 
/b/1/openmp-clang-x86_64-linux-debian/llvm.build/./bin/FileCheck 
/b/1/openmp-clang-x86_64-linux-debian/llvm.src/openmp/runtime/test/ompt/parallel/nested.c
# RUN: at line 2
/b/1/openmp-clang-x86_64-linux-debian/llvm.build/./bin/clang -fopenmp   -I 
/b/1/openmp-clang-x86_64-linux-debian/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 -I /b/1/openmp-clang-x86_64-linux-debian/llvm.src/openmp/runtime/test -L 
/b/1/openmp-clang-x86_64-linux-debian/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
  -fno-omit-frame-pointer -I 
/b/1/openmp-clang-x86_64-linux-debian/llvm.src/openmp/runtime/test/ompt 
/b/1/openmp-clang-x86_64-linux-debian/llvm.src/openmp/runtime/test/ompt/parallel/nested.c
 -o 
/b/1/openmp-clang-x86_64-linux-debian/llvm.build/runtimes/runtimes-bins/openmp/runtime/test/ompt/parallel/Output/nested.c.tmp
 -lm -latomic && 
/b/1/openmp-clang-x86_64-linux-debian/llvm.build/runtimes/runtimes-bins/openmp/runtime/test/ompt/parallel/Output/nested.c.tmp
 | sort -n -s | tee 
/b/1/openmp-clang-x86_64-linux-debian/llvm.build/runtimes/runtimes-bins/openmp/runtime/test/ompt/parallel/Output/nested.c.tmp.out
 | /b/1/openmp-clang-x86_64-linux-debian/llvm.build/./bin/FileCheck 
--check-prefix=THREADS 
/b/1/openmp-clang-x86_64-linux-debian/llvm.src/openmp/

[clang] [clang-format] extend clang-format directive with options to prevent formatting for one line (PR #118566)

2025-01-01 Thread Oleksandr T. via cfe-commits

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

>From 75da343b0bd6e3b0f3219b349f6be4c882947820 Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Wed, 4 Dec 2024 02:24:12 +0200
Subject: [PATCH 1/6] [clang-format] extend clang-format directive with options
 to prevent formatting for one line

---
 clang/include/clang/Format/Format.h   | 11 +++-
 clang/lib/Format/DefinitionBlockSeparator.cpp |  3 +-
 clang/lib/Format/Format.cpp   | 59 +--
 clang/lib/Format/FormatTokenLexer.cpp | 39 +---
 clang/lib/Format/FormatTokenLexer.h   |  8 ++-
 .../Format/IntegerLiteralSeparatorFixer.cpp   |  4 +-
 clang/lib/Format/SortJavaScriptImports.cpp| 10 +++-
 clang/lib/Format/TokenAnnotator.cpp   |  4 +-
 clang/unittests/Format/FormatTest.cpp | 53 +
 .../unittests/Format/SortImportsTestJava.cpp  |  9 +++
 10 files changed, 165 insertions(+), 35 deletions(-)

diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 6383934afa2c40..b25d190178247d 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -5620,8 +5620,15 @@ inline StringRef 
getLanguageName(FormatStyle::LanguageKind Language) {
   }
 }
 
-bool isClangFormatOn(StringRef Comment);
-bool isClangFormatOff(StringRef Comment);
+enum class ClangFormatDirective {
+  None,
+  Off,
+  On,
+  OffLine,
+  OffNextLine,
+};
+
+ClangFormatDirective parseClangFormatDirective(StringRef Comment);
 
 } // end namespace format
 } // end namespace clang
diff --git a/clang/lib/Format/DefinitionBlockSeparator.cpp 
b/clang/lib/Format/DefinitionBlockSeparator.cpp
index 319236d3bd618c..709ad5e776cc5a 100644
--- a/clang/lib/Format/DefinitionBlockSeparator.cpp
+++ b/clang/lib/Format/DefinitionBlockSeparator.cpp
@@ -144,7 +144,8 @@ void DefinitionBlockSeparator::separateBlocks(
 return false;
 
   if (const auto *Tok = OperateLine->First;
-  Tok->is(tok::comment) && !isClangFormatOn(Tok->TokenText)) {
+  Tok->is(tok::comment) && parseClangFormatDirective(Tok->TokenText) ==
+   ClangFormatDirective::None) {
 return true;
   }
 
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index dcaac4b0d42cc5..11802e8f5b3738 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3266,10 +3266,11 @@ tooling::Replacements sortCppIncludes(const FormatStyle 
&Style, StringRef Code,
   FormattingOff = false;
 
 bool IsBlockComment = false;
+ClangFormatDirective CFD = parseClangFormatDirective(Trimmed);
 
-if (isClangFormatOff(Trimmed)) {
+if (CFD == ClangFormatDirective::Off) {
   FormattingOff = true;
-} else if (isClangFormatOn(Trimmed)) {
+} else if (CFD == ClangFormatDirective::On) {
   FormattingOff = false;
 } else if (Trimmed.starts_with("/*")) {
   IsBlockComment = true;
@@ -3452,9 +3453,10 @@ tooling::Replacements sortJavaImports(const FormatStyle 
&Style, StringRef Code,
 Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
 
 StringRef Trimmed = Line.trim();
-if (isClangFormatOff(Trimmed))
+ClangFormatDirective CFD = parseClangFormatDirective(Trimmed);
+if (CFD == ClangFormatDirective::Off)
   FormattingOff = true;
-else if (isClangFormatOn(Trimmed))
+else if (CFD == ClangFormatDirective::On)
   FormattingOff = false;
 
 if (ImportRegex.match(Line, &Matches)) {
@@ -4190,24 +4192,45 @@ Expected getStyle(StringRef StyleName, 
StringRef FileName,
   return FallbackStyle;
 }
 
-static bool isClangFormatOnOff(StringRef Comment, bool On) {
-  if (Comment == (On ? "/* clang-format on */" : "/* clang-format off */"))
-return true;
+static unsigned skipWhitespace(unsigned Pos, StringRef Str, unsigned Length) {
+  while (Pos < Length && isspace(Str[Pos]))
+++Pos;
+  return Pos;
+}
 
-  static const char ClangFormatOn[] = "// clang-format on";
-  static const char ClangFormatOff[] = "// clang-format off";
-  const unsigned Size = (On ? sizeof ClangFormatOn : sizeof ClangFormatOff) - 
1;
+ClangFormatDirective parseClangFormatDirective(StringRef Comment) {
+  size_t Pos = std::min(Comment.find("/*"), Comment.find("//"));
+  unsigned Length = Comment.size();
+  if (Pos == StringRef::npos)
+return ClangFormatDirective::None;
 
-  return Comment.starts_with(On ? ClangFormatOn : ClangFormatOff) &&
- (Comment.size() == Size || Comment[Size] == ':');
-}
+  Pos = skipWhitespace(Pos + 2, Comment, Length);
+  StringRef ClangFormatDirectiveName = "clang-format";
 
-bool isClangFormatOn(StringRef Comment) {
-  return isClangFormatOnOff(Comment, /*On=*/true);
-}
+  if (Comment.substr(Pos, ClangFormatDirectiveName.size()) ==
+  ClangFormatDirectiveName) {
+Pos =
+skipWhitespace(Pos + ClangFormatDirectiveName.size(), Comment, Length);
+
+unsigned EndDi

[clang] [Clang][P1061] Add stuctured binding packs (PR #121417)

2025-01-01 Thread via cfe-commits

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


[clang] [Clang][ASTMatcher] Add `dependentTemplateSpecializationType` AST mat… (PR #121435)

2025-01-01 Thread kefan cao via cfe-commits

caokefan wrote:

@HighCommander4

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


[clang] [Clang] emit -Wignored-qualifiers diagnostic for cv-qualified base classes (PR #121419)

2025-01-01 Thread Oleksandr T. via cfe-commits

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

>From 3f6b1d68978857035a972f49b1cfd9d9d0151be9 Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Wed, 1 Jan 2025 01:47:17 +0200
Subject: [PATCH] [Clang] emit -Wignored-qualifiers diagnostic for cv-qualified
 base classes

---
 clang/docs/ReleaseNotes.rst   |  1 +
 .../clang/Basic/DiagnosticSemaKinds.td|  4 
 clang/lib/Sema/SemaDeclCXX.cpp|  9 +
 .../SemaCXX/warn-base-type-qualifiers.cpp | 20 +++
 4 files changed, 34 insertions(+)
 create mode 100644 clang/test/SemaCXX/warn-base-type-qualifiers.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b7da12bcf65818..659f0ebd97fc46 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -733,6 +733,7 @@ Improvements to Clang's diagnostics
   scope.Unlock();
   require(scope); // Warning!  Requires mu1.
 }
+- Clang now emits a ``-Wignored-qualifiers`` diagnostic when a base class 
includes cv-qualifiers (#GH55474).
 
 Improvements to Clang's time-trace
 --
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 330ae045616aba..294cfa24975a73 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -487,6 +487,10 @@ def err_noreturn_non_function : Error<
 def warn_qual_return_type : Warning<
   "'%0' type qualifier%s1 on return type %plural{1:has|:have}1 no effect">,
   InGroup, DefaultIgnore;
+def warn_qual_base_type : Warning<
+  "'%0' qualifier%s1 on base class type %2 have no effect">,
+  InGroup, DefaultIgnore;
+
 def warn_deprecated_redundant_constexpr_static_def : Warning<
   "out-of-line definition of constexpr static data member is redundant "
   "in C++17 and is deprecated">,
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index c5a72cf812ebc9..b82ca1541ba249 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -2655,6 +2655,15 @@ CXXBaseSpecifier *Sema::CheckBaseSpecifier(CXXRecordDecl 
*Class,
   return nullptr;
 }
 
+if (BaseType.hasQualifiers() && !isa(BaseType)) 
{
+  auto Quals =
+  BaseType.getQualifiers().getAsString(Context.getPrintingPolicy());
+  Diag(BaseLoc, diag::warn_qual_base_type)
+  << Quals << std::count(Quals.begin(), Quals.end(), ' ') + 1
+  << BaseType;
+  Diag(BaseLoc, diag::note_base_class_specified_here) << BaseType;
+}
+
 // For the MS ABI, propagate DLL attributes to base class templates.
 if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
 Context.getTargetInfo().getTriple().isPS()) {
diff --git a/clang/test/SemaCXX/warn-base-type-qualifiers.cpp 
b/clang/test/SemaCXX/warn-base-type-qualifiers.cpp
new file mode 100644
index 00..a5af7ec7415bf5
--- /dev/null
+++ b/clang/test/SemaCXX/warn-base-type-qualifiers.cpp
@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 %s -std=c++11 -Wignored-qualifiers -verify
+
+class A { };
+
+typedef const A A_Const;
+class B : public A_Const { }; // expected-warning {{'const' qualifier on base 
class type 'A_Const' (aka 'const A') have no effect}} \
+  // expected-note {{base class 'A_Const' (aka 
'const A') specified here}}
+
+typedef const volatile A A_Const_Volatile;
+class C : public A_Const_Volatile { }; // expected-warning {{'const volatile' 
qualifiers on base class type 'A_Const_Volatile' (aka 'const volatile A') have 
no effect}} \
+   // expected-note {{base class 
'A_Const_Volatile' (aka 'const volatile A') specified here}}
+
+struct D {
+  D(int);
+};
+template  struct E : T {
+  using T::T;
+  E(int &) : E(0) {}
+};
+E e(1);

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


[clang] [clang-format] Support globstar in .clang-format-ignore (PR #121404)

2025-01-01 Thread via cfe-commits

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


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


[clang] [clang-format] Add `VariableTemplates` option (PR #121318)

2025-01-01 Thread via cfe-commits

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

Should there be a parse test?

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


[clang] [Clang] emit -Wignored-qualifiers diagnostic for cv-qualified base classes (PR #121419)

2025-01-01 Thread Oleksandr T. via cfe-commits


@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 %s -std=c++11 -Wignored-qualifiers -verify
+
+class A { };
+
+typedef const A A_Const;
+class B : public A_Const { }; // expected-warning {{'const' qualifier on base 
class type 'A_Const' (aka 'const A') have no effect}} \
+  // expected-note {{base class 'A_Const' (aka 
'const A') specified here}}
+
+typedef const volatile A A_Const_Volatile;
+class C : public A_Const_Volatile { }; // expected-warning {{'const volatile' 
qualifiers on base class type 'A_Const_Volatile' (aka 'const volatile A') have 
no effect}} \
+   // expected-note {{base class 
'A_Const_Volatile' (aka 'const volatile A') specified here}}
+
+struct D {
+  D(int);
+};
+template  struct E : T {

a-tarasyuk wrote:

@AaronBallman @erichkeane should a warning be triggered in this case?

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


[clang-tools-extra] [clang-tidy] Create bugprone-incorrect-enable-shared-from-this check (PR #102299)

2025-01-01 Thread Piotr Zegar via cfe-commits

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


[clang-tools-extra] [clang-tidy] Create bugprone-incorrect-enable-shared-from-this check (PR #102299)

2025-01-01 Thread Piotr Zegar via cfe-commits


@@ -0,0 +1,34 @@
+.. title:: clang-tidy - bugprone-incorrect-enable-shared-from-this
+
+bugprone-incorrect-enable-shared-from-this
+==
+
+Detect classes or structs that do not publicly inherit from 
+``std::enable_shared_from_this``, because unintended behavior will 
+otherwise occur when calling ``shared_from_this``.
+
+Consider the following code:

PiotrZSL wrote:

Note: this line isn't needed

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


[clang-tools-extra] [clang-tidy] Create bugprone-incorrect-enable-shared-from-this check (PR #102299)

2025-01-01 Thread Piotr Zegar via cfe-commits


@@ -0,0 +1,64 @@
+//===--- IncorrectEnableSharedFromThisCheck.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 "IncorrectEnableSharedFromThisCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/DeclCXX.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+void IncorrectEnableSharedFromThisCheck::registerMatchers(MatchFinder *Finder) 
{
+  const auto EnableSharedFromThis =
+  cxxRecordDecl(hasName("enable_shared_from_this"), isInStdNamespace());
+  const auto QType = hasCanonicalType(hasDeclaration(
+  cxxRecordDecl(
+  anyOf(EnableSharedFromThis.bind("enable_rec"),
+cxxRecordDecl(hasAnyBase(cxxBaseSpecifier(
+isPublic(), hasType(hasCanonicalType(
+hasDeclaration(EnableSharedFromThis
+  .bind("base_rec")));
+  Finder->addMatcher(
+  cxxRecordDecl(

PiotrZSL wrote:

Note: You may consider excluding system headers, may speed up analisys.

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


  1   2   >