[clang] [Clang][RISCV] Add missing support for `__builtin_riscv_cpop_32/64` (PR #76256)

2023-12-24 Thread Yingwei Zheng via cfe-commits

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


[clang] [Clang][RISCV] Use `__builtin_popcount` in `__riscv_cpop_32/64` (PR #76286)

2023-12-24 Thread Yingwei Zheng via cfe-commits

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


[clang] d26791b - [Clang][RISCV] Use `__builtin_popcount` in `__riscv_cpop_32/64` (#76286)

2023-12-24 Thread via cfe-commits

Author: Yingwei Zheng
Date: 2023-12-24T16:04:49+08:00
New Revision: d26791b09bae4f8bf0f9531957a14864f8696f15

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

LOG: [Clang][RISCV] Use `__builtin_popcount` in `__riscv_cpop_32/64` (#76286)

This patch replaces `__builtin_riscv_cpop_32/64` with `__builtin_popcount(ll)` 
because `__builtin_riscv_cpop_32/64` is not implemented in clang.

Added: 


Modified: 
clang/lib/Headers/riscv_bitmanip.h
clang/test/CodeGen/RISCV/rvb-intrinsics/zbb.c

Removed: 




diff  --git a/clang/lib/Headers/riscv_bitmanip.h 
b/clang/lib/Headers/riscv_bitmanip.h
index 1a81cc8618c975..044cbaa037e43a 100644
--- a/clang/lib/Headers/riscv_bitmanip.h
+++ b/clang/lib/Headers/riscv_bitmanip.h
@@ -34,7 +34,7 @@ __riscv_ctz_32(uint32_t __x) {
 
 static __inline__ unsigned __attribute__((__always_inline__, __nodebug__))
 __riscv_cpop_32(uint32_t __x) {
-  return __builtin_riscv_cpop_32(__x);
+  return __builtin_popcount(__x);
 }
 
 #if __riscv_xlen == 64
@@ -55,7 +55,7 @@ __riscv_ctz_64(uint64_t __x) {
 
 static __inline__ unsigned __attribute__((__always_inline__, __nodebug__))
 __riscv_cpop_64(uint64_t __x) {
-  return __builtin_riscv_cpop_64(__x);
+  return __builtin_popcountll(__x);
 }
 #endif
 #endif // defined(__riscv_zbb)

diff  --git a/clang/test/CodeGen/RISCV/rvb-intrinsics/zbb.c 
b/clang/test/CodeGen/RISCV/rvb-intrinsics/zbb.c
index 5edbc578e82e9a..fbc51b4bf144ae 100644
--- a/clang/test/CodeGen/RISCV/rvb-intrinsics/zbb.c
+++ b/clang/test/CodeGen/RISCV/rvb-intrinsics/zbb.c
@@ -51,8 +51,8 @@ unsigned int clz_32(uint32_t a) {
 // RV64ZBB-LABEL: @clz_64(
 // RV64ZBB-NEXT:  entry:
 // RV64ZBB-NEXT:[[TMP0:%.*]] = call i64 @llvm.ctlz.i64(i64 [[A:%.*]], i1 
false)
-// RV64ZBB-NEXT:[[CAST:%.*]] = trunc i64 [[TMP0]] to i32
-// RV64ZBB-NEXT:ret i32 [[CAST]]
+// RV64ZBB-NEXT:[[CAST_I:%.*]] = trunc i64 [[TMP0]] to i32
+// RV64ZBB-NEXT:ret i32 [[CAST_I]]
 //
 unsigned int clz_64(uint64_t a) {
   return __riscv_clz_64(a);
@@ -77,10 +77,36 @@ unsigned int ctz_32(uint32_t a) {
 // RV64ZBB-LABEL: @ctz_64(
 // RV64ZBB-NEXT:  entry:
 // RV64ZBB-NEXT:[[TMP0:%.*]] = call i64 @llvm.cttz.i64(i64 [[A:%.*]], i1 
false)
-// RV64ZBB-NEXT:[[CAST:%.*]] = trunc i64 [[TMP0]] to i32
-// RV64ZBB-NEXT:ret i32 [[CAST]]
+// RV64ZBB-NEXT:[[CAST_I:%.*]] = trunc i64 [[TMP0]] to i32
+// RV64ZBB-NEXT:ret i32 [[CAST_I]]
 //
 unsigned int ctz_64(uint64_t a) {
   return __riscv_ctz_64(a);
 }
 #endif
+
+// RV32ZBB-LABEL: @cpop_32(
+// RV32ZBB-NEXT:  entry:
+// RV32ZBB-NEXT:[[TMP0:%.*]] = call i32 @llvm.ctpop.i32(i32 [[A:%.*]])
+// RV32ZBB-NEXT:ret i32 [[TMP0]]
+//
+// RV64ZBB-LABEL: @cpop_32(
+// RV64ZBB-NEXT:  entry:
+// RV64ZBB-NEXT:[[TMP0:%.*]] = call i32 @llvm.ctpop.i32(i32 [[A:%.*]])
+// RV64ZBB-NEXT:ret i32 [[TMP0]]
+//
+unsigned int cpop_32(uint32_t a) {
+  return __riscv_cpop_32(a);
+}
+
+#if __riscv_xlen == 64
+// RV64ZBB-LABEL: @cpop_64(
+// RV64ZBB-NEXT:  entry:
+// RV64ZBB-NEXT:[[TMP0:%.*]] = call i64 @llvm.ctpop.i64(i64 [[A:%.*]])
+// RV64ZBB-NEXT:[[CAST_I:%.*]] = trunc i64 [[TMP0]] to i32
+// RV64ZBB-NEXT:ret i32 [[CAST_I]]
+//
+unsigned int cpop_64(uint64_t a) {
+  return __riscv_cpop_64(a);
+}
+#endif



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


[clang] [clang] Add build type to LibASTMatchersTutorial.rst cmake (PR #76301)

2023-12-24 Thread Timm Baeder via cfe-commits

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


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


[clang] 1dc715a - [Clang][RISCV] Add missing support for `__riscv_clmulr_32/64` in `riscv_bitmanip.h` (#76289)

2023-12-24 Thread via cfe-commits

Author: Yingwei Zheng
Date: 2023-12-24T16:14:22+08:00
New Revision: 1dc715a8a4d058dc8b7afbf9ce3fff5a3ff6e4ef

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

LOG: [Clang][RISCV] Add missing support for `__riscv_clmulr_32/64` in 
`riscv_bitmanip.h` (#76289)

This patch adds support for `__riscv_clmulr_32/64` in `riscv_bitmanip.h`.
It also fixes the extension requirements of `clmul/clmulh`.

Added: 


Modified: 
clang/lib/Headers/riscv_bitmanip.h
clang/test/CodeGen/RISCV/rvb-intrinsics/zbc.c

Removed: 




diff  --git a/clang/lib/Headers/riscv_bitmanip.h 
b/clang/lib/Headers/riscv_bitmanip.h
index 044cbaa037e43a..2bc7ee022a96bd 100644
--- a/clang/lib/Headers/riscv_bitmanip.h
+++ b/clang/lib/Headers/riscv_bitmanip.h
@@ -120,7 +120,23 @@ __riscv_zip_32(uint32_t __x) {
 #endif
 #endif // defined(__riscv_zbkb)
 
-#if defined(__riscv_zbkc)
+#if defined(__riscv_zbc)
+#if __riscv_xlen == 32
+static __inline__ uint32_t __attribute__((__always_inline__, __nodebug__))
+__riscv_clmulr_32(uint32_t __x, uint32_t __y) {
+  return __builtin_riscv_clmulr_32(__x, __y);
+}
+#endif
+
+#if __riscv_xlen == 64
+static __inline__ uint64_t __attribute__((__always_inline__, __nodebug__))
+__riscv_clmulr_64(uint64_t __x, uint64_t __y) {
+  return __builtin_riscv_clmulr_64(__x, __y);
+}
+#endif
+#endif // defined(__riscv_zbc)
+
+#if defined(__riscv_zbkc) || defined(__riscv_zbc)
 static __inline__ uint32_t __attribute__((__always_inline__, __nodebug__))
 __riscv_clmul_32(uint32_t __x, uint32_t __y) {
   return __builtin_riscv_clmul_32(__x, __y);
@@ -144,7 +160,7 @@ __riscv_clmulh_64(uint64_t __x, uint64_t __y) {
   return __builtin_riscv_clmulh_64(__x, __y);
 }
 #endif
-#endif // defined(__riscv_zbkc)
+#endif // defined(__riscv_zbkc) || defined(__riscv_zbc)
 
 #if defined(__riscv_zbkx)
 #if __riscv_xlen == 32

diff  --git a/clang/test/CodeGen/RISCV/rvb-intrinsics/zbc.c 
b/clang/test/CodeGen/RISCV/rvb-intrinsics/zbc.c
index ae9153eff155e1..93db3a482ef2bc 100644
--- a/clang/test/CodeGen/RISCV/rvb-intrinsics/zbc.c
+++ b/clang/test/CodeGen/RISCV/rvb-intrinsics/zbc.c
@@ -6,7 +6,7 @@
 // RUN: -disable-O0-optnone | opt -S -passes=mem2reg \
 // RUN: | FileCheck %s  -check-prefix=RV64ZBC
 
-#include 
+#include 
 
 #if __riscv_xlen == 64
 // RV64ZBC-LABEL: @clmul_64(
@@ -15,7 +15,7 @@
 // RV64ZBC-NEXT:ret i64 [[TMP0]]
 //
 uint64_t clmul_64(uint64_t a, uint64_t b) {
-  return __builtin_riscv_clmul_64(a, b);
+  return __riscv_clmul_64(a, b);
 }
 
 // RV64ZBC-LABEL: @clmulh_64(
@@ -24,7 +24,7 @@ uint64_t clmul_64(uint64_t a, uint64_t b) {
 // RV64ZBC-NEXT:ret i64 [[TMP0]]
 //
 uint64_t clmulh_64(uint64_t a, uint64_t b) {
-  return __builtin_riscv_clmulh_64(a, b);
+  return __riscv_clmulh_64(a, b);
 }
 
 // RV64ZBC-LABEL: @clmulr_64(
@@ -33,7 +33,7 @@ uint64_t clmulh_64(uint64_t a, uint64_t b) {
 // RV64ZBC-NEXT:ret i64 [[TMP0]]
 //
 uint64_t clmulr_64(uint64_t a, uint64_t b) {
-  return __builtin_riscv_clmulr_64(a, b);
+  return __riscv_clmulr_64(a, b);
 }
 #endif
 
@@ -48,7 +48,7 @@ uint64_t clmulr_64(uint64_t a, uint64_t b) {
 // RV64ZBC-NEXT:ret i32 [[TMP0]]
 //
 uint32_t clmul_32(uint32_t a, uint32_t b) {
-  return __builtin_riscv_clmul_32(a, b);
+  return __riscv_clmul_32(a, b);
 }
 
 #if __riscv_xlen == 32
@@ -58,7 +58,7 @@ uint32_t clmul_32(uint32_t a, uint32_t b) {
 // RV32ZBC-NEXT:ret i32 [[TMP0]]
 //
 uint32_t clmulh_32(uint32_t a, uint32_t b) {
-  return __builtin_riscv_clmulh_32(a, b);
+  return __riscv_clmulh_32(a, b);
 }
 
 // RV32ZBC-LABEL: @clmulr_32(
@@ -67,6 +67,6 @@ uint32_t clmulh_32(uint32_t a, uint32_t b) {
 // RV32ZBC-NEXT:ret i32 [[TMP0]]
 //
 uint32_t clmulr_32(uint32_t a, uint32_t b) {
-  return __builtin_riscv_clmulr_32(a, b);
+  return __riscv_clmulr_32(a, b);
 }
 #endif



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


[clang] [Clang][RISCV] Add missing support for `__riscv_clmulr_32/64` in `riscv_bitmanip.h` (PR #76289)

2023-12-24 Thread Yingwei Zheng via cfe-commits

https://github.com/dtcxzyw closed 
https://github.com/llvm/llvm-project/pull/76289
___
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 check readability-return-expression-in-void-function (PR #76249)

2023-12-24 Thread Piotr Zegar via cfe-commits
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= ,
Danny =?utf-8?q?Mösch?= 
Message-ID:
In-Reply-To: 


PiotrZSL wrote:

I run check on llvm-project, finds thousands of issues. Most of them comes from 
google test but other issues are like this one:
```
if (x)
  return call();
```

Just some simplification to not write {}.
I think that both IgnoreMacros and StrictMode(false) could be needed. If 
StrictMode is false then only returnStmt that got compoundStmt as parent should 
be check, to reduce impact.

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


[clang-tools-extra] Allow to pass config file to clang-tidy-diff (PR #75457)

2023-12-24 Thread Piotr Zegar via cfe-commits

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

LGTM, release notes can always by changed later if needed.

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


[clang-tools-extra] Allow to pass config file to clang-tidy-diff (PR #75457)

2023-12-24 Thread Piotr Zegar via cfe-commits

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

LGTM (wrong button)

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


[clang-tools-extra] [clang-tidy] introduce a unused local non trival variable check (PR #76101)

2023-12-24 Thread Piotr Zegar via cfe-commits


@@ -0,0 +1,89 @@
+//===--- UnusedLocalNonTrivialVariableCheck.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 "UnusedLocalNonTrivialVariableCheck.h"
+#include "../utils/Matchers.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersMacros.h"
+
+using namespace clang::ast_matchers;
+using namespace clang::tidy::matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+static constexpr StringRef DefaultIncludeTypeRegex = 
"std::.*mutex;std::future";

PiotrZSL wrote:

I think that this std::string wont be detected because this is just typedef, 
and oryginal type is actually a std::base_string.

Consider adding those as default:
```
std::basic_istringstream
std::basic_stringstream
std::basic_string_view
std::basic_string
std::bitset
std::basic_regex
std::path
```

Those do not cary object ownership, when things like std::vector could.
I assume that anyway almost eveyrone will use configuration that catch all and 
use excludes. You could put into documentation that default check configuration 
is limited and recommended is to set allowed to .* to catch as much as possible.

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


[clang] 8f9803b - [clang-format] Add an fnmatch-like function for .clang-format-ignore (#76021)

2023-12-24 Thread via cfe-commits

Author: Owen Pan
Date: 2023-12-24T01:05:10-08:00
New Revision: 8f9803b5ab0b03c31c8cb182b44bd2eb70d9d8b0

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

LOG: [clang-format] Add an fnmatch-like function for .clang-format-ignore 
(#76021)

This is needed because Windows doesn't have anything equivalent to the
POSIX fnmatch() function.

Added: 
clang/lib/Format/MatchFilePath.cpp
clang/lib/Format/MatchFilePath.h
clang/unittests/Format/MatchFilePathTest.cpp

Modified: 
clang/lib/Format/CMakeLists.txt
clang/unittests/Format/CMakeLists.txt

Removed: 




diff  --git a/clang/lib/Format/CMakeLists.txt b/clang/lib/Format/CMakeLists.txt
index 015ec7c0cc84e3..84a3c136f650a8 100644
--- a/clang/lib/Format/CMakeLists.txt
+++ b/clang/lib/Format/CMakeLists.txt
@@ -11,6 +11,7 @@ add_clang_library(clangFormat
   IntegerLiteralSeparatorFixer.cpp
   MacroCallReconstructor.cpp
   MacroExpander.cpp
+  MatchFilePath.cpp
   NamespaceEndCommentsFixer.cpp
   ObjCPropertyAttributeOrderFixer.cpp
   QualifierAlignmentFixer.cpp

diff  --git a/clang/lib/Format/MatchFilePath.cpp 
b/clang/lib/Format/MatchFilePath.cpp
new file mode 100644
index 00..412ee4954587e0
--- /dev/null
+++ b/clang/lib/Format/MatchFilePath.cpp
@@ -0,0 +1,122 @@
+//===--- MatchFilePath.cpp - Match file path with pattern ---*- 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
+//
+//===--===//
+///
+/// \file
+/// This file implements the functionality of matching a file path name to
+/// a pattern, similar to the POSIX fnmatch() function.
+///
+//===--===//
+
+#include "MatchFilePath.h"
+
+using namespace llvm;
+
+namespace clang {
+namespace format {
+
+// Check whether `FilePath` matches `Pattern` based on POSIX (1003.1-2008)
+// 2.13.1, 2.13.2, and Rule 1 of 2.13.3.
+bool matchFilePath(StringRef Pattern, StringRef FilePath) {
+  assert(!Pattern.empty());
+  assert(!FilePath.empty());
+
+  // 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())
+return false;
+
+  constexpr auto Separator = '/';
+  const auto EOP = Pattern.size();  // End of `Pattern`.
+  const auto End = FilePath.size(); // End of `FilePath`.
+  unsigned I = 0;   // Index to `Pattern`.
+
+  for (unsigned J = 0; J < End; ++J) {
+if (I == EOP)
+  return false;
+
+switch (const auto F = FilePath[J]; Pattern[I]) {
+case '\\':
+  if (++I == EOP || F != Pattern[I])
+return false;
+  break;
+case '?':
+  if (F == Separator)
+return false;
+  break;
+case '*': {
+  while (++I < EOP && Pattern[I] == '*') { // Skip consecutive stars.
+  }
+  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;
+  // 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;
+  }
+  // Recurse.
+  for (auto Pat = Pattern.substr(I); J < End && FilePath[J] != Separator;
+   ++J) {
+if (matchFilePath(Pat, FilePath.substr(J)))
+  return true;
+  }
+  return false;
+}
+case '[':
+  // Skip e.g. `[!]`.
+  if (I + 3 < EOP || (I + 3 == EOP && Pattern[I + 1] != '!')) {
+// Skip unpaired `[`, brackets containing slashes, and `[]`.
+if (const auto K = Pattern.find_first_of("]/", I + 1);
+K != StringRef::npos && Pattern[K] == ']' && K > I + 1) {
+  if (F == Separator)
+return false;
+  ++I; // After the `[`.
+  bool Negated = false;
+  if (Pattern[I] == '!') {
+Negated = true;
+++I; // After the `!`.
+  }
+  bool Match = false;
+  do {
+if (I + 2 < K && Pattern[I + 1] == '-') {
+  Match = Pattern[I] <= F && F <= Pattern[I + 2];
+  I += 3; // After the range, e.g. `A-Z`.
+} else {
+  Match = F == Pattern[I++];
+}
+  } while (!Match

[clang] [clang-format] Add an fnmatch-like function for .clang-format-ignore (PR #76021)

2023-12-24 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Add .clang-format.ignore for ignoring files (PR #76327)

2023-12-24 Thread Owen Pan via cfe-commits

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

Closes #52975.

>From 4afd12db61528b40d842a7fbee9af37c2235822c Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sun, 24 Dec 2023 01:18:55 -0800
Subject: [PATCH] [clang-format] Add .clang-format.ignore for ignoring files

Closes #52975.
---
 clang/docs/ClangFormat.rst| 18 ++
 clang/test/Format/clang-format-ignore.cpp | 24 
 clang/tools/clang-format/ClangFormat.cpp  | 71 ++-
 3 files changed, 112 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/Format/clang-format-ignore.cpp

diff --git a/clang/docs/ClangFormat.rst b/clang/docs/ClangFormat.rst
index f52f35550d03eb..a0b28f2273991f 100644
--- a/clang/docs/ClangFormat.rst
+++ b/clang/docs/ClangFormat.rst
@@ -131,6 +131,24 @@ An easy way to create the ``.clang-format`` file is:
 
 Available style options are described in :doc:`ClangFormatStyleOptions`.
 
+You can create ``.clang-format-ignore`` files to make ``clang-format`` ignore
+certain files. A ``.clang-format-ignore`` file consists of patterns of file 
path
+names. It has the following format:
+- A blank line is skipped.
+- Leading and trailing spaces of a line are trimmed.
+- A line starting with a hash (``#``) is a comment.
+- A non-comment line is a single pattern.
+- The slash (``/``) is used as the directory separator.
+- A pattern is relative to the directory of the ``.clang-format-ignore`` file
+  (or the root directory if the pattern starts with a slash).
+- Patterns follow the rules specified in POSIX 2.13.1, 2.13.2, and Rule 1 of
+  2.13.3.
+- 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
+the directory of the ``.clang-format-ignore`` file, use ``*``.
+Multiple ``.clang-format-ignore`` files are supported similar to the
+``.clang-format`` files, with a lower directory level file voiding the higher
+level ones.
 
 Vim Integration
 ===
diff --git a/clang/test/Format/clang-format-ignore.cpp 
b/clang/test/Format/clang-format-ignore.cpp
new file mode 100644
index 00..a2210266034d4c
--- /dev/null
+++ b/clang/test/Format/clang-format-ignore.cpp
@@ -0,0 +1,24 @@
+// RUN: mkdir -p %t.dir/level1/level2
+
+// RUN: cd %t.dir
+// RUN: printf "*\nlevel*/*.c*\n*/*2/foo.*\n" > .clang-format-ignore
+// RUN: touch foo.cc
+// RUN: clang-format -verbose .clang-format-ignore foo.cc 2> %t.stderr
+// RUN: not grep "Formatting" %t.stderr
+
+// RUN: cd level1
+// RUN: touch bar.cc baz.c
+// RUN: clang-format -verbose bar.cc baz.c 2> %t.stderr
+// RUN: not grep "Formatting" %t.stderr
+
+// RUN: cd level2
+// RUN: touch foo.c foo.js
+// RUN: clang-format -verbose foo.c foo.js 2> %t.stderr
+// RUN: not grep "Formatting" %t.stderr
+// RUN: printf "*.js\n" > .clang-format-ignore
+// RUN: clang-format -verbose foo.c foo.js 2> %t.stderr
+// RUN: grep -E "Formatting (.*)foo.c(.*)" %t.stderr
+// RUN: not grep -E "Formatting (.*)foo.js(.*)" %t.stderr
+
+// RUN: cd ../../..
+// RUN: rm -rf %t.dir
diff --git a/clang/tools/clang-format/ClangFormat.cpp 
b/clang/tools/clang-format/ClangFormat.cpp
index d2e3d8d43aef21..be78f8cbebf5e1 100644
--- a/clang/tools/clang-format/ClangFormat.cpp
+++ b/clang/tools/clang-format/ClangFormat.cpp
@@ -12,6 +12,7 @@
 ///
 
//===--===//
 
+#include "../../lib/Format/MatchFilePath.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/FileManager.h"
@@ -570,6 +571,71 @@ static int dumpConfig(bool IsSTDIN) {
   return 0;
 }
 
+// Check whether `FilePath` is ignored according to the nearest
+// .clang-format-ignore file based on the rules below:
+// - A blank line is skipped.
+// - Leading and trailing spaces of a line are trimmed.
+// - A line starting with a hash (`#`) is a comment.
+// - A non-comment line is a single pattern.
+// - The slash (`/`) is used as the directory separator.
+// - A pattern is relative to the directory of the .clang-format-ignore file 
(or
+//   the root directory if the pattern starts with a slash).
+// - A pattern is negated if it starts with a bang (`!`).
+static bool isIgnored(const StringRef FilePath) {
+  if (!llvm::sys::fs::is_regular_file(FilePath))
+return false;
+
+  using namespace llvm::sys::path;
+  SmallString<128> Path, AbsPath{convert_to_slash(FilePath)};
+
+  llvm::vfs::getRealFileSystem()->makeAbsolute(AbsPath);
+  remove_dots(AbsPath, /*remove_dot_dot=*/true);
+
+  StringRef IgnoreDir{AbsPath};
+  do {
+IgnoreDir = parent_path(IgnoreDir);
+if (IgnoreDir.empty())
+  return false;
+
+Path = IgnoreDir;
+append(Path, ".clang-format-ignore");
+  } while (!llvm::sys::fs::is_regular_file(Path));
+
+  std::ifstream IgnoreFile{Path.c_str()};
+  if (!IgnoreFile.good())
+return false;
+
+  bool HasMatch = false;
+  for (std::string Pattern; std::getline(IgnoreFile, Patter

[clang] [clang-format] Add .clang-format.ignore for ignoring files (PR #76327)

2023-12-24 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang

@llvm/pr-subscribers-clang-format

Author: Owen Pan (owenca)


Changes

Closes #52975.

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


3 Files Affected:

- (modified) clang/docs/ClangFormat.rst (+18) 
- (added) clang/test/Format/clang-format-ignore.cpp (+24) 
- (modified) clang/tools/clang-format/ClangFormat.cpp (+70-1) 


``diff
diff --git a/clang/docs/ClangFormat.rst b/clang/docs/ClangFormat.rst
index f52f35550d03eb..a0b28f2273991f 100644
--- a/clang/docs/ClangFormat.rst
+++ b/clang/docs/ClangFormat.rst
@@ -131,6 +131,24 @@ An easy way to create the ``.clang-format`` file is:
 
 Available style options are described in :doc:`ClangFormatStyleOptions`.
 
+You can create ``.clang-format-ignore`` files to make ``clang-format`` ignore
+certain files. A ``.clang-format-ignore`` file consists of patterns of file 
path
+names. It has the following format:
+- A blank line is skipped.
+- Leading and trailing spaces of a line are trimmed.
+- A line starting with a hash (``#``) is a comment.
+- A non-comment line is a single pattern.
+- The slash (``/``) is used as the directory separator.
+- A pattern is relative to the directory of the ``.clang-format-ignore`` file
+  (or the root directory if the pattern starts with a slash).
+- Patterns follow the rules specified in POSIX 2.13.1, 2.13.2, and Rule 1 of
+  2.13.3.
+- 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
+the directory of the ``.clang-format-ignore`` file, use ``*``.
+Multiple ``.clang-format-ignore`` files are supported similar to the
+``.clang-format`` files, with a lower directory level file voiding the higher
+level ones.
 
 Vim Integration
 ===
diff --git a/clang/test/Format/clang-format-ignore.cpp 
b/clang/test/Format/clang-format-ignore.cpp
new file mode 100644
index 00..a2210266034d4c
--- /dev/null
+++ b/clang/test/Format/clang-format-ignore.cpp
@@ -0,0 +1,24 @@
+// RUN: mkdir -p %t.dir/level1/level2
+
+// RUN: cd %t.dir
+// RUN: printf "*\nlevel*/*.c*\n*/*2/foo.*\n" > .clang-format-ignore
+// RUN: touch foo.cc
+// RUN: clang-format -verbose .clang-format-ignore foo.cc 2> %t.stderr
+// RUN: not grep "Formatting" %t.stderr
+
+// RUN: cd level1
+// RUN: touch bar.cc baz.c
+// RUN: clang-format -verbose bar.cc baz.c 2> %t.stderr
+// RUN: not grep "Formatting" %t.stderr
+
+// RUN: cd level2
+// RUN: touch foo.c foo.js
+// RUN: clang-format -verbose foo.c foo.js 2> %t.stderr
+// RUN: not grep "Formatting" %t.stderr
+// RUN: printf "*.js\n" > .clang-format-ignore
+// RUN: clang-format -verbose foo.c foo.js 2> %t.stderr
+// RUN: grep -E "Formatting (.*)foo.c(.*)" %t.stderr
+// RUN: not grep -E "Formatting (.*)foo.js(.*)" %t.stderr
+
+// RUN: cd ../../..
+// RUN: rm -rf %t.dir
diff --git a/clang/tools/clang-format/ClangFormat.cpp 
b/clang/tools/clang-format/ClangFormat.cpp
index d2e3d8d43aef21..be78f8cbebf5e1 100644
--- a/clang/tools/clang-format/ClangFormat.cpp
+++ b/clang/tools/clang-format/ClangFormat.cpp
@@ -12,6 +12,7 @@
 ///
 
//===--===//
 
+#include "../../lib/Format/MatchFilePath.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/FileManager.h"
@@ -570,6 +571,71 @@ static int dumpConfig(bool IsSTDIN) {
   return 0;
 }
 
+// Check whether `FilePath` is ignored according to the nearest
+// .clang-format-ignore file based on the rules below:
+// - A blank line is skipped.
+// - Leading and trailing spaces of a line are trimmed.
+// - A line starting with a hash (`#`) is a comment.
+// - A non-comment line is a single pattern.
+// - The slash (`/`) is used as the directory separator.
+// - A pattern is relative to the directory of the .clang-format-ignore file 
(or
+//   the root directory if the pattern starts with a slash).
+// - A pattern is negated if it starts with a bang (`!`).
+static bool isIgnored(const StringRef FilePath) {
+  if (!llvm::sys::fs::is_regular_file(FilePath))
+return false;
+
+  using namespace llvm::sys::path;
+  SmallString<128> Path, AbsPath{convert_to_slash(FilePath)};
+
+  llvm::vfs::getRealFileSystem()->makeAbsolute(AbsPath);
+  remove_dots(AbsPath, /*remove_dot_dot=*/true);
+
+  StringRef IgnoreDir{AbsPath};
+  do {
+IgnoreDir = parent_path(IgnoreDir);
+if (IgnoreDir.empty())
+  return false;
+
+Path = IgnoreDir;
+append(Path, ".clang-format-ignore");
+  } while (!llvm::sys::fs::is_regular_file(Path));
+
+  std::ifstream IgnoreFile{Path.c_str()};
+  if (!IgnoreFile.good())
+return false;
+
+  bool HasMatch = false;
+  for (std::string Pattern; std::getline(IgnoreFile, Pattern);) {
+Pattern = StringRef(Pattern).trim();
+if (Pattern.empty() || Pattern[0] == '#')
+  continue;
+
+const bool IsNegated = Pattern[0] == '!';
+if (IsNegated)
+  Pattern.erase(0, 1);
+

[clang] [clang-format] Add .clang-format.ignore for ignoring files (PR #76327)

2023-12-24 Thread Owen Pan via cfe-commits


@@ -131,6 +131,24 @@ An easy way to create the ``.clang-format`` file is:
 
 Available style options are described in :doc:`ClangFormatStyleOptions`.
 
+You can create ``.clang-format-ignore`` files to make ``clang-format`` ignore
+certain files. A ``.clang-format-ignore`` file consists of patterns of file 
path
+names. It has the following format:
+- A blank line is skipped.
+- Leading and trailing spaces of a line are trimmed.
+- A line starting with a hash (``#``) is a comment.
+- A non-comment line is a single pattern.
+- The slash (``/``) is used as the directory separator.
+- A pattern is relative to the directory of the ``.clang-format-ignore`` file
+  (or the root directory if the pattern starts with a slash).
+- Patterns follow the rules specified in POSIX 2.13.1, 2.13.2, and Rule 1 of
+  2.13.3.

owenca wrote:

```suggestion
(or the root directory if the pattern starts with a slash).
- Patterns follow the rules specified in POSIX 2.13.1, 2.13.2, and Rule 1 of
2.13.3.
```

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


[clang] [clang-format] Add .clang-format.ignore for ignoring files (PR #76327)

2023-12-24 Thread Owen Pan via cfe-commits

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

>From 4afd12db61528b40d842a7fbee9af37c2235822c Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sun, 24 Dec 2023 01:18:55 -0800
Subject: [PATCH 1/2] [clang-format] Add .clang-format.ignore for ignoring
 files

Closes #52975.
---
 clang/docs/ClangFormat.rst| 18 ++
 clang/test/Format/clang-format-ignore.cpp | 24 
 clang/tools/clang-format/ClangFormat.cpp  | 71 ++-
 3 files changed, 112 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/Format/clang-format-ignore.cpp

diff --git a/clang/docs/ClangFormat.rst b/clang/docs/ClangFormat.rst
index f52f35550d03eb..a0b28f2273991f 100644
--- a/clang/docs/ClangFormat.rst
+++ b/clang/docs/ClangFormat.rst
@@ -131,6 +131,24 @@ An easy way to create the ``.clang-format`` file is:
 
 Available style options are described in :doc:`ClangFormatStyleOptions`.
 
+You can create ``.clang-format-ignore`` files to make ``clang-format`` ignore
+certain files. A ``.clang-format-ignore`` file consists of patterns of file 
path
+names. It has the following format:
+- A blank line is skipped.
+- Leading and trailing spaces of a line are trimmed.
+- A line starting with a hash (``#``) is a comment.
+- A non-comment line is a single pattern.
+- The slash (``/``) is used as the directory separator.
+- A pattern is relative to the directory of the ``.clang-format-ignore`` file
+  (or the root directory if the pattern starts with a slash).
+- Patterns follow the rules specified in POSIX 2.13.1, 2.13.2, and Rule 1 of
+  2.13.3.
+- 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
+the directory of the ``.clang-format-ignore`` file, use ``*``.
+Multiple ``.clang-format-ignore`` files are supported similar to the
+``.clang-format`` files, with a lower directory level file voiding the higher
+level ones.
 
 Vim Integration
 ===
diff --git a/clang/test/Format/clang-format-ignore.cpp 
b/clang/test/Format/clang-format-ignore.cpp
new file mode 100644
index 00..a2210266034d4c
--- /dev/null
+++ b/clang/test/Format/clang-format-ignore.cpp
@@ -0,0 +1,24 @@
+// RUN: mkdir -p %t.dir/level1/level2
+
+// RUN: cd %t.dir
+// RUN: printf "*\nlevel*/*.c*\n*/*2/foo.*\n" > .clang-format-ignore
+// RUN: touch foo.cc
+// RUN: clang-format -verbose .clang-format-ignore foo.cc 2> %t.stderr
+// RUN: not grep "Formatting" %t.stderr
+
+// RUN: cd level1
+// RUN: touch bar.cc baz.c
+// RUN: clang-format -verbose bar.cc baz.c 2> %t.stderr
+// RUN: not grep "Formatting" %t.stderr
+
+// RUN: cd level2
+// RUN: touch foo.c foo.js
+// RUN: clang-format -verbose foo.c foo.js 2> %t.stderr
+// RUN: not grep "Formatting" %t.stderr
+// RUN: printf "*.js\n" > .clang-format-ignore
+// RUN: clang-format -verbose foo.c foo.js 2> %t.stderr
+// RUN: grep -E "Formatting (.*)foo.c(.*)" %t.stderr
+// RUN: not grep -E "Formatting (.*)foo.js(.*)" %t.stderr
+
+// RUN: cd ../../..
+// RUN: rm -rf %t.dir
diff --git a/clang/tools/clang-format/ClangFormat.cpp 
b/clang/tools/clang-format/ClangFormat.cpp
index d2e3d8d43aef21..be78f8cbebf5e1 100644
--- a/clang/tools/clang-format/ClangFormat.cpp
+++ b/clang/tools/clang-format/ClangFormat.cpp
@@ -12,6 +12,7 @@
 ///
 
//===--===//
 
+#include "../../lib/Format/MatchFilePath.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/DiagnosticOptions.h"
 #include "clang/Basic/FileManager.h"
@@ -570,6 +571,71 @@ static int dumpConfig(bool IsSTDIN) {
   return 0;
 }
 
+// Check whether `FilePath` is ignored according to the nearest
+// .clang-format-ignore file based on the rules below:
+// - A blank line is skipped.
+// - Leading and trailing spaces of a line are trimmed.
+// - A line starting with a hash (`#`) is a comment.
+// - A non-comment line is a single pattern.
+// - The slash (`/`) is used as the directory separator.
+// - A pattern is relative to the directory of the .clang-format-ignore file 
(or
+//   the root directory if the pattern starts with a slash).
+// - A pattern is negated if it starts with a bang (`!`).
+static bool isIgnored(const StringRef FilePath) {
+  if (!llvm::sys::fs::is_regular_file(FilePath))
+return false;
+
+  using namespace llvm::sys::path;
+  SmallString<128> Path, AbsPath{convert_to_slash(FilePath)};
+
+  llvm::vfs::getRealFileSystem()->makeAbsolute(AbsPath);
+  remove_dots(AbsPath, /*remove_dot_dot=*/true);
+
+  StringRef IgnoreDir{AbsPath};
+  do {
+IgnoreDir = parent_path(IgnoreDir);
+if (IgnoreDir.empty())
+  return false;
+
+Path = IgnoreDir;
+append(Path, ".clang-format-ignore");
+  } while (!llvm::sys::fs::is_regular_file(Path));
+
+  std::ifstream IgnoreFile{Path.c_str()};
+  if (!IgnoreFile.good())
+return false;
+
+  bool HasMatch = false;
+  for (std::string Pattern; std::getline(IgnoreFile, Pattern);) {
+   

[clang-tools-extra] [clangd] Resolve the dependent type from its single instantiation. Take 1 (PR #71279)

2023-12-24 Thread Younan Zhang via cfe-commits

zyn0217 wrote:

Another issue I've encountered while at it is that, given the following code,
```cpp
void foo();
auto lambda = [] {
  return ^foo();
};
```
let `N` represent the selection node for the expression `foo()`, 
`N.getDeclContext()` then yields `TranslationUnitDecl` rather than the 
`CXXRecordDecl`of the lambda expression.

I presume there's something wrong at `SelectionTree::Node::getDeclContext()`, 
because lambda expressions would slip through the current traversal logic.

```txt
`-LambdaExpr  '(lambda at line:2:15)'<-- parent 3; not a 
Decl thus ignored!
  |-CXXRecordDecl  col:15 implicit class definition
  | |-DefinitionData
  | | |-DefaultConstructor
  | | |-CopyConstructor
  | | |-MoveConstructor
  | | |-CopyAssignment
  | | |-MoveAssignment
  | | `-Destructor
  | |-CXXMethodDecl  line:2:15 constexpr operator() 'auto () 
const -> void' inline
  | | `-CompoundStmt 
  | |   `-ReturnStmt 
  | | `-CallExpr  'void'
  | |   `-ImplicitCastExpr  'void (*)()' 
  | | `-DeclRefExpr  'void ()' lvalue Function 0xb76c1c8 'foo' 
'void ()'
  | |-CXXConversionDecl  line:2:15 implicit constexpr 
operator void (*)() 'auto (*() const noexcept)() -> void' inline
  | |-CXXMethodDecl  line:2:15 implicit __invoke 'auto () -> 
void' static inline
  | `-CXXDestructorDecl  col:15 implicit referenced constexpr ~(lambda 
at line:2:15) 'void () noexcept' inline default trivial
  `-CompoundStmt<--parent 2
`-ReturnStmt<-- parent 1
  `-CallExpr  'void'   <-- starting point
`-ImplicitCastExpr  'void (*)()' 
  `-DeclRefExpr  'void ()' lvalue Function 0xb76c1c8 'foo' 
'void ()'
```

https://github.com/llvm/llvm-project/blob/51b988efb06f0343e7b71c9aec9ec3195412179d/clang-tools-extra/clangd/Selection.cpp#L1107-L1118

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


[clang-tools-extra] [clangd] Handle lambda scopes inside Node::getDeclContext() (PR #76329)

2023-12-24 Thread Younan Zhang via cfe-commits

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

We used to consider the `DeclContext` for selection nodes inside a lambda as 
the enclosing scope of the lambda expression, rather than the lambda itself.

For example,

```cpp
void foo();
auto lambda = [] {
  return ^foo();
};
```

where `N` is the selection node for the expression `foo()`, 
`N.getDeclContext()` returns the `TranslationUnitDecl` previously, which IMO is 
wrong, since the `RecordDecl` of the lambda is closer.

Seemingly, this affects nothing currently.

>From c0b04507075b39e494d3e6fa39168bc47b92f338 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Sun, 24 Dec 2023 18:08:30 +0800
Subject: [PATCH] [clangd] Handle lambda scopes inside Node::getDeclContext()

We used to consider the DeclContext for selection nodes inside
a lambda as the scope of the lambda expression locates in.

For example,

```cpp
void foo();
auto lambda = [] {
  return ^foo();
};
```

where N is the selection node for the expression `foo()`,
`N.getDeclContext()` returns the TranslationUnitDecl previously,
which IMO is wrong, since the RecordDecl of the lambda is closer.
---
 clang-tools-extra/clangd/Selection.cpp  |  3 +++
 .../clangd/unittests/SelectionTests.cpp | 13 +
 2 files changed, 16 insertions(+)

diff --git a/clang-tools-extra/clangd/Selection.cpp 
b/clang-tools-extra/clangd/Selection.cpp
index 8c6d5750ecefdb..a7413485b04ac3 100644
--- a/clang-tools-extra/clangd/Selection.cpp
+++ b/clang-tools-extra/clangd/Selection.cpp
@@ -1113,6 +1113,9 @@ const DeclContext &SelectionTree::Node::getDeclContext() 
const {
   return *DC;
   return *Current->getLexicalDeclContext();
 }
+if (auto *LE = CurrentNode->ASTNode.get())
+  if (CurrentNode != this)
+return *LE->getLambdaClass();
   }
   llvm_unreachable("A tree must always be rooted at TranslationUnitDecl.");
 }
diff --git a/clang-tools-extra/clangd/unittests/SelectionTests.cpp 
b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
index 4c019a1524f3c3..cdb50dfc1c3095 100644
--- a/clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -880,6 +880,19 @@ TEST(SelectionTest, DeclContextIsLexical) {
   }
 }
 
+TEST(SelectionTest, DeclContextLambda) {
+  llvm::Annotations Test(R"cpp(
+void foo();
+auto lambda = [] {
+  return $1^foo();
+};
+  )cpp");
+  auto AST = TestTU::withCode(Test.code()).build();
+  auto ST = SelectionTree::createRight(AST.getASTContext(), AST.getTokens(),
+   Test.point("1"), Test.point("1"));
+  EXPECT_FALSE(ST.commonAncestor()->getDeclContext().isTranslationUnit());
+}
+
 } // namespace
 } // 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] Handle lambda scopes inside Node::getDeclContext() (PR #76329)

2023-12-24 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clangd

Author: Younan Zhang (zyn0217)


Changes

We used to consider the `DeclContext` for selection nodes inside a lambda as 
the enclosing scope of the lambda expression, rather than the lambda itself.

For example,

```cpp
void foo();
auto lambda = [] {
  return ^foo();
};
```

where `N` is the selection node for the expression `foo()`, 
`N.getDeclContext()` returns the `TranslationUnitDecl` previously, which IMO is 
wrong, since the `RecordDecl` of the lambda is closer.

Seemingly, this affects nothing currently.

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


2 Files Affected:

- (modified) clang-tools-extra/clangd/Selection.cpp (+3) 
- (modified) clang-tools-extra/clangd/unittests/SelectionTests.cpp (+13) 


``diff
diff --git a/clang-tools-extra/clangd/Selection.cpp 
b/clang-tools-extra/clangd/Selection.cpp
index 8c6d5750ecefdb..a7413485b04ac3 100644
--- a/clang-tools-extra/clangd/Selection.cpp
+++ b/clang-tools-extra/clangd/Selection.cpp
@@ -1113,6 +1113,9 @@ const DeclContext &SelectionTree::Node::getDeclContext() 
const {
   return *DC;
   return *Current->getLexicalDeclContext();
 }
+if (auto *LE = CurrentNode->ASTNode.get())
+  if (CurrentNode != this)
+return *LE->getLambdaClass();
   }
   llvm_unreachable("A tree must always be rooted at TranslationUnitDecl.");
 }
diff --git a/clang-tools-extra/clangd/unittests/SelectionTests.cpp 
b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
index 4c019a1524f3c3..cdb50dfc1c3095 100644
--- a/clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -880,6 +880,19 @@ TEST(SelectionTest, DeclContextIsLexical) {
   }
 }
 
+TEST(SelectionTest, DeclContextLambda) {
+  llvm::Annotations Test(R"cpp(
+void foo();
+auto lambda = [] {
+  return $1^foo();
+};
+  )cpp");
+  auto AST = TestTU::withCode(Test.code()).build();
+  auto ST = SelectionTree::createRight(AST.getASTContext(), AST.getTokens(),
+   Test.point("1"), Test.point("1"));
+  EXPECT_FALSE(ST.commonAncestor()->getDeclContext().isTranslationUnit());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang

``




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


[clang-tools-extra] [WIP][clangd] Resolve the dependent type from its single instantiation. Take 1 (PR #71279)

2023-12-24 Thread Younan Zhang via cfe-commits

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


[clang-tools-extra] [WIP][clangd] Resolve the dependent type from its single instantiation. Take 1 (PR #71279)

2023-12-24 Thread Younan Zhang via cfe-commits

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


[clang-tools-extra] [WIP][clangd] Resolve the dependent type from its single instantiation. Take 1 (PR #71279)

2023-12-24 Thread Younan Zhang via cfe-commits

https://github.com/zyn0217 updated 
https://github.com/llvm/llvm-project/pull/71279

>From c0703d7d9549e82434b37f9d5658b566a480d752 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Sat, 4 Nov 2023 18:43:58 +0800
Subject: [PATCH 1/4] [clangd] Resolve the dependent type from its single
 instantiation. Take 1

This is an enhancement to the HeuristicResolver, trying to extract
the deduced type from the single instantiation for a template. This
partially addresses the point #1 from
https://github.com/clangd/clangd/issues/1768.

This patch doesn't tackle CXXUnresolvedConstructExpr or similarities
since I feel that is more arduous and would prefer to leave it for
my future work.
---
 .../clangd/HeuristicResolver.cpp  | 101 ++
 .../clangd/unittests/XRefsTests.cpp   |  48 +
 2 files changed, 149 insertions(+)

diff --git a/clang-tools-extra/clangd/HeuristicResolver.cpp 
b/clang-tools-extra/clangd/HeuristicResolver.cpp
index 3c147b6b582bf0..d3dced9b325367 100644
--- a/clang-tools-extra/clangd/HeuristicResolver.cpp
+++ b/clang-tools-extra/clangd/HeuristicResolver.cpp
@@ -7,10 +7,14 @@
 
//===--===//
 
 #include "HeuristicResolver.h"
+#include "AST.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/CXXInheritance.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/ExprCXX.h"
+#include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/Type.h"
 
 namespace clang {
@@ -46,6 +50,98 @@ const Type *resolveDeclsToType(const std::vector &Decls,
   return nullptr;
 }
 
+// Visitor that helps to extract deduced type from instantiated entities.
+// This merely performs the source location comparison against each Decl
+// until it finds a Decl with the same location as the
+// dependent one. Its associated type will then be extracted.
+struct InstantiatedDeclVisitor : RecursiveASTVisitor {
+
+  InstantiatedDeclVisitor(NamedDecl *DependentDecl) : 
DependentDecl(DependentDecl) {}
+
+  bool shouldVisitTemplateInstantiations() const { return true; }
+
+  bool shouldVisitLambdaBody() const { return true; }
+
+  bool shouldVisitImplicitCode() const { return true; }
+
+  template 
+  bool onDeclVisited(D *MaybeInstantiated) {
+if (MaybeInstantiated->getDeclContext()->isDependentContext())
+  return true;
+auto *Dependent = dyn_cast(DependentDecl);
+if (!Dependent)
+  return true;
+auto LHS = MaybeInstantiated->getTypeSourceInfo(),
+ RHS = Dependent->getTypeSourceInfo();
+if (!LHS || !RHS)
+  return true;
+if (LHS->getTypeLoc().getSourceRange() !=
+RHS->getTypeLoc().getSourceRange())
+  return true;
+DeducedType = MaybeInstantiated->getType();
+return false;
+  }
+
+  bool VisitFieldDecl(FieldDecl *FD) {
+return onDeclVisited(FD);
+  }
+
+  bool VisitVarDecl(VarDecl *VD) {
+return onDeclVisited(VD);
+  }
+
+  NamedDecl *DependentDecl;
+  QualType DeducedType;
+};
+
+/// Attempt to resolve the dependent type from the surrounding context for 
which
+/// a single instantiation is available.
+const Type *
+resolveTypeFromInstantiatedTemplate(const CXXDependentScopeMemberExpr *Expr) {
+  if (Expr->isImplicitAccess())
+return nullptr;
+
+  auto *Base = Expr->getBase();
+  NamedDecl *ND = nullptr;
+  if (auto *CXXMember = dyn_cast(Base))
+ND = CXXMember->getMemberDecl();
+
+  if (auto *DRExpr = dyn_cast(Base))
+ND = DRExpr->getFoundDecl();
+
+  // FIXME: Handle CXXUnresolvedConstructExpr. This kind of type doesn't have
+  // available Decls to be matched against. Which inhibits the current 
heuristic
+  // from resolving expressions such as `T().fo^o()`, where T is a
+  // single-instantiated template parameter.
+  if (!ND)
+return nullptr;
+
+  NamedDecl *Instantiation = nullptr;
+
+  // Find out a single instantiation that we can start with. The enclosing
+  // context for the current Decl might not be a templated entity (e.g. a 
member
+  // function inside a class template), hence we shall walk up the decl
+  // contexts first.
+  for (auto *EnclosingContext = ND->getDeclContext(); EnclosingContext;
+   EnclosingContext = EnclosingContext->getParent()) {
+if (auto *ND = dyn_cast(EnclosingContext)) {
+  Instantiation = getOnlyInstantiation(ND);
+  if (Instantiation)
+break;
+}
+  }
+
+  if (!Instantiation)
+return nullptr;
+
+  // This will traverse down the instantiation entity, visit each Decl, and
+  // extract the deduced type for the undetermined Decl `ND`.
+  InstantiatedDeclVisitor Visitor(ND);
+  Visitor.TraverseDecl(Instantiation);
+
+  return Visitor.DeducedType.getTypePtrOrNull();
+}
+
 } // namespace
 
 // Helper function for HeuristicResolver::resolveDependentMember()
@@ -150,6 +246,11 @@ std::vector 
HeuristicResolver::resolveMemberExpr(
   if (ME->isArrow()) {
 BaseType = getPointeeType(BaseType);
   }
+
+  if 

[clang] [clang-format] Fix bad indentation with attribute and templated type (PR #76336)

2023-12-24 Thread via cfe-commits

https://github.com/XDeme created https://github.com/llvm/llvm-project/pull/76336

Fixes llvm/llvm-project#76314

>From 24aa5e41505eebb64288e7369a3b4f35ee0214fc Mon Sep 17 00:00:00 2001
From: XDeme 
Date: Sun, 24 Dec 2023 11:27:31 -0300
Subject: [PATCH] [clang-format] Fix bad indentation with attribute and
 templated type

---
 clang/lib/Format/ContinuationIndenter.cpp | 2 +-
 clang/unittests/Format/FormatTest.cpp | 4 
 2 files changed, 5 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index 8489a30dd34ab3..102504182c4505 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -398,7 +398,7 @@ bool ContinuationIndenter::mustBreak(const LineState 
&State) {
   }
   if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
(Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) &&
-Style.isCpp() &&
+State.Line->First->isNot(TT_AttributeSquare) && Style.isCpp() &&
 // FIXME: This is a temporary workaround for the case where 
clang-format
 // sets BreakBeforeParameter to avoid bin packing and this creates a
 // completely unnecessary line break after a template type that isn't
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 762fc8254bdfc9..d5265aa230c7d2 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -26492,6 +26492,10 @@ TEST_F(FormatTest, BreakAfterAttributes) {
   verifyFormat("[[nodiscard]]\n"
"Foo& operator-(Foo&);",
Style);
+
+  verifyFormat("[[maybe_unused]]\n"
+   "foo f;",
+   Style);
 }
 
 TEST_F(FormatTest, InsertNewlineAtEOF) {

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


[clang] [clang-format] Fix bad indentation with attribute and templated type (PR #76336)

2023-12-24 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: None (XDeme)


Changes

Fixes llvm/llvm-project#76314

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


2 Files Affected:

- (modified) clang/lib/Format/ContinuationIndenter.cpp (+1-1) 
- (modified) clang/unittests/Format/FormatTest.cpp (+4) 


``diff
diff --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index 8489a30dd34ab3..102504182c4505 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -398,7 +398,7 @@ bool ContinuationIndenter::mustBreak(const LineState 
&State) {
   }
   if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) ||
(Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) &&
-Style.isCpp() &&
+State.Line->First->isNot(TT_AttributeSquare) && Style.isCpp() &&
 // FIXME: This is a temporary workaround for the case where 
clang-format
 // sets BreakBeforeParameter to avoid bin packing and this creates a
 // completely unnecessary line break after a template type that isn't
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 762fc8254bdfc9..d5265aa230c7d2 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -26492,6 +26492,10 @@ TEST_F(FormatTest, BreakAfterAttributes) {
   verifyFormat("[[nodiscard]]\n"
"Foo& operator-(Foo&);",
Style);
+
+  verifyFormat("[[maybe_unused]]\n"
+   "foo f;",
+   Style);
 }
 
 TEST_F(FormatTest, InsertNewlineAtEOF) {

``




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


[clang-tools-extra] [clangd] Handle lambda scopes inside Node::getDeclContext() (PR #76329)

2023-12-24 Thread Younan Zhang via cfe-commits

https://github.com/zyn0217 updated 
https://github.com/llvm/llvm-project/pull/76329

>From c0b04507075b39e494d3e6fa39168bc47b92f338 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Sun, 24 Dec 2023 18:08:30 +0800
Subject: [PATCH 1/2] [clangd] Handle lambda scopes inside
 Node::getDeclContext()

We used to consider the DeclContext for selection nodes inside
a lambda as the scope of the lambda expression locates in.

For example,

```cpp
void foo();
auto lambda = [] {
  return ^foo();
};
```

where N is the selection node for the expression `foo()`,
`N.getDeclContext()` returns the TranslationUnitDecl previously,
which IMO is wrong, since the RecordDecl of the lambda is closer.
---
 clang-tools-extra/clangd/Selection.cpp  |  3 +++
 .../clangd/unittests/SelectionTests.cpp | 13 +
 2 files changed, 16 insertions(+)

diff --git a/clang-tools-extra/clangd/Selection.cpp 
b/clang-tools-extra/clangd/Selection.cpp
index 8c6d5750ecefdb..a7413485b04ac3 100644
--- a/clang-tools-extra/clangd/Selection.cpp
+++ b/clang-tools-extra/clangd/Selection.cpp
@@ -1113,6 +1113,9 @@ const DeclContext &SelectionTree::Node::getDeclContext() 
const {
   return *DC;
   return *Current->getLexicalDeclContext();
 }
+if (auto *LE = CurrentNode->ASTNode.get())
+  if (CurrentNode != this)
+return *LE->getLambdaClass();
   }
   llvm_unreachable("A tree must always be rooted at TranslationUnitDecl.");
 }
diff --git a/clang-tools-extra/clangd/unittests/SelectionTests.cpp 
b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
index 4c019a1524f3c3..cdb50dfc1c3095 100644
--- a/clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -880,6 +880,19 @@ TEST(SelectionTest, DeclContextIsLexical) {
   }
 }
 
+TEST(SelectionTest, DeclContextLambda) {
+  llvm::Annotations Test(R"cpp(
+void foo();
+auto lambda = [] {
+  return $1^foo();
+};
+  )cpp");
+  auto AST = TestTU::withCode(Test.code()).build();
+  auto ST = SelectionTree::createRight(AST.getASTContext(), AST.getTokens(),
+   Test.point("1"), Test.point("1"));
+  EXPECT_FALSE(ST.commonAncestor()->getDeclContext().isTranslationUnit());
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang

>From 18274ed552f955172a788391393c58f8e32a65a6 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Sun, 24 Dec 2023 23:50:10 +0800
Subject: [PATCH 2/2] DC should be operator()

---
 clang-tools-extra/clangd/Selection.cpp| 4 ++--
 clang-tools-extra/clangd/unittests/SelectionTests.cpp | 2 +-
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/clang-tools-extra/clangd/Selection.cpp 
b/clang-tools-extra/clangd/Selection.cpp
index a7413485b04ac3..277cb8769a1b12 100644
--- a/clang-tools-extra/clangd/Selection.cpp
+++ b/clang-tools-extra/clangd/Selection.cpp
@@ -1113,9 +1113,9 @@ const DeclContext &SelectionTree::Node::getDeclContext() 
const {
   return *DC;
   return *Current->getLexicalDeclContext();
 }
-if (auto *LE = CurrentNode->ASTNode.get())
+if (const auto *LE = CurrentNode->ASTNode.get())
   if (CurrentNode != this)
-return *LE->getLambdaClass();
+return *LE->getCallOperator();
   }
   llvm_unreachable("A tree must always be rooted at TranslationUnitDecl.");
 }
diff --git a/clang-tools-extra/clangd/unittests/SelectionTests.cpp 
b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
index cdb50dfc1c3095..754e8c287c5148 100644
--- a/clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -890,7 +890,7 @@ TEST(SelectionTest, DeclContextLambda) {
   auto AST = TestTU::withCode(Test.code()).build();
   auto ST = SelectionTree::createRight(AST.getASTContext(), AST.getTokens(),
Test.point("1"), Test.point("1"));
-  EXPECT_FALSE(ST.commonAncestor()->getDeclContext().isTranslationUnit());
+  EXPECT_TRUE(ST.commonAncestor()->getDeclContext().isFunctionOrMethod());
 }
 
 } // namespace

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


[clang-tools-extra] [clangd] Handle lambda scopes inside Node::getDeclContext() (PR #76329)

2023-12-24 Thread Younan Zhang via cfe-commits

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


[clang] [llvm] Recommit [RISCV] Update the interface of sifive vqmaccqoq (#74284) (PR #75768)

2023-12-24 Thread Craig Topper via cfe-commits


@@ -553,29 +560,40 @@ class GetFTypeInfo {
 }
 
 multiclass VPatVMACC info_pairs, ValueType vec_m1> {
+ list info_pairs, ValueType vec_m1,
+ bit lmul_follows_vd = 0> {

topperc wrote:

lmul doesn't follow vd for any of these instructions. It always follows vs2, 
but one of the instructions has the same lmul for vs2 and vd.

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


[clang] [llvm] Recommit [RISCV] Update the interface of sifive vqmaccqoq (#74284) (PR #75768)

2023-12-24 Thread Craig Topper via cfe-commits

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


[clang] [llvm] Recommit [RISCV] Update the interface of sifive vqmaccqoq (#74284) (PR #75768)

2023-12-24 Thread Craig Topper via cfe-commits


@@ -349,14 +349,21 @@ multiclass VPseudoSiFiveVMACC;
 }
 
-multiclass VPseudoSiFiveVQMACC {
+multiclass VPseudoSiFiveVQMACCDOD {
   foreach m = MxListVF8 in
 let VLMul = m.value in
 defm NAME : VPseudoSiFiveVMACC;
 }
 
+multiclass VPseudoSiFiveVQMACCQOQ {
+  foreach i = [0, 1, 2, 3] in

topperc wrote:

`foreach i = 0-3 in`

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


[clang] [clang] Reword apologetic Clang diagnostic messages (PR #76310)

2023-12-24 Thread via cfe-commits


@@ -9913,11 +9913,11 @@ def warn_new_dangling_initializer_list : Warning<
   "will be destroyed at the end of the full-expression">,
   InGroup;
 def warn_unsupported_lifetime_extension : Warning<
-  "sorry, lifetime extension of "
+  "lifetime extension of "
   "%select{temporary|backing array of initializer list}0 created "
-  "by aggregate initialization using default member initializer "
+  "by aggregate initialization using a default member initializer "
   "is not supported; lifetime of %select{temporary|backing array}0 "
-  "will end at the end of the full-expression">, InGroup;
+  "will terminate at the end of the full-expression">, InGroup;

cor3ntin wrote:

end is the more correct terminology here, it is a term of art - and we should 
avoid overloading "terminate"

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


[clang] [clang] Reword apologetic Clang diagnostic messages (PR #76310)

2023-12-24 Thread via cfe-commits


@@ -5188,7 +5188,7 @@ def err_template_arg_not_object_or_func : Error<
 def err_template_arg_not_pointer_to_member_form : Error<
   "non-type template argument is not a pointer to member constant">;
 def err_template_arg_member_ptr_base_derived_not_supported : Error<
-  "sorry, non-type template argument of pointer-to-member type %1 that refers "
+  "non-type template argument of a pointer to member type %1, that refers "

cor3ntin wrote:

`pointer-to-member` is a term of art, we should keep it (and `a` is incorrect 
grammatically)

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


[llvm] [clang] Recommit [RISCV] Update the interface of sifive vqmaccqoq (#74284) (PR #75768)

2023-12-24 Thread Craig Topper via cfe-commits

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


[clang] [RISCV] Prevent checkRVVTypeSupport from issuing more than 1 diagnostic. (PR #74950)

2023-12-24 Thread Craig Topper via cfe-commits

topperc wrote:

Ping

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


[clang] [RISCV] Refactor checkRVVTypeSupport to use BuiltinVectorTypeInfo. (PR #74949)

2023-12-24 Thread Craig Topper via cfe-commits

topperc wrote:

Ping

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


[clang-tools-extra] [clang-tidy] introduce a unused local non trival variable check (PR #76101)

2023-12-24 Thread Tyler Rockwood via cfe-commits

https://github.com/rockwotj updated 
https://github.com/llvm/llvm-project/pull/76101

>From cf118a475b8dfef36c365c417c9cf63b79ff4055 Mon Sep 17 00:00:00 2001
From: Tyler Rockwood 
Date: Thu, 21 Dec 2023 16:31:12 -0600
Subject: [PATCH 1/2] clang-tidy/bugprone: introduce
 unused-local-non-trivial-variable check

Signed-off-by: Tyler Rockwood 
---
 .../bugprone/BugproneTidyModule.cpp   |  3 +
 .../clang-tidy/bugprone/CMakeLists.txt|  1 +
 .../UnusedLocalNonTrivialVariableCheck.cpp| 88 +++
 .../UnusedLocalNonTrivialVariableCheck.h  | 44 ++
 clang-tools-extra/docs/ReleaseNotes.rst   |  5 ++
 .../unused-local-non-trivial-variable.rst | 56 
 .../docs/clang-tidy/checks/list.rst   |  1 +
 .../unused-local-non-trivial-variable.cpp | 87 ++
 8 files changed, 285 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-local-non-trivial-variable.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-local-non-trivial-variable.cpp

diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index 7a910037368c83..435cb1e3fbcff3 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -83,6 +83,7 @@
 #include "UnhandledSelfAssignmentCheck.h"
 #include "UniquePtrArrayMismatchCheck.h"
 #include "UnsafeFunctionsCheck.h"
+#include "UnusedLocalNonTrivialVariableCheck.h"
 #include "UnusedRaiiCheck.h"
 #include "UnusedReturnValueCheck.h"
 #include "UseAfterMoveCheck.h"
@@ -235,6 +236,8 @@ class BugproneModule : public ClangTidyModule {
 "bugprone-unique-ptr-array-mismatch");
 CheckFactories.registerCheck(
 "bugprone-unsafe-functions");
+CheckFactories.registerCheck(
+"bugprone-unused-local-non-trivial-variable");
 CheckFactories.registerCheck("bugprone-unused-raii");
 CheckFactories.registerCheck(
 "bugprone-unused-return-value");
diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
index d443fd8d1452f1..70e7fbc7ec0c14 100644
--- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
@@ -79,6 +79,7 @@ add_clang_library(clangTidyBugproneModule
   UnhandledSelfAssignmentCheck.cpp
   UniquePtrArrayMismatchCheck.cpp
   UnsafeFunctionsCheck.cpp
+  UnusedLocalNonTrivialVariableCheck.cpp
   UnusedRaiiCheck.cpp
   UnusedReturnValueCheck.cpp
   UseAfterMoveCheck.cpp
diff --git 
a/clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.cpp
new file mode 100644
index 00..2d82c46a92ac12
--- /dev/null
+++ 
b/clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.cpp
@@ -0,0 +1,88 @@
+//===--- UnusedLocalNonTrivialVariableCheck.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 "UnusedLocalNonTrivialVariableCheck.h"
+#include "../utils/Matchers.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersMacros.h"
+
+using namespace clang::ast_matchers;
+using namespace clang::tidy::matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+static constexpr StringRef DefaultIncludeTypeRegex =
+"::std::.*mutex;::std::future;::std::basic_string;::std::basic_regex;"
+"::std::base_istringstream;::std::base_stringstream;::std::bitset;"
+"::std::path";
+
+AST_MATCHER(VarDecl, isLocalVarDecl) { return Node.isLocalVarDecl(); }
+AST_MATCHER(VarDecl, isReferenced) { return Node.isReferenced(); }
+AST_MATCHER(Type, isReferenceType) { return Node.isReferenceType(); }
+AST_MATCHER(QualType, isTrivial) {
+  return Node.isTrivialType(Finder->getASTContext()) ||
+ Node.isTriviallyCopyableType(Finder->getASTContext());
+}
+} // namespace
+
+UnusedLocalNonTrivialVariableCheck::UnusedLocalNonTrivialVariableCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  IncludeTypes(utils::options::parseStringList(
+  Options.get("IncludeTypes", DefaultIncludeTypeRegex))),
+  ExcludeTypes(

[clang-tools-extra] [clang-tidy] introduce a unused local non trival variable check (PR #76101)

2023-12-24 Thread Tyler Rockwood via cfe-commits


@@ -0,0 +1,89 @@
+//===--- UnusedLocalNonTrivialVariableCheck.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 "UnusedLocalNonTrivialVariableCheck.h"
+#include "../utils/Matchers.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersMacros.h"
+
+using namespace clang::ast_matchers;
+using namespace clang::tidy::matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+static constexpr StringRef DefaultIncludeTypeRegex = 
"std::.*mutex;std::future";

rockwotj wrote:

Done. I didn't add `std::basic_string_view` because string_view should be a 
trivial type.

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


[llvm] [clang] Revert "InstCombine: Fold is.fpclass(x, fcInf) to fabs+fcmp" (PR #76338)

2023-12-24 Thread Yingwei Zheng via cfe-commits

https://github.com/dtcxzyw updated 
https://github.com/llvm/llvm-project/pull/76338

>From a646e872e72bab7b143db7496adfeb633b882dc4 Mon Sep 17 00:00:00 2001
From: Yingwei Zheng 
Date: Mon, 25 Dec 2023 01:39:27 +0800
Subject: [PATCH] Revert "InstCombine: Fold is.fpclass(x, fcInf) to fabs+fcmp"

This reverts commit 2b582440c16c72b6b021ea5c212ceda3bdfb2b9b.
---
 clang/test/CodeGen/isfpclass.c| 23 -
 clang/test/Headers/__clang_hip_math.hip   | 40 ++-
 .../InstCombine/InstCombineCalls.cpp  | 18 ---
 llvm/test/Transforms/InstCombine/and-fcmp.ll  |  9 ++--
 .../combine-is.fpclass-and-fcmp.ll| 26 --
 .../create-class-from-logic-fcmp.ll   | 30 ---
 .../test/Transforms/InstCombine/is_fpclass.ll | 51 ---
 7 files changed, 72 insertions(+), 125 deletions(-)

diff --git a/clang/test/CodeGen/isfpclass.c b/clang/test/CodeGen/isfpclass.c
index 34873c08e04f87..08c2633266dbd5 100644
--- a/clang/test/CodeGen/isfpclass.c
+++ b/clang/test/CodeGen/isfpclass.c
@@ -4,9 +4,8 @@
 // CHECK-LABEL: define dso_local i1 @check_isfpclass_finite
 // CHECK-SAME: (float noundef [[X:%.*]]) local_unnamed_addr #[[ATTR0:[0-9]+]] {
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = tail call float @llvm.fabs.f32(float [[X]])
-// CHECK-NEXT:[[TMP1:%.*]] = fcmp one float [[TMP0]], 0x7FF0
-// CHECK-NEXT:ret i1 [[TMP1]]
+// CHECK-NEXT:[[TMP0:%.*]] = tail call i1 @llvm.is.fpclass.f32(float 
[[X]], i32 504)
+// CHECK-NEXT:ret i1 [[TMP0]]
 //
 _Bool check_isfpclass_finite(float x) {
   return __builtin_isfpclass(x, 504 /*Finite*/);
@@ -15,7 +14,7 @@ _Bool check_isfpclass_finite(float x) {
 // CHECK-LABEL: define dso_local i1 @check_isfpclass_finite_strict
 // CHECK-SAME: (float noundef [[X:%.*]]) local_unnamed_addr #[[ATTR2:[0-9]+]] {
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = tail call i1 @llvm.is.fpclass.f32(float 
[[X]], i32 504) #[[ATTR6:[0-9]+]]
+// CHECK-NEXT:[[TMP0:%.*]] = tail call i1 @llvm.is.fpclass.f32(float 
[[X]], i32 504) #[[ATTR5:[0-9]+]]
 // CHECK-NEXT:ret i1 [[TMP0]]
 //
 _Bool check_isfpclass_finite_strict(float x) {
@@ -36,7 +35,7 @@ _Bool check_isfpclass_nan_f32(float x) {
 // CHECK-LABEL: define dso_local i1 @check_isfpclass_nan_f32_strict
 // CHECK-SAME: (float noundef [[X:%.*]]) local_unnamed_addr #[[ATTR2]] {
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = tail call i1 @llvm.is.fpclass.f32(float 
[[X]], i32 3) #[[ATTR6]]
+// CHECK-NEXT:[[TMP0:%.*]] = tail call i1 @llvm.is.fpclass.f32(float 
[[X]], i32 3) #[[ATTR5]]
 // CHECK-NEXT:ret i1 [[TMP0]]
 //
 _Bool check_isfpclass_nan_f32_strict(float x) {
@@ -57,7 +56,7 @@ _Bool check_isfpclass_snan_f64(double x) {
 // CHECK-LABEL: define dso_local i1 @check_isfpclass_snan_f64_strict
 // CHECK-SAME: (double noundef [[X:%.*]]) local_unnamed_addr #[[ATTR2]] {
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = tail call i1 @llvm.is.fpclass.f64(double 
[[X]], i32 1) #[[ATTR6]]
+// CHECK-NEXT:[[TMP0:%.*]] = tail call i1 @llvm.is.fpclass.f64(double 
[[X]], i32 1) #[[ATTR5]]
 // CHECK-NEXT:ret i1 [[TMP0]]
 //
 _Bool check_isfpclass_snan_f64_strict(double x) {
@@ -78,7 +77,7 @@ _Bool check_isfpclass_zero_f16(_Float16 x) {
 // CHECK-LABEL: define dso_local i1 @check_isfpclass_zero_f16_strict
 // CHECK-SAME: (half noundef [[X:%.*]]) local_unnamed_addr #[[ATTR2]] {
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = tail call i1 @llvm.is.fpclass.f16(half [[X]], 
i32 96) #[[ATTR6]]
+// CHECK-NEXT:[[TMP0:%.*]] = tail call i1 @llvm.is.fpclass.f16(half [[X]], 
i32 96) #[[ATTR5]]
 // CHECK-NEXT:ret i1 [[TMP0]]
 //
 _Bool check_isfpclass_zero_f16_strict(_Float16 x) {
@@ -89,7 +88,7 @@ _Bool check_isfpclass_zero_f16_strict(_Float16 x) {
 // CHECK-LABEL: define dso_local i1 @check_isnan
 // CHECK-SAME: (float noundef [[X:%.*]]) local_unnamed_addr #[[ATTR2]] {
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = tail call i1 @llvm.is.fpclass.f32(float 
[[X]], i32 3) #[[ATTR6]]
+// CHECK-NEXT:[[TMP0:%.*]] = tail call i1 @llvm.is.fpclass.f32(float 
[[X]], i32 3) #[[ATTR5]]
 // CHECK-NEXT:ret i1 [[TMP0]]
 //
 _Bool check_isnan(float x) {
@@ -100,7 +99,7 @@ _Bool check_isnan(float x) {
 // CHECK-LABEL: define dso_local i1 @check_isinf
 // CHECK-SAME: (float noundef [[X:%.*]]) local_unnamed_addr #[[ATTR2]] {
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = tail call i1 @llvm.is.fpclass.f32(float 
[[X]], i32 516) #[[ATTR6]]
+// CHECK-NEXT:[[TMP0:%.*]] = tail call i1 @llvm.is.fpclass.f32(float 
[[X]], i32 516) #[[ATTR5]]
 // CHECK-NEXT:ret i1 [[TMP0]]
 //
 _Bool check_isinf(float x) {
@@ -111,7 +110,7 @@ _Bool check_isinf(float x) {
 // CHECK-LABEL: define dso_local i1 @check_isfinite
 // CHECK-SAME: (float noundef [[X:%.*]]) local_unnamed_addr #[[ATTR2]] {
 // CHECK-NEXT:  entry:
-// CHECK-NEXT:[[TMP0:%.*]] = tail call i1 @llvm.is.fpclass.f32(float 
[[X]], i32 504) #[[ATTR

[clang-tools-extra] [clang-tidy] introduce a unused local non trival variable check (PR #76101)

2023-12-24 Thread Piotr Zegar via cfe-commits

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


[clang-tools-extra] [clang-tidy] introduce a unused local non trival variable check (PR #76101)

2023-12-24 Thread Piotr Zegar via cfe-commits

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

Overall looks fine.

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


[clang-tools-extra] [clang-tidy] introduce a unused local non trival variable check (PR #76101)

2023-12-24 Thread Piotr Zegar via cfe-commits


@@ -0,0 +1,91 @@
+// RUN: %check_clang_tidy -std=c++17 %s 
bugprone-unused-local-non-trivial-variable %t -- \

PiotrZSL wrote:

use -std=c++17-or-later

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


[clang-tools-extra] [clang-tidy] introduce a unused local non trival variable check (PR #76101)

2023-12-24 Thread Piotr Zegar via cfe-commits


@@ -0,0 +1,91 @@
+// RUN: %check_clang_tidy -std=c++17 %s 
bugprone-unused-local-non-trivial-variable %t -- \
+// RUN:   -config="{CheckOptions: 
{bugprone-unused-local-non-trivial-variable.IncludeTypes: '::async::Future'}}"

PiotrZSL wrote:

would be nice to add also ExcludeTypes and test for that.

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


[clang-tools-extra] [clang-tidy] introduce a unused local non trival variable check (PR #76101)

2023-12-24 Thread Piotr Zegar via cfe-commits


@@ -0,0 +1,92 @@
+//===--- UnusedLocalNonTrivialVariableCheck.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 "UnusedLocalNonTrivialVariableCheck.h"
+#include "../utils/Matchers.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersMacros.h"
+
+using namespace clang::ast_matchers;
+using namespace clang::tidy::matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+static constexpr StringRef DefaultIncludeTypeRegex =
+"::std::.*mutex;::std::future;::std::basic_string;::std::basic_regex;"
+"::std::base_istringstream;::std::base_stringstream;::std::bitset;"
+"::std::path";

PiotrZSL wrote:

I forget that path is in std::filesystem::path

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


[clang-tools-extra] [clang-tidy] introduce a unused local non trival variable check (PR #76101)

2023-12-24 Thread Piotr Zegar via cfe-commits


@@ -0,0 +1,92 @@
+//===--- UnusedLocalNonTrivialVariableCheck.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 "UnusedLocalNonTrivialVariableCheck.h"
+#include "../utils/Matchers.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersMacros.h"
+
+using namespace clang::ast_matchers;
+using namespace clang::tidy::matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+static constexpr StringRef DefaultIncludeTypeRegex =
+"::std::.*mutex;::std::future;::std::basic_string;::std::basic_regex;"
+"::std::base_istringstream;::std::base_stringstream;::std::bitset;"
+"::std::path";
+
+AST_MATCHER(VarDecl, isLocalVarDecl) { return Node.isLocalVarDecl(); }
+AST_MATCHER(VarDecl, isReferenced) { return Node.isReferenced(); }
+AST_MATCHER(Type, isReferenceType) { return Node.isReferenceType(); }
+AST_MATCHER(QualType, isTrivial) {
+  return Node.isTrivialType(Finder->getASTContext()) ||
+ Node.isTriviallyCopyableType(Finder->getASTContext());
+}
+} // namespace
+
+UnusedLocalNonTrivialVariableCheck::UnusedLocalNonTrivialVariableCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  IncludeTypes(utils::options::parseStringList(
+  Options.get("IncludeTypes", DefaultIncludeTypeRegex))),
+  ExcludeTypes(
+  utils::options::parseStringList(Options.get("ExcludeTypes", ""))) {}
+
+void UnusedLocalNonTrivialVariableCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IncludeTypes",
+utils::options::serializeStringList(IncludeTypes));
+  Options.store(Opts, "ExcludeTypes",
+utils::options::serializeStringList(ExcludeTypes));
+}
+
+void UnusedLocalNonTrivialVariableCheck::registerMatchers(MatchFinder *Finder) 
{
+  if (IncludeTypes.empty())
+return;
+
+  Finder->addMatcher(
+  varDecl(isLocalVarDecl(), unless(isReferenced()),
+  unless(isExpansionInSystemHeader()),

PiotrZSL wrote:

you can remove unless(isExpansionInSystemHeader()) as this should be handled in 
diffrent way for all checks in more generic way

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


[clang] [clang-format] Fix handling of C-Style variable definition of a struct (PR #76344)

2023-12-24 Thread via cfe-commits

https://github.com/XDeme created https://github.com/llvm/llvm-project/pull/76344

Fixes llvm/llvm-project#71939

The problem was happening because we were treating `struct Foo f{};` as a 
struct definition, so `{` was being treated as `TT_StructLBrace`

>From a55c720f344645bdad3838aaa39b136c8b8ee6dc Mon Sep 17 00:00:00 2001
From: XDeme 
Date: Sun, 24 Dec 2023 20:18:02 -0300
Subject: [PATCH] [clang-format] Fix handling of C-Style variable definition of
 a struct

---
 clang/lib/Format/UnwrappedLineParser.cpp  | 8 
 clang/unittests/Format/FormatTest.cpp | 1 +
 clang/unittests/Format/TokenAnnotatorTest.cpp | 6 ++
 3 files changed, 15 insertions(+)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 684609747a5513..9cacb0d175adae 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -3873,6 +3873,7 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
   const FormatToken &InitialToken = *FormatTok;
   nextToken();
 
+  int NonMacroIdentifierCount = 0;
   // The actual identifier can be a nested name specifier, and in macros
   // it is often token-pasted.
   // An [[attribute]] can be before the identifier.
@@ -3898,6 +3899,8 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
 FormatTok->is(tok::identifier) &&
 FormatTok->TokenText != FormatTok->TokenText.upper();
 nextToken();
+if (IsNonMacroIdentifier)
+  ++NonMacroIdentifierCount;
 // We can have macros in between 'class' and the class name.
 if (!IsNonMacroIdentifier && FormatTok->is(tok::l_paren))
   parseParens();
@@ -3960,6 +3963,11 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
 }
   };
   if (FormatTok->is(tok::l_brace)) {
+// Handles C-Style variable declaration of a struct
+if (Style.isCpp() && NonMacroIdentifierCount == 2) {
+  parseBracedList();
+  return;
+}
 auto [OpenBraceType, ClosingBraceType] = GetBraceTypes(InitialToken);
 FormatTok->setFinalizedType(OpenBraceType);
 if (ParseAsExpr) {
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 762fc8254bdfc9..d37d1f58b51a4a 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -14548,6 +14548,7 @@ TEST_F(FormatTest, 
UnderstandContextOfRecordTypeKeywords) {
   verifyFormat("struct foo f() {}\nint n;");
   verifyFormat("class foo f() {}\nint n;");
   verifyFormat("union foo f() {}\nint n;");
+  verifyFormat("struct MACRO foo f{};");
 
   // Templates.
   verifyFormat("template  void f() {}\nint n;");
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 2cafc0438ffb46..568574bf73a872 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -503,6 +503,12 @@ TEST_F(TokenAnnotatorTest, UnderstandsVariables) {
   annotate("inline bool var = is_integral_v && is_signed_v;");
   EXPECT_EQ(Tokens.size(), 15u) << Tokens;
   EXPECT_TOKEN(Tokens[8], tok::ampamp, TT_BinaryOperator);
+
+  Tokens = annotate("struct Foo f{};");
+  EXPECT_EQ(Tokens.size(), 7u) << Tokens;
+  EXPECT_TOKEN(Tokens[1], tok::identifier, TT_Unknown);
+  EXPECT_TOKEN(Tokens[2], tok::identifier, TT_StartOfName);
+  EXPECT_TOKEN(Tokens[3], tok::l_brace, TT_Unknown);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandsVariableTemplates) {

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


[clang] [clang-format] Fix handling of C-Style variable definition of a struct (PR #76344)

2023-12-24 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: None (XDeme)


Changes

Fixes llvm/llvm-project#71939

The problem was happening because we were treating `struct Foo f{};` as a 
struct definition, so `{` was being treated as `TT_StructLBrace`

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


3 Files Affected:

- (modified) clang/lib/Format/UnwrappedLineParser.cpp (+8) 
- (modified) clang/unittests/Format/FormatTest.cpp (+1) 
- (modified) clang/unittests/Format/TokenAnnotatorTest.cpp (+6) 


``diff
diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 684609747a5513..9cacb0d175adae 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -3873,6 +3873,7 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
   const FormatToken &InitialToken = *FormatTok;
   nextToken();
 
+  int NonMacroIdentifierCount = 0;
   // The actual identifier can be a nested name specifier, and in macros
   // it is often token-pasted.
   // An [[attribute]] can be before the identifier.
@@ -3898,6 +3899,8 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
 FormatTok->is(tok::identifier) &&
 FormatTok->TokenText != FormatTok->TokenText.upper();
 nextToken();
+if (IsNonMacroIdentifier)
+  ++NonMacroIdentifierCount;
 // We can have macros in between 'class' and the class name.
 if (!IsNonMacroIdentifier && FormatTok->is(tok::l_paren))
   parseParens();
@@ -3960,6 +3963,11 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
 }
   };
   if (FormatTok->is(tok::l_brace)) {
+// Handles C-Style variable declaration of a struct
+if (Style.isCpp() && NonMacroIdentifierCount == 2) {
+  parseBracedList();
+  return;
+}
 auto [OpenBraceType, ClosingBraceType] = GetBraceTypes(InitialToken);
 FormatTok->setFinalizedType(OpenBraceType);
 if (ParseAsExpr) {
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 762fc8254bdfc9..d37d1f58b51a4a 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -14548,6 +14548,7 @@ TEST_F(FormatTest, 
UnderstandContextOfRecordTypeKeywords) {
   verifyFormat("struct foo f() {}\nint n;");
   verifyFormat("class foo f() {}\nint n;");
   verifyFormat("union foo f() {}\nint n;");
+  verifyFormat("struct MACRO foo f{};");
 
   // Templates.
   verifyFormat("template  void f() {}\nint n;");
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 2cafc0438ffb46..568574bf73a872 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -503,6 +503,12 @@ TEST_F(TokenAnnotatorTest, UnderstandsVariables) {
   annotate("inline bool var = is_integral_v && is_signed_v;");
   EXPECT_EQ(Tokens.size(), 15u) << Tokens;
   EXPECT_TOKEN(Tokens[8], tok::ampamp, TT_BinaryOperator);
+
+  Tokens = annotate("struct Foo f{};");
+  EXPECT_EQ(Tokens.size(), 7u) << Tokens;
+  EXPECT_TOKEN(Tokens[1], tok::identifier, TT_Unknown);
+  EXPECT_TOKEN(Tokens[2], tok::identifier, TT_StartOfName);
+  EXPECT_TOKEN(Tokens[3], tok::l_brace, TT_Unknown);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandsVariableTemplates) {

``




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


[llvm] [compiler-rt] [libcxx] [clang] [mlir] [clang-tools-extra] [RegAllocFast] Lazily initialize InstrPosIndexes for each MBB (PR #76275)

2023-12-24 Thread via cfe-commits

https://github.com/HaohaiWen updated 
https://github.com/llvm/llvm-project/pull/76275

>From 23882772e4dac82b45cac2b3ea4fba12415764f6 Mon Sep 17 00:00:00 2001
From: Haohai Wen 
Date: Sat, 23 Dec 2023 09:55:37 +0800
Subject: [PATCH] [RegAllocFast] Lazily initialize InstrPosIndexes for each MBB

Most basic block do not need to query dominates. Defer initialization of
InstrPosIndexes to first query for each MBB.
---
 llvm/lib/CodeGen/RegAllocFast.cpp | 12 +++-
 1 file changed, 11 insertions(+), 1 deletion(-)

diff --git a/llvm/lib/CodeGen/RegAllocFast.cpp 
b/llvm/lib/CodeGen/RegAllocFast.cpp
index d7edaa1d7ea47d..e81d4793013682 100644
--- a/llvm/lib/CodeGen/RegAllocFast.cpp
+++ b/llvm/lib/CodeGen/RegAllocFast.cpp
@@ -66,6 +66,8 @@ namespace {
 /// can be used to determine dominance between instructions in same MBB.
 class InstrPosIndexes {
 public:
+  void unsetInitialized() { IsInitialized = false; }
+
   void init(const MachineBasicBlock &MBB) {
 CurMBB = &MBB;
 Instr2PosIndex.clear();
@@ -80,6 +82,13 @@ class InstrPosIndexes {
   /// index without affecting existing instruction's index. Return true if all
   /// instructions index has been reassigned.
   bool getIndex(const MachineInstr &MI, uint64_t &Index) {
+if (!IsInitialized) {
+  init(*MI.getParent());
+  IsInitialized = true;
+  Index = Instr2PosIndex.at(&MI);
+  return true;
+}
+
 assert(MI.getParent() == CurMBB && "MI is not in CurMBB");
 auto It = Instr2PosIndex.find(&MI);
 if (It != Instr2PosIndex.end()) {
@@ -159,6 +168,7 @@ class InstrPosIndexes {
   }
 
 private:
+  bool IsInitialized = false;
   enum { InstrDist = 1024 };
   const MachineBasicBlock *CurMBB = nullptr;
   DenseMap Instr2PosIndex;
@@ -1665,7 +1675,7 @@ void RegAllocFast::allocateBasicBlock(MachineBasicBlock 
&MBB) {
   this->MBB = &MBB;
   LLVM_DEBUG(dbgs() << "\nAllocating " << MBB);
 
-  PosIndexes.init(MBB);
+  PosIndexes.unsetInitialized();
   RegUnitStates.assign(TRI->getNumRegUnits(), regFree);
   assert(LiveVirtRegs.empty() && "Mapping not cleared from last block?");
 

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


[llvm] [compiler-rt] [libcxx] [clang] [mlir] [clang-tools-extra] [CostModel][X86] Fix fpext conversion cost for 16 elements (PR #76278)

2023-12-24 Thread via cfe-commits

https://github.com/HaohaiWen updated 
https://github.com/llvm/llvm-project/pull/76278

>From 87f3d68e82dcc752aa727f62b8b1b56b1257b343 Mon Sep 17 00:00:00 2001
From: Haohai Wen 
Date: Sat, 23 Dec 2023 13:16:02 +0800
Subject: [PATCH 1/2] [CostModel][X86] Track fpext conversion for 16 elements

---
 llvm/test/Analysis/CostModel/X86/cast.ll | 20 
 1 file changed, 12 insertions(+), 8 deletions(-)

diff --git a/llvm/test/Analysis/CostModel/X86/cast.ll 
b/llvm/test/Analysis/CostModel/X86/cast.ll
index 5a83d4e81fd38e..e0173e9df4dc3b 100644
--- a/llvm/test/Analysis/CostModel/X86/cast.ll
+++ b/llvm/test/Analysis/CostModel/X86/cast.ll
@@ -616,27 +616,31 @@ define void @fp_conv(<8 x float> %a, <16 x float>%b, <4 x 
float> %c) {
 ; SSE-LABEL: 'fp_conv'
 ; SSE-NEXT:  Cost Model: Found an estimated cost of 3 for instruction: %A1 = 
fpext <4 x float> %c to <4 x double>
 ; SSE-NEXT:  Cost Model: Found an estimated cost of 6 for instruction: %A2 = 
fpext <8 x float> %a to <8 x double>
-; SSE-NEXT:  Cost Model: Found an estimated cost of 3 for instruction: %A3 = 
fptrunc <4 x double> undef to <4 x float>
-; SSE-NEXT:  Cost Model: Found an estimated cost of 6 for instruction: %A4 = 
fptrunc <8 x double> undef to <8 x float>
+; SSE-NEXT:  Cost Model: Found an estimated cost of 12 for instruction: %A3 = 
fpext <16 x float> %b to <16 x double>
+; SSE-NEXT:  Cost Model: Found an estimated cost of 3 for instruction: %A4 = 
fptrunc <4 x double> undef to <4 x float>
+; SSE-NEXT:  Cost Model: Found an estimated cost of 6 for instruction: %A5 = 
fptrunc <8 x double> undef to <8 x float>
 ; SSE-NEXT:  Cost Model: Found an estimated cost of 0 for instruction: ret void
 ;
 ; AVX-LABEL: 'fp_conv'
 ; AVX-NEXT:  Cost Model: Found an estimated cost of 1 for instruction: %A1 = 
fpext <4 x float> %c to <4 x double>
 ; AVX-NEXT:  Cost Model: Found an estimated cost of 3 for instruction: %A2 = 
fpext <8 x float> %a to <8 x double>
-; AVX-NEXT:  Cost Model: Found an estimated cost of 1 for instruction: %A3 = 
fptrunc <4 x double> undef to <4 x float>
-; AVX-NEXT:  Cost Model: Found an estimated cost of 3 for instruction: %A4 = 
fptrunc <8 x double> undef to <8 x float>
+; AVX-NEXT:  Cost Model: Found an estimated cost of 6 for instruction: %A3 = 
fpext <16 x float> %b to <16 x double>
+; AVX-NEXT:  Cost Model: Found an estimated cost of 1 for instruction: %A4 = 
fptrunc <4 x double> undef to <4 x float>
+; AVX-NEXT:  Cost Model: Found an estimated cost of 3 for instruction: %A5 = 
fptrunc <8 x double> undef to <8 x float>
 ; AVX-NEXT:  Cost Model: Found an estimated cost of 0 for instruction: ret void
 ;
 ; AVX512-LABEL: 'fp_conv'
 ; AVX512-NEXT:  Cost Model: Found an estimated cost of 1 for instruction: %A1 
= fpext <4 x float> %c to <4 x double>
 ; AVX512-NEXT:  Cost Model: Found an estimated cost of 1 for instruction: %A2 
= fpext <8 x float> %a to <8 x double>
-; AVX512-NEXT:  Cost Model: Found an estimated cost of 1 for instruction: %A3 
= fptrunc <4 x double> undef to <4 x float>
-; AVX512-NEXT:  Cost Model: Found an estimated cost of 1 for instruction: %A4 
= fptrunc <8 x double> undef to <8 x float>
+; AVX512-NEXT:  Cost Model: Found an estimated cost of 6 for instruction: %A3 
= fpext <16 x float> %b to <16 x double>
+; AVX512-NEXT:  Cost Model: Found an estimated cost of 1 for instruction: %A4 
= fptrunc <4 x double> undef to <4 x float>
+; AVX512-NEXT:  Cost Model: Found an estimated cost of 1 for instruction: %A5 
= fptrunc <8 x double> undef to <8 x float>
 ; AVX512-NEXT:  Cost Model: Found an estimated cost of 0 for instruction: ret 
void
 ;
   %A1 = fpext <4 x float> %c to <4 x double>
   %A2 = fpext <8 x float> %a to <8 x double>
-  %A3 = fptrunc <4 x double> undef to <4 x float>
-  %A4 = fptrunc <8 x double> undef to <8 x float>
+  %A3 = fpext <16 x float> %b to <16 x double>
+  %A4 = fptrunc <4 x double> undef to <4 x float>
+  %A5 = fptrunc <8 x double> undef to <8 x float>
   ret void
 }

>From 90c9efc967dd02a37ebf2abf0c771011ae670dea Mon Sep 17 00:00:00 2001
From: Haohai Wen 
Date: Sat, 23 Dec 2023 13:28:10 +0800
Subject: [PATCH 2/2] [CostModel][X86] Fix fpext conversion cost for 16
 elements

The fpext conversion cost for 16 elements should be 5.
---
 llvm/lib/Target/X86/X86TargetTransformInfo.cpp | 1 +
 llvm/test/Analysis/CostModel/X86/cast.ll   | 2 +-
 2 files changed, 2 insertions(+), 1 deletion(-)

diff --git a/llvm/lib/Target/X86/X86TargetTransformInfo.cpp 
b/llvm/lib/Target/X86/X86TargetTransformInfo.cpp
index 8a04987e768a12..e7b7c9666ed43c 100644
--- a/llvm/lib/Target/X86/X86TargetTransformInfo.cpp
+++ b/llvm/lib/Target/X86/X86TargetTransformInfo.cpp
@@ -2223,6 +2223,7 @@ InstructionCost X86TTIImpl::getCastInstrCost(unsigned 
Opcode, Type *Dst,
   static const TypeConversionCostTblEntry AVX512FConversionTbl[] = {
 { ISD::FP_EXTEND, MVT::v8f64,   MVT::v8f32,  1 },
 { ISD::FP_EXTEND, MVT::v8f64,   MVT::v16f32, 3 },
+{ ISD::FP_EXTEND, MVT::v16f64,  MVT::v16f32, 5 }, // 
2*vcvtps2pd+ve

[llvm] [clang-tools-extra] [compiler-rt] [mlir] [clang] [libcxx] [CostModel][X86] Fix fpext conversion cost for 16 elements (PR #76278)

2023-12-24 Thread via cfe-commits

HaohaiWen wrote:

> Please can you confirm this as llvm-mca predicts worse case (znver4) to be 4 
> https://llvm.godbolt.org/z/fxWTaf3Gv

Currenttly, uiCA don't support Zen4 and I don't have Zen4 machine.
I can measure it on local SKX machine with nanoBench 
(https://github.com/andreas-abel/nanoBench). Maybe you can use it to confirm 
Zen4 cost if you do have Zen4 machine. 
e.g.
```
./nanoBench.sh -init "xor zmm0, zmm0" -asm "vcvtps2pd zmm2, ymm0; vextractf64x4 
ymm0, zmm0, 1; vcvtps2pd zmm1, ymm0" -config configs/cfg_SkylakeX_common.txt 
-unroll 1000 -loop 1000 -warm_up_count 10 -cpu 0
Note: Hyper-threading is enabled; it can be disabled with "sudo ./disable-HT.sh"
CORE_CYCLES: 4.77
INST_RETIRED: 3.00
IDQ.MITE_UOPS: 5.71
IDQ.DSB_UOPS: -0.70
IDQ.MS_UOPS: 0.01
LSD.UOPS: 0.00
UOPS_ISSUED: 5.01
UOPS_EXECUTED: 5.01
UOPS_RETIRED.RETIRE_SLOTS: 5.01
UOPS_DISPATCHED_PORT.PORT_0: 2.00
UOPS_DISPATCHED_PORT.PORT_1: 0.00
UOPS_DISPATCHED_PORT.PORT_2: 0.00
UOPS_DISPATCHED_PORT.PORT_3: 0.00
UOPS_DISPATCHED_PORT.PORT_4: 0.00
UOPS_DISPATCHED_PORT.PORT_5: 3.00
UOPS_DISPATCHED_PORT.PORT_6: 0.00
UOPS_DISPATCHED_PORT.PORT_7: 0.00

```

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


[compiler-rt] [clang-tools-extra] [clang] [libcxx] [mlir] [llvm] [RegAllocFast] Lazily initialize InstrPosIndexes for each MBB (PR #76275)

2023-12-24 Thread via cfe-commits

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


[clang] [clang][driver] Fix unused var warnings in if statements (PR #76346)

2023-12-24 Thread Max Winkler via cfe-commits

https://github.com/MaxEW707 created 
https://github.com/llvm/llvm-project/pull/76346

None

>From e95623f3e0b89d2499ffe19a4d36eabef9ffa2d4 Mon Sep 17 00:00:00 2001
From: MaxEW707 <82551778+maxew...@users.noreply.github.com>
Date: Sun, 24 Dec 2023 20:53:19 -0500
Subject: [PATCH] Fix unused var warnings in clang driver

---
 clang/lib/Driver/ToolChains/Clang.cpp | 8 
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 4783affd3220bc..a76bd9d9881a2e 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -3203,13 +3203,13 @@ static void RenderFloatingPointOptions(const ToolChain 
&TC, const Driver &D,
options::OPT_fstrict_float_cast_overflow, false))
 CmdArgs.push_back("-fno-strict-float-cast-overflow");
 
-  if (const Arg *A = Args.getLastArg(options::OPT_fcx_limited_range))
+  if (Args.getLastArg(options::OPT_fcx_limited_range))
 CmdArgs.push_back("-fcx-limited-range");
-  if (const Arg *A = Args.getLastArg(options::OPT_fcx_fortran_rules))
+  if (Args.getLastArg(options::OPT_fcx_fortran_rules))
 CmdArgs.push_back("-fcx-fortran-rules");
-  if (const Arg *A = Args.getLastArg(options::OPT_fno_cx_limited_range))
+  if (Args.getLastArg(options::OPT_fno_cx_limited_range))
 CmdArgs.push_back("-fno-cx-limited-range");
-  if (const Arg *A = Args.getLastArg(options::OPT_fno_cx_fortran_rules))
+  if (Args.getLastArg(options::OPT_fno_cx_fortran_rules))
 CmdArgs.push_back("-fno-cx-fortran-rules");
 }
 

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


[clang] [clang][driver] Fix unused var warnings in if statements (PR #76346)

2023-12-24 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Max Winkler (MaxEW707)


Changes



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


1 Files Affected:

- (modified) clang/lib/Driver/ToolChains/Clang.cpp (+4-4) 


``diff
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 4783affd3220bc..a76bd9d9881a2e 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -3203,13 +3203,13 @@ static void RenderFloatingPointOptions(const ToolChain 
&TC, const Driver &D,
options::OPT_fstrict_float_cast_overflow, false))
 CmdArgs.push_back("-fno-strict-float-cast-overflow");
 
-  if (const Arg *A = Args.getLastArg(options::OPT_fcx_limited_range))
+  if (Args.getLastArg(options::OPT_fcx_limited_range))
 CmdArgs.push_back("-fcx-limited-range");
-  if (const Arg *A = Args.getLastArg(options::OPT_fcx_fortran_rules))
+  if (Args.getLastArg(options::OPT_fcx_fortran_rules))
 CmdArgs.push_back("-fcx-fortran-rules");
-  if (const Arg *A = Args.getLastArg(options::OPT_fno_cx_limited_range))
+  if (Args.getLastArg(options::OPT_fno_cx_limited_range))
 CmdArgs.push_back("-fno-cx-limited-range");
-  if (const Arg *A = Args.getLastArg(options::OPT_fno_cx_fortran_rules))
+  if (Args.getLastArg(options::OPT_fno_cx_fortran_rules))
 CmdArgs.push_back("-fno-cx-fortran-rules");
 }
 

``




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


[clang] [clang][driver] Fix unused var warnings in if statements (PR #76346)

2023-12-24 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-driver

Author: Max Winkler (MaxEW707)


Changes



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


1 Files Affected:

- (modified) clang/lib/Driver/ToolChains/Clang.cpp (+4-4) 


``diff
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 4783affd3220bc..a76bd9d9881a2e 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -3203,13 +3203,13 @@ static void RenderFloatingPointOptions(const ToolChain 
&TC, const Driver &D,
options::OPT_fstrict_float_cast_overflow, false))
 CmdArgs.push_back("-fno-strict-float-cast-overflow");
 
-  if (const Arg *A = Args.getLastArg(options::OPT_fcx_limited_range))
+  if (Args.getLastArg(options::OPT_fcx_limited_range))
 CmdArgs.push_back("-fcx-limited-range");
-  if (const Arg *A = Args.getLastArg(options::OPT_fcx_fortran_rules))
+  if (Args.getLastArg(options::OPT_fcx_fortran_rules))
 CmdArgs.push_back("-fcx-fortran-rules");
-  if (const Arg *A = Args.getLastArg(options::OPT_fno_cx_limited_range))
+  if (Args.getLastArg(options::OPT_fno_cx_limited_range))
 CmdArgs.push_back("-fno-cx-limited-range");
-  if (const Arg *A = Args.getLastArg(options::OPT_fno_cx_fortran_rules))
+  if (Args.getLastArg(options::OPT_fno_cx_fortran_rules))
 CmdArgs.push_back("-fno-cx-fortran-rules");
 }
 

``




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


[clang] [Clang] Implement the 'counted_by' attribute (PR #76348)

2023-12-24 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Bill Wendling (bwendling)


Changes

The 'counted_by' attribute is used on flexible array members. The
argument for the attribute is the name of the field member holding the
count of elements in the flexible array. This information is used to
improve the results of the array bound sanitizer and the
'__builtin_dynamic_object_size' builtin. The 'count' field member must
be within the same non-anonymous, enclosing struct as the flexible array
member. For example:

  struct bar;
  struct foo {
int count;
struct inner {
  struct {
int count; /* The 'count' referenced by 'counted_by' */
  };
  struct {
/* ... */
struct bar *array[] __attribute__((counted_by(count)));
  };
} baz;
  };

This example specifies that the flexible array member 'array' has the
number of elements allocated for it in 'count':

  struct bar;
  struct foo {
size_t count;
 /* ... */
struct bar *array[] __attribute__((counted_by(count)));
  };

This establishes a relationship between 'array' and 'count';
specifically that 'p->array' must have *at least* 'p->count' number of
elements available. It's the user's responsibility to ensure that this
relationship is maintained throughout changes to the structure.

In the following, the allocated array erroneously has fewer elements
than what's specified by 'p->count'. This would result in an
out-of-bounds access not not being detected:

  struct foo *p;

  void foo_alloc(size_t count) {
p = malloc(MAX(sizeof(struct foo),
   offsetof(struct foo, array[0]) + count *
   sizeof(struct bar *)));
p->count = count + 42;
  }

The next example updates 'p->count', breaking the relationship
requirement that 'p->array' must have at least 'p->count' number of
elements available:

  void use_foo(int index, int val) {
p->count += 42;
p->array[index] = val; /* The sanitizer can't properly check this access 
*/
  }

In this example, an update to 'p->count' maintains the relationship
requirement:

  void use_foo(int index, int val) {
if (p->count == 0)
  return;
--p->count;
p->array[index] = val;
  }

---

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


20 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+5) 
- (modified) clang/include/clang/AST/DeclBase.h (+10) 
- (modified) clang/include/clang/Basic/Attr.td (+18) 
- (modified) clang/include/clang/Basic/AttrDocs.td (+78) 
- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+13) 
- (modified) clang/include/clang/Sema/Sema.h (+3) 
- (modified) clang/include/clang/Sema/TypoCorrection.h (+8-4) 
- (modified) clang/lib/AST/ASTImporter.cpp (+13) 
- (modified) clang/lib/AST/DeclBase.cpp (+73-1) 
- (modified) clang/lib/AST/Expr.cpp (+10-73) 
- (modified) clang/lib/CodeGen/CGBuiltin.cpp (+191) 
- (modified) clang/lib/CodeGen/CGExpr.cpp (+345-6) 
- (modified) clang/lib/CodeGen/CodeGenFunction.h (+21) 
- (modified) clang/lib/Sema/SemaDecl.cpp (+6) 
- (modified) clang/lib/Sema/SemaDeclAttr.cpp (+133) 
- (modified) clang/lib/Sema/SemaExpr.cpp (+9-7) 
- (added) clang/test/CodeGen/attr-counted-by.c (+1815) 
- (modified) clang/test/CodeGen/bounds-checking.c (+9-1) 
- (modified) clang/test/Misc/pragma-attribute-supported-attributes-list.test 
(+1) 
- (added) clang/test/Sema/attr-counted-by.c (+64) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ee211c16a48ac8..cfd89e32c3d0b9 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -202,6 +202,11 @@ C Language Changes
 - Enums will now be represented in TBAA metadata using their actual underlying
   integer type. Previously they were treated as chars, which meant they could
   alias with all other types.
+- Clang now supports the C-only attribute ``counted_by``. When applied to a
+  struct's flexible array member, it points to the struct field that holds the
+  number of elements in the flexible array member. This information can improve
+  the results of the array bound sanitizer and the
+  ``__builtin_dynamic_object_size`` builtin.
 
 C23 Feature Support
 ^^^
diff --git a/clang/include/clang/AST/DeclBase.h 
b/clang/include/clang/AST/DeclBase.h
index 10dcbdb262d84e..5b1038582bc674 100644
--- a/clang/include/clang/AST/DeclBase.h
+++ b/clang/include/clang/AST/DeclBase.h
@@ -19,6 +19,7 @@
 #include "clang/AST/SelectorLocationsKind.h"
 #include "clang/Basic/IdentifierTable.h"
 #include "clang/Basic/LLVM.h"
+#include "clang/Basic/LangOptions.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/Specifiers.h"
 #include "llvm/ADT/ArrayRef.h"
@@ -488,6 +489,15 @@ class alignas(8) Decl {
   // Return true if this is a FileContext Decl.
   bool isFileContextDecl() const;
 
+  /// Whether it resembles a flexible array member. This is a static member
+  /// because we want

[clang] 9b99a30 - [clang][ASTImporter] skip TemplateTypeParmDecl in VisitTypeAliasTemplateDecl (#74919)

2023-12-24 Thread via cfe-commits

Author: Qizhi Hu
Date: 2023-12-25T10:13:35+08:00
New Revision: 9b99a307b225d0db071a5cc68cbe4f5a0534e724

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

LOG: [clang][ASTImporter] skip TemplateTypeParmDecl in 
VisitTypeAliasTemplateDecl (#74919)

Skip checking `TemplateTypeParmDecl ` in `VisitTypeAliasTemplateDecl`.
[Fix this crash](https://github.com/llvm/llvm-project/issues/74765)

Co-authored-by: huqizhi <836744...@qq.com>

Added: 


Modified: 
clang/lib/AST/ASTImporter.cpp
clang/lib/AST/ASTStructuralEquivalence.cpp
clang/unittests/AST/ASTImporterTest.cpp

Removed: 




diff  --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 949310856562cd..b61180c4f3491d 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -2771,9 +2771,11 @@ 
ASTNodeImporter::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
 for (auto *FoundDecl : FoundDecls) {
   if (!FoundDecl->isInIdentifierNamespace(IDNS))
 continue;
-  if (auto *FoundAlias = dyn_cast(FoundDecl))
-return Importer.MapImported(D, FoundAlias);
-  ConflictingDecls.push_back(FoundDecl);
+  if (auto *FoundAlias = dyn_cast(FoundDecl)) {
+if (IsStructuralMatch(D, FoundAlias))
+  return Importer.MapImported(D, FoundAlias);
+ConflictingDecls.push_back(FoundDecl);
+  }
 }
 
 if (!ConflictingDecls.empty()) {
@@ -9402,7 +9404,6 @@ Expected ASTImporter::Import(Decl *FromD) {
 setImportDeclError(FromD, *Error);
 return make_error(*Error);
   }
-
   // Make sure that ImportImpl registered the imported decl.
   assert(ImportedDecls.count(FromD) != 0 && "Missing call to MapImported?");
   if (auto Error = ImportAttrs(ToD, FromD))

diff  --git a/clang/lib/AST/ASTStructuralEquivalence.cpp 
b/clang/lib/AST/ASTStructuralEquivalence.cpp
index 6bb4bf14b873d7..1f492b051e0341 100644
--- a/clang/lib/AST/ASTStructuralEquivalence.cpp
+++ b/clang/lib/AST/ASTStructuralEquivalence.cpp
@@ -1977,6 +1977,18 @@ static bool 
IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
   D2->getTemplatedDecl()->getType());
 }
 
+static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
+ TypeAliasTemplateDecl *D1,
+ TypeAliasTemplateDecl *D2) {
+  // Check template parameters.
+  if (!IsTemplateDeclCommonStructurallyEquivalent(Context, D1, D2))
+return false;
+
+  // Check the templated declaration.
+  return IsStructurallyEquivalent(Context, D1->getTemplatedDecl(),
+  D2->getTemplatedDecl());
+}
+
 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
  ConceptDecl *D1,
  ConceptDecl *D2) {

diff  --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index 6c7b2b64ca2d1d..ed8ecb080e268d 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -9295,6 +9295,53 @@ TEST_P(ASTImporterOptionSpecificTestBase,
   // EXPECT_EQ(ToF1Imported->getPreviousDecl(), ToF1);
 }
 
+TEST_P(ASTImporterOptionSpecificTestBase,
+   ImportTypeAliasTemplateAfterSimilarCalledTemplateTypeParm) {
+  const char *Code =
+  R"(
+  struct S;
+  template 
+  using Callable = S;
+  template 
+  int bindingFunctionVTable;
+  )";
+  Decl *FromTU = getTuDecl(Code, Lang_CXX17);
+
+  auto *FromCallable = FirstDeclMatcher().match(
+  FromTU, typeAliasTemplateDecl(hasName("Callable")));
+
+  auto *FromCallableParm = FirstDeclMatcher().match(
+  FromTU, templateTypeParmDecl(hasName("Callable")));
+
+  auto *ToFromCallableParm = Import(FromCallableParm, Lang_CXX17);
+  auto *ToCallable = Import(FromCallable, Lang_CXX17);
+  EXPECT_TRUE(ToFromCallableParm);
+  EXPECT_TRUE(ToCallable);
+}
+
+TEST_P(ASTImporterOptionSpecificTestBase, ImportConflictTypeAliasTemplate) {
+  const char *ToCode =
+  R"(
+  struct S;
+  template 
+  using Callable = S;
+  )";
+  const char *Code =
+  R"(
+  struct S;
+  template 
+  using Callable = S;
+  )";
+  (void)getToTuDecl(ToCode, Lang_CXX17);
+  Decl *FromTU = getTuDecl(Code, Lang_CXX17);
+
+  auto *FromCallable = FirstDeclMatcher().match(
+  FromTU, typeAliasTemplateDecl(hasName("Callable")));
+
+  auto *ImportedCallable = Import(FromCallable, Lang_CXX17);
+  EXPECT_FALSE(ImportedCallable);
+}
+
 INSTANTIATE_TEST_SUITE_P(ParameterizedTests, ASTImporterLookupTableTest,
  DefaultTestValuesForRunOptions);
 



___
cfe-commits mailing list
cfe-commit

[clang] [clang][ASTImporter] skip TemplateTypeParmDecl in VisitTypeAliasTemplateDecl (PR #74919)

2023-12-24 Thread Qizhi Hu via cfe-commits

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


[clang] 81ae2a8 - [clang] Fix '-Wunused-variable' warnings. NFC

2023-12-24 Thread Michael Liao via cfe-commits

Author: Michael Liao
Date: 2023-12-24T22:00:57-05:00
New Revision: 81ae2a8bb01d38162e0269fc6819584af6d60b03

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

LOG: [clang] Fix '-Wunused-variable' warnings. NFC

Added: 


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

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 4783affd3220bc..70dc7e54aca125 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -3203,13 +3203,13 @@ static void RenderFloatingPointOptions(const ToolChain 
&TC, const Driver &D,
options::OPT_fstrict_float_cast_overflow, false))
 CmdArgs.push_back("-fno-strict-float-cast-overflow");
 
-  if (const Arg *A = Args.getLastArg(options::OPT_fcx_limited_range))
+  if (Args.hasArg(options::OPT_fcx_limited_range))
 CmdArgs.push_back("-fcx-limited-range");
-  if (const Arg *A = Args.getLastArg(options::OPT_fcx_fortran_rules))
+  if (Args.hasArg(options::OPT_fcx_fortran_rules))
 CmdArgs.push_back("-fcx-fortran-rules");
-  if (const Arg *A = Args.getLastArg(options::OPT_fno_cx_limited_range))
+  if (Args.hasArg(options::OPT_fno_cx_limited_range))
 CmdArgs.push_back("-fno-cx-limited-range");
-  if (const Arg *A = Args.getLastArg(options::OPT_fno_cx_fortran_rules))
+  if (Args.hasArg(options::OPT_fno_cx_fortran_rules))
 CmdArgs.push_back("-fno-cx-fortran-rules");
 }
 



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


[clang-tools-extra] [clang] Fixed clang-tidy rewriter not properly handling symlinks (PR #76350)

2023-12-24 Thread Félix-Antoine Constantin via cfe-commits

https://github.com/felix642 created 
https://github.com/llvm/llvm-project/pull/76350

Rewriter would not properly fix files if they were symlinked and using --fix 
with clang-tidy would overwrite the symlink with the corrections rather than 
the file.

With these changes the Rewriter now properly resolves the symlink before 
applying the fixes.

Fixes #60845

From 37bde4bedaa6a80fb5c855a06d790cb0180fa5bd Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?F=C3=A9lix-Antoine=20Constantin?=
 
Date: Sun, 24 Dec 2023 21:01:32 -0500
Subject: [PATCH] Fixed clang-tidy rewriter not properly handling symlinks

Rewriter would not properly fix files if they were symlinked and using
--fix with clang-tidy would overwrite the symlink with the corrections
rather than the file.

With these changes the Rewriter now properly resolves the symlink before
applying the fixes.

Fixes #60845
---
 clang-tools-extra/docs/ReleaseNotes.rst   |  2 ++
 clang/lib/Rewrite/Rewriter.cpp| 24 +-
 clang/unittests/libclang/LibclangTest.cpp | 25 +++
 3 files changed, 41 insertions(+), 10 deletions(-)

diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 6d91748e4cef18..8a16ce1a7988a2 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -119,6 +119,8 @@ Improvements to clang-tidy
 
 - Improved `--dump-config` to print check options in alphabetical order.
 
+- Improved `--fix` to properly apply corrections on files that are symlinked.
+
 - Improved :program:`clang-tidy-diff.py` script. It now returns exit code `1`
   if any :program:`clang-tidy` subprocess exits with a non-zero code or if
   exporting fixes fails. It now accepts a directory as a value for
diff --git a/clang/lib/Rewrite/Rewriter.cpp b/clang/lib/Rewrite/Rewriter.cpp
index 0e6ae365064463..edc147ec304801 100644
--- a/clang/lib/Rewrite/Rewriter.cpp
+++ b/clang/lib/Rewrite/Rewriter.cpp
@@ -14,6 +14,7 @@
 #include "clang/Rewrite/Core/Rewriter.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/DiagnosticIDs.h"
+#include "clang/Basic/FileEntry.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Lex/Lexer.h"
@@ -412,16 +413,19 @@ bool Rewriter::overwriteChangedFiles() {
   unsigned OverwriteFailure = Diag.getCustomDiagID(
   DiagnosticsEngine::Error, "unable to overwrite file %0: %1");
   for (buffer_iterator I = buffer_begin(), E = buffer_end(); I != E; ++I) {
-OptionalFileEntryRef Entry = getSourceMgr().getFileEntryRefForID(I->first);
-llvm::SmallString<128> Path(Entry->getName());
-getSourceMgr().getFileManager().makeAbsolutePath(Path);
-if (auto Error = llvm::writeToOutput(Path, [&](llvm::raw_ostream &OS) {
-  I->second.write(OS);
-  return llvm::Error::success();
-})) {
-  Diag.Report(OverwriteFailure)
-  << Entry->getName() << llvm::toString(std::move(Error));
-  AllWritten = false;
+if (OptionalFileEntryRef fileEntry =
+getSourceMgr().getFileEntryRefForID(I->first)) {
+  llvm::StringRef FileName =
+  getSourceMgr().getFileManager().getCanonicalName(*fileEntry);
+  if (auto Error =
+  llvm::writeToOutput(FileName, [&](llvm::raw_ostream &OS) {
+I->second.write(OS);
+return llvm::Error::success();
+  })) {
+Diag.Report(OverwriteFailure)
+<< FileName << llvm::toString(std::move(Error));
+AllWritten = false;
+  }
 }
   }
   return !AllWritten;
diff --git a/clang/unittests/libclang/LibclangTest.cpp 
b/clang/unittests/libclang/LibclangTest.cpp
index 87075a46d75187..cde19d9004cd81 100644
--- a/clang/unittests/libclang/LibclangTest.cpp
+++ b/clang/unittests/libclang/LibclangTest.cpp
@@ -16,6 +16,7 @@
 #include "llvm/Support/raw_ostream.h"
 #include "gtest/gtest.h"
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -1379,3 +1380,27 @@ TEST_F(LibclangRewriteTest, RewriteRemove) {
   ASSERT_EQ(clang_CXRewriter_overwriteChangedFiles(Rew), 0);
   EXPECT_EQ(getFileContent(Filename), "int () { return 0; }");
 }
+
+TEST_F(LibclangRewriteTest, Symlink) {
+  std::filesystem::path Symlink = "link.cpp";
+  std::filesystem::create_symlink(Filename, Symlink);
+  ASSERT_TRUE(std::filesystem::exists(Symlink));
+  FilesAndDirsToRemove.emplace(Symlink);
+
+  CXTranslationUnit SymTu = clang_parseTranslationUnit(
+  Index, Symlink.c_str(), nullptr, 0, nullptr, 0, TUFlags);
+  CXFile SymlinkFile = clang_getFile(SymTu, Symlink.c_str());
+  CXRewriter SymRew = clang_CXRewriter_create(SymTu);
+
+  CXSourceLocation B = clang_getLocation(SymTu, SymlinkFile, 1, 5);
+  CXSourceLocation E = clang_getLocation(SymTu, SymlinkFile, 1, 9);
+  CXSourceRange Rng = clang_getRange(B, E);
+
+  clang_CXRewriter_removeText(SymRew, Rng);
+
+  ASSERT_EQ(clang_CXRewriter_overwriteChangedFiles(SymRew), 0);
+  EXPECT_EQ(getFileContent(Filename), "i

[clang-tools-extra] [clang] Fixed clang-tidy rewriter not properly handling symlinks (PR #76350)

2023-12-24 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Félix-Antoine Constantin (felix642)


Changes

Rewriter would not properly fix files if they were symlinked and using --fix 
with clang-tidy would overwrite the symlink with the corrections rather than 
the file.

With these changes the Rewriter now properly resolves the symlink before 
applying the fixes.

Fixes #60845

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


3 Files Affected:

- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+2) 
- (modified) clang/lib/Rewrite/Rewriter.cpp (+14-10) 
- (modified) clang/unittests/libclang/LibclangTest.cpp (+25) 


``diff
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 6d91748e4cef18..8a16ce1a7988a2 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -119,6 +119,8 @@ Improvements to clang-tidy
 
 - Improved `--dump-config` to print check options in alphabetical order.
 
+- Improved `--fix` to properly apply corrections on files that are symlinked.
+
 - Improved :program:`clang-tidy-diff.py` script. It now returns exit code `1`
   if any :program:`clang-tidy` subprocess exits with a non-zero code or if
   exporting fixes fails. It now accepts a directory as a value for
diff --git a/clang/lib/Rewrite/Rewriter.cpp b/clang/lib/Rewrite/Rewriter.cpp
index 0e6ae365064463..edc147ec304801 100644
--- a/clang/lib/Rewrite/Rewriter.cpp
+++ b/clang/lib/Rewrite/Rewriter.cpp
@@ -14,6 +14,7 @@
 #include "clang/Rewrite/Core/Rewriter.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/DiagnosticIDs.h"
+#include "clang/Basic/FileEntry.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Lex/Lexer.h"
@@ -412,16 +413,19 @@ bool Rewriter::overwriteChangedFiles() {
   unsigned OverwriteFailure = Diag.getCustomDiagID(
   DiagnosticsEngine::Error, "unable to overwrite file %0: %1");
   for (buffer_iterator I = buffer_begin(), E = buffer_end(); I != E; ++I) {
-OptionalFileEntryRef Entry = getSourceMgr().getFileEntryRefForID(I->first);
-llvm::SmallString<128> Path(Entry->getName());
-getSourceMgr().getFileManager().makeAbsolutePath(Path);
-if (auto Error = llvm::writeToOutput(Path, [&](llvm::raw_ostream &OS) {
-  I->second.write(OS);
-  return llvm::Error::success();
-})) {
-  Diag.Report(OverwriteFailure)
-  << Entry->getName() << llvm::toString(std::move(Error));
-  AllWritten = false;
+if (OptionalFileEntryRef fileEntry =
+getSourceMgr().getFileEntryRefForID(I->first)) {
+  llvm::StringRef FileName =
+  getSourceMgr().getFileManager().getCanonicalName(*fileEntry);
+  if (auto Error =
+  llvm::writeToOutput(FileName, [&](llvm::raw_ostream &OS) {
+I->second.write(OS);
+return llvm::Error::success();
+  })) {
+Diag.Report(OverwriteFailure)
+<< FileName << llvm::toString(std::move(Error));
+AllWritten = false;
+  }
 }
   }
   return !AllWritten;
diff --git a/clang/unittests/libclang/LibclangTest.cpp 
b/clang/unittests/libclang/LibclangTest.cpp
index 87075a46d75187..cde19d9004cd81 100644
--- a/clang/unittests/libclang/LibclangTest.cpp
+++ b/clang/unittests/libclang/LibclangTest.cpp
@@ -16,6 +16,7 @@
 #include "llvm/Support/raw_ostream.h"
 #include "gtest/gtest.h"
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -1379,3 +1380,27 @@ TEST_F(LibclangRewriteTest, RewriteRemove) {
   ASSERT_EQ(clang_CXRewriter_overwriteChangedFiles(Rew), 0);
   EXPECT_EQ(getFileContent(Filename), "int () { return 0; }");
 }
+
+TEST_F(LibclangRewriteTest, Symlink) {
+  std::filesystem::path Symlink = "link.cpp";
+  std::filesystem::create_symlink(Filename, Symlink);
+  ASSERT_TRUE(std::filesystem::exists(Symlink));
+  FilesAndDirsToRemove.emplace(Symlink);
+
+  CXTranslationUnit SymTu = clang_parseTranslationUnit(
+  Index, Symlink.c_str(), nullptr, 0, nullptr, 0, TUFlags);
+  CXFile SymlinkFile = clang_getFile(SymTu, Symlink.c_str());
+  CXRewriter SymRew = clang_CXRewriter_create(SymTu);
+
+  CXSourceLocation B = clang_getLocation(SymTu, SymlinkFile, 1, 5);
+  CXSourceLocation E = clang_getLocation(SymTu, SymlinkFile, 1, 9);
+  CXSourceRange Rng = clang_getRange(B, E);
+
+  clang_CXRewriter_removeText(SymRew, Rng);
+
+  ASSERT_EQ(clang_CXRewriter_overwriteChangedFiles(SymRew), 0);
+  EXPECT_EQ(getFileContent(Filename), "int () { return 0; }");
+  EXPECT_TRUE(std::filesystem::is_symlink(Symlink));
+
+  clang_CXRewriter_dispose(SymRew);
+}

``




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


[clang-tools-extra] [clang] Fixed clang-tidy rewriter not properly handling symlinks (PR #76350)

2023-12-24 Thread Félix-Antoine Constantin via cfe-commits

https://github.com/felix642 updated 
https://github.com/llvm/llvm-project/pull/76350

From 0a5ae9bfff7597794889c93e4da5789714be3a4f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?F=C3=A9lix-Antoine=20Constantin?=
 
Date: Sun, 24 Dec 2023 21:01:32 -0500
Subject: [PATCH] [clang][tidy] Fixed clang-tidy rewriter not properly handling
 symlinks

Rewriter would not properly fix files if they were symlinked and using
--fix with clang-tidy would overwrite the symlink with the corrections
rather than the file.

With these changes the Rewriter now properly resolves the symlink before
applying the fixes.

Fixes #60845
---
 clang-tools-extra/docs/ReleaseNotes.rst   |  2 ++
 clang/lib/Rewrite/Rewriter.cpp| 24 +-
 clang/unittests/libclang/LibclangTest.cpp | 25 +++
 3 files changed, 41 insertions(+), 10 deletions(-)

diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 6d91748e4cef18..8a16ce1a7988a2 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -119,6 +119,8 @@ Improvements to clang-tidy
 
 - Improved `--dump-config` to print check options in alphabetical order.
 
+- Improved `--fix` to properly apply corrections on files that are symlinked.
+
 - Improved :program:`clang-tidy-diff.py` script. It now returns exit code `1`
   if any :program:`clang-tidy` subprocess exits with a non-zero code or if
   exporting fixes fails. It now accepts a directory as a value for
diff --git a/clang/lib/Rewrite/Rewriter.cpp b/clang/lib/Rewrite/Rewriter.cpp
index 0e6ae365064463..edc147ec304801 100644
--- a/clang/lib/Rewrite/Rewriter.cpp
+++ b/clang/lib/Rewrite/Rewriter.cpp
@@ -14,6 +14,7 @@
 #include "clang/Rewrite/Core/Rewriter.h"
 #include "clang/Basic/Diagnostic.h"
 #include "clang/Basic/DiagnosticIDs.h"
+#include "clang/Basic/FileEntry.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Lex/Lexer.h"
@@ -412,16 +413,19 @@ bool Rewriter::overwriteChangedFiles() {
   unsigned OverwriteFailure = Diag.getCustomDiagID(
   DiagnosticsEngine::Error, "unable to overwrite file %0: %1");
   for (buffer_iterator I = buffer_begin(), E = buffer_end(); I != E; ++I) {
-OptionalFileEntryRef Entry = getSourceMgr().getFileEntryRefForID(I->first);
-llvm::SmallString<128> Path(Entry->getName());
-getSourceMgr().getFileManager().makeAbsolutePath(Path);
-if (auto Error = llvm::writeToOutput(Path, [&](llvm::raw_ostream &OS) {
-  I->second.write(OS);
-  return llvm::Error::success();
-})) {
-  Diag.Report(OverwriteFailure)
-  << Entry->getName() << llvm::toString(std::move(Error));
-  AllWritten = false;
+if (OptionalFileEntryRef fileEntry =
+getSourceMgr().getFileEntryRefForID(I->first)) {
+  llvm::StringRef FileName =
+  getSourceMgr().getFileManager().getCanonicalName(*fileEntry);
+  if (auto Error =
+  llvm::writeToOutput(FileName, [&](llvm::raw_ostream &OS) {
+I->second.write(OS);
+return llvm::Error::success();
+  })) {
+Diag.Report(OverwriteFailure)
+<< FileName << llvm::toString(std::move(Error));
+AllWritten = false;
+  }
 }
   }
   return !AllWritten;
diff --git a/clang/unittests/libclang/LibclangTest.cpp 
b/clang/unittests/libclang/LibclangTest.cpp
index 87075a46d75187..cde19d9004cd81 100644
--- a/clang/unittests/libclang/LibclangTest.cpp
+++ b/clang/unittests/libclang/LibclangTest.cpp
@@ -16,6 +16,7 @@
 #include "llvm/Support/raw_ostream.h"
 #include "gtest/gtest.h"
 #include 
+#include 
 #include 
 #include 
 #include 
@@ -1379,3 +1380,27 @@ TEST_F(LibclangRewriteTest, RewriteRemove) {
   ASSERT_EQ(clang_CXRewriter_overwriteChangedFiles(Rew), 0);
   EXPECT_EQ(getFileContent(Filename), "int () { return 0; }");
 }
+
+TEST_F(LibclangRewriteTest, Symlink) {
+  std::filesystem::path Symlink = "link.cpp";
+  std::filesystem::create_symlink(Filename, Symlink);
+  ASSERT_TRUE(std::filesystem::exists(Symlink));
+  FilesAndDirsToRemove.emplace(Symlink);
+
+  CXTranslationUnit SymTu = clang_parseTranslationUnit(
+  Index, Symlink.c_str(), nullptr, 0, nullptr, 0, TUFlags);
+  CXFile SymlinkFile = clang_getFile(SymTu, Symlink.c_str());
+  CXRewriter SymRew = clang_CXRewriter_create(SymTu);
+
+  CXSourceLocation B = clang_getLocation(SymTu, SymlinkFile, 1, 5);
+  CXSourceLocation E = clang_getLocation(SymTu, SymlinkFile, 1, 9);
+  CXSourceRange Rng = clang_getRange(B, E);
+
+  clang_CXRewriter_removeText(SymRew, Rng);
+
+  ASSERT_EQ(clang_CXRewriter_overwriteChangedFiles(SymRew), 0);
+  EXPECT_EQ(getFileContent(Filename), "int () { return 0; }");
+  EXPECT_TRUE(std::filesystem::is_symlink(Symlink));
+
+  clang_CXRewriter_dispose(SymRew);
+}

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

[clang-tools-extra] [clang] [clang][tidy] Fixed clang-tidy rewriter not properly handling symlinks (PR #76350)

2023-12-24 Thread Félix-Antoine Constantin via cfe-commits

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


[clang] [clang][driver] Fix unused var warnings in if statements (PR #76346)

2023-12-24 Thread Max Winkler via cfe-commits

MaxEW707 wrote:

Closing this out. Looks like someone beat me to it :).

https://github.com/llvm/llvm-project/commit/81ae2a8bb01d38162e0269fc6819584af6d60b03

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


[clang] [clang][driver] Fix unused var warnings in if statements (PR #76346)

2023-12-24 Thread Max Winkler via cfe-commits

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


[clang-tools-extra] [clang-tidy] introduce a unused local non trival variable check (PR #76101)

2023-12-24 Thread Tyler Rockwood via cfe-commits

https://github.com/rockwotj updated 
https://github.com/llvm/llvm-project/pull/76101

>From 6f0b7e5a80a8812e95357397384217dde4f81b01 Mon Sep 17 00:00:00 2001
From: Tyler Rockwood 
Date: Thu, 21 Dec 2023 16:31:12 -0600
Subject: [PATCH 1/2] clang-tidy/bugprone: introduce
 unused-local-non-trivial-variable check

Signed-off-by: Tyler Rockwood 
---
 .../bugprone/BugproneTidyModule.cpp   |   3 +
 .../clang-tidy/bugprone/CMakeLists.txt|   1 +
 .../UnusedLocalNonTrivialVariableCheck.cpp|  87 +
 .../UnusedLocalNonTrivialVariableCheck.h  |  44 +++
 clang-tools-extra/docs/ReleaseNotes.rst   |   5 +
 .../unused-local-non-trivial-variable.rst |  56 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 .../unused-local-non-trivial-variable.cpp | 114 ++
 8 files changed, 311 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-local-non-trivial-variable.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-local-non-trivial-variable.cpp

diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index 7a910037368c83..435cb1e3fbcff3 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -83,6 +83,7 @@
 #include "UnhandledSelfAssignmentCheck.h"
 #include "UniquePtrArrayMismatchCheck.h"
 #include "UnsafeFunctionsCheck.h"
+#include "UnusedLocalNonTrivialVariableCheck.h"
 #include "UnusedRaiiCheck.h"
 #include "UnusedReturnValueCheck.h"
 #include "UseAfterMoveCheck.h"
@@ -235,6 +236,8 @@ class BugproneModule : public ClangTidyModule {
 "bugprone-unique-ptr-array-mismatch");
 CheckFactories.registerCheck(
 "bugprone-unsafe-functions");
+CheckFactories.registerCheck(
+"bugprone-unused-local-non-trivial-variable");
 CheckFactories.registerCheck("bugprone-unused-raii");
 CheckFactories.registerCheck(
 "bugprone-unused-return-value");
diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
index d443fd8d1452f1..70e7fbc7ec0c14 100644
--- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
@@ -79,6 +79,7 @@ add_clang_library(clangTidyBugproneModule
   UnhandledSelfAssignmentCheck.cpp
   UniquePtrArrayMismatchCheck.cpp
   UnsafeFunctionsCheck.cpp
+  UnusedLocalNonTrivialVariableCheck.cpp
   UnusedRaiiCheck.cpp
   UnusedReturnValueCheck.cpp
   UseAfterMoveCheck.cpp
diff --git 
a/clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.cpp
new file mode 100644
index 00..18f975668b8cad
--- /dev/null
+++ 
b/clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.cpp
@@ -0,0 +1,87 @@
+//===--- UnusedLocalNonTrivialVariableCheck.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 "UnusedLocalNonTrivialVariableCheck.h"
+#include "../utils/Matchers.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersMacros.h"
+
+using namespace clang::ast_matchers;
+using namespace clang::tidy::matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+static constexpr StringRef DefaultIncludeTypeRegex =
+"::std::.*mutex;::std::future;::std::basic_string;::std::basic_regex;"
+"::std::base_istringstream;::std::base_stringstream;::std::bitset;"
+"::std::filesystem::path";
+
+AST_MATCHER(VarDecl, isLocalVarDecl) { return Node.isLocalVarDecl(); }
+AST_MATCHER(VarDecl, isReferenced) { return Node.isReferenced(); }
+AST_MATCHER(Type, isReferenceType) { return Node.isReferenceType(); }
+AST_MATCHER(QualType, isTrivial) {
+  return Node.isTrivialType(Finder->getASTContext()) ||
+ Node.isTriviallyCopyableType(Finder->getASTContext());
+}
+} // namespace
+
+UnusedLocalNonTrivialVariableCheck::UnusedLocalNonTrivialVariableCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  IncludeTypes(utils::options::parseStringList(
+  Options.get("IncludeTypes", DefaultIncludeTypeRegex))),
+  Exclud

[clang-tools-extra] [clang-tidy] introduce a unused local non trival variable check (PR #76101)

2023-12-24 Thread Tyler Rockwood via cfe-commits


@@ -0,0 +1,92 @@
+//===--- UnusedLocalNonTrivialVariableCheck.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 "UnusedLocalNonTrivialVariableCheck.h"
+#include "../utils/Matchers.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersMacros.h"
+
+using namespace clang::ast_matchers;
+using namespace clang::tidy::matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+static constexpr StringRef DefaultIncludeTypeRegex =
+"::std::.*mutex;::std::future;::std::basic_string;::std::basic_regex;"
+"::std::base_istringstream;::std::base_stringstream;::std::bitset;"
+"::std::path";

rockwotj wrote:

Yeah I don't use these APIs much, but good catch! I've fixed it.

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


[clang] [llvm] [RISCV] Always emit relocations for resolved symbols and relax (PR #73793)

2023-12-24 Thread Fangrui Song via cfe-commits

MaskRay wrote:

The current patch doesn't do what the title implies ("Always emit relocations 
for resolved ").

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


[clang-tools-extra] [clang-tidy] introduce a unused local non trival variable check (PR #76101)

2023-12-24 Thread Tyler Rockwood via cfe-commits


@@ -0,0 +1,92 @@
+//===--- UnusedLocalNonTrivialVariableCheck.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 "UnusedLocalNonTrivialVariableCheck.h"
+#include "../utils/Matchers.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersMacros.h"
+
+using namespace clang::ast_matchers;
+using namespace clang::tidy::matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+static constexpr StringRef DefaultIncludeTypeRegex =
+"::std::.*mutex;::std::future;::std::basic_string;::std::basic_regex;"
+"::std::base_istringstream;::std::base_stringstream;::std::bitset;"
+"::std::path";
+
+AST_MATCHER(VarDecl, isLocalVarDecl) { return Node.isLocalVarDecl(); }
+AST_MATCHER(VarDecl, isReferenced) { return Node.isReferenced(); }
+AST_MATCHER(Type, isReferenceType) { return Node.isReferenceType(); }
+AST_MATCHER(QualType, isTrivial) {
+  return Node.isTrivialType(Finder->getASTContext()) ||
+ Node.isTriviallyCopyableType(Finder->getASTContext());
+}
+} // namespace
+
+UnusedLocalNonTrivialVariableCheck::UnusedLocalNonTrivialVariableCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  IncludeTypes(utils::options::parseStringList(
+  Options.get("IncludeTypes", DefaultIncludeTypeRegex))),
+  ExcludeTypes(
+  utils::options::parseStringList(Options.get("ExcludeTypes", ""))) {}
+
+void UnusedLocalNonTrivialVariableCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IncludeTypes",
+utils::options::serializeStringList(IncludeTypes));
+  Options.store(Opts, "ExcludeTypes",
+utils::options::serializeStringList(ExcludeTypes));
+}
+
+void UnusedLocalNonTrivialVariableCheck::registerMatchers(MatchFinder *Finder) 
{
+  if (IncludeTypes.empty())
+return;
+
+  Finder->addMatcher(
+  varDecl(isLocalVarDecl(), unless(isReferenced()),
+  unless(isExpansionInSystemHeader()),

rockwotj wrote:

SG removed.

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


[clang-tools-extra] [clang-tidy] introduce a unused local non trival variable check (PR #76101)

2023-12-24 Thread Tyler Rockwood via cfe-commits


@@ -0,0 +1,91 @@
+// RUN: %check_clang_tidy -std=c++17 %s 
bugprone-unused-local-non-trivial-variable %t -- \

rockwotj wrote:

Done.

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


[clang-tools-extra] [clang-tidy] introduce a unused local non trival variable check (PR #76101)

2023-12-24 Thread Tyler Rockwood via cfe-commits


@@ -0,0 +1,91 @@
+// RUN: %check_clang_tidy -std=c++17 %s 
bugprone-unused-local-non-trivial-variable %t -- \
+// RUN:   -config="{CheckOptions: 
{bugprone-unused-local-non-trivial-variable.IncludeTypes: '::async::Future'}}"

rockwotj wrote:

Done.

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


[clang] [clang] Fix --entry command line option (PR #69114)

2023-12-24 Thread Fangrui Song via cfe-commits

MaskRay wrote:

Since `--entry` is wrong, `--entry=` is unsupported, and nobody seems to use 
the driver option which only affects linking, we probably should just remove 
it. Users are expected to use `-Wl,-e,entry` or `-Wl,--entry=entry` anyway.

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


[clang] [clang-format] Fix handling of C-Style variable definition of a struct (PR #76344)

2023-12-24 Thread via cfe-commits

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


[clang] [llvm] [compiler-rt] [mlir] [emacs][lsp][tblgen] add tblgen-lsp-server support for emacs lsp-mode (PR #76337)

2023-12-24 Thread via cfe-commits

https://github.com/mgcsysinfcat updated 
https://github.com/llvm/llvm-project/pull/76337

>From b530c6dfc9d2e098b3634ea720f0b0bfde0d411f Mon Sep 17 00:00:00 2001
From: mgcsysinfcat 
Date: Sun, 24 Dec 2023 23:00:00 +0800
Subject: [PATCH] add tblgen-lsp-server support for lsp-mode

---
 mlir/utils/emacs/tblgen-lsp.el | 45 ++
 1 file changed, 45 insertions(+)
 create mode 100644 mlir/utils/emacs/tblgen-lsp.el

diff --git a/mlir/utils/emacs/tblgen-lsp.el b/mlir/utils/emacs/tblgen-lsp.el
new file mode 100644
index 00..607459549193a1
--- /dev/null
+++ b/mlir/utils/emacs/tblgen-lsp.el
@@ -0,0 +1,45 @@
+;;; tblgen-lsp.el --- Description -*- lexical-binding: t; -*-
+;;
+;; Package-Requires: ((emacs "24.3"))
+;;
+;; This file is not part of GNU Emacs.
+;;
+;;; Commentary:
+;;  LSP clinet to use with `tablegen-mode' that uses `tblgen-lsp-server' or any
+;;  user made compatible server.
+;;
+;;
+;;; Code:
+
+
+(defgroup lsp-tblgen nil
+  "LSP support for Tablegen."
+  :group 'lsp-mode
+  :link '(url-link "https://mlir.llvm.org/docs/Tools/MLIRLSP/";))
+
+(defcustom lsp-tblgen-server-executable "tblgen-lsp-server"
+  "Command to start the mlir language server."
+  :group 'lsp-tblgen
+  :risky t
+  :type 'file)
+
+
+(defcustom lsp-tblgen-server-args ""
+  "Args of LSP client for TableGen "
+  :group 'lsp-tblgen
+  :risky t
+  :type 'file)
+
+(defun lsp-tblgen-setup ()
+  "Setup the LSP client for TableGen."
+  (add-to-list 'lsp-language-id-configuration '(tablegen-mode . "tablegen"))
+
+  (lsp-register-client
+   (make-lsp-client
+:new-connection (lsp-stdio-connection (lambda () (cons 
lsp-tblgen-server-executable lsp-tblgen-server-args))); (concat 
"--tablegen-compilation-database=" lsp-tblgen-compilation-database-location) )))
+:activation-fn (lsp-activate-on "tablegen")
+:priority -1
+:server-id 'tblgen-lsp-server)))
+
+(provide 'tblgen-lsp)
+;;; tblgen-lsp.el ends here

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


[clang-tools-extra] [clang-tidy] introduce a unused local non trival variable check (PR #76101)

2023-12-24 Thread Piotr Zegar via cfe-commits

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

LGTM.
Unless you want this to be merged by rockw...@users.noreply.github.com please 
change your github privacy settings.

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


[clang] fe21b39 - [Basic] Use range-based for loops (NFC)

2023-12-24 Thread Kazu Hirata via cfe-commits

Author: Kazu Hirata
Date: 2023-12-24T23:38:25-08:00
New Revision: fe21b3941df24420b72e789dcf67de2dc17c4417

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

LOG: [Basic] Use range-based for loops (NFC)

Added: 


Modified: 
clang/include/clang/Basic/PlistSupport.h
clang/lib/Basic/Warnings.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/PlistSupport.h 
b/clang/include/clang/Basic/PlistSupport.h
index 557462a5b90d01..d52d196019cf84 100644
--- a/clang/include/clang/Basic/PlistSupport.h
+++ b/clang/include/clang/Basic/PlistSupport.h
@@ -77,8 +77,7 @@ inline raw_ostream &EmitInteger(raw_ostream &o, int64_t 
value) {
 
 inline raw_ostream &EmitString(raw_ostream &o, StringRef s) {
   o << "";
-  for (StringRef::const_iterator I = s.begin(), E = s.end(); I != E; ++I) {
-char c = *I;
+  for (char c : s) {
 switch (c) {
 default:
   o << c;

diff  --git a/clang/lib/Basic/Warnings.cpp b/clang/lib/Basic/Warnings.cpp
index cb23d844ef8f6f..bab1af4f03b67b 100644
--- a/clang/lib/Basic/Warnings.cpp
+++ b/clang/lib/Basic/Warnings.cpp
@@ -198,8 +198,7 @@ void clang::ProcessWarningOptions(DiagnosticsEngine &Diags,
   }
 }
 
-for (unsigned i = 0, e = Opts.Remarks.size(); i != e; ++i) {
-  StringRef Opt = Opts.Remarks[i];
+for (StringRef Opt : Opts.Remarks) {
   const auto Flavor = diag::Flavor::Remark;
 
   // Check to see if this warning starts with "no-", if so, this is a



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