[clang] [alpha.webkit.NoUnretainedMemberChecker] Add a new WebKit checker for unretained member variables and ivars. (PR #128641)

2025-03-08 Thread Rashmi Mudduluru via cfe-commits


@@ -3487,6 +3487,19 @@ Raw pointers and references to an object which supports 
CheckedPtr or CheckedRef
 
 See `WebKit Guidelines for Safer C++ Programming 
`_ for details.
 
+alpha.webkit.NoUnretainedMemberChecker
+
+Raw pointers and references to a NS or CF object can't be used as class 
members or ivars. Only RetainPtr is allowed.

t-rasmud wrote:

Maybe add a note here saying RetainPtr is a requirement irrespective of whether 
ARC is enabled for CF types.

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


[clang] [llvm] [alpha.webkit.UnretainedLambdaCapturesChecker] Add a WebKit checker for lambda capturing NS or CF types. (PR #128651)

2025-03-08 Thread Rashmi Mudduluru via cfe-commits

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


[clang] [ARM] Using cp15 while mtp =auto and arch is arm_arch6k and support thumb2 (PR #130027)

2025-03-08 Thread via cfe-commits


@@ -240,7 +247,7 @@ arm::ReadTPMode arm::getReadTPMode(const Driver &D, const 
ArgList &Args,
   D.Diag(diag::err_drv_invalid_mtp) << A->getAsString(Args);
 return ReadTPMode::Invalid;
   }
-  return (isHardTPSupported(Triple) ? ReadTPMode::TPIDRURO : ReadTPMode::Soft);
+  return (isHardTPAndThumb2(Triple) ? ReadTPMode::TPIDRURO : ReadTPMode::Soft);

Zhenhang1213 wrote:

I have updated my code, and could you review it again, thx

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


[clang] [C2y] Implement WG14 N3411 (PR #130180)

2025-03-08 Thread Aaron Ballman via cfe-commits

https://github.com/AaronBallman created 
https://github.com/llvm/llvm-project/pull/130180

This paper (https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3411.pdf) allows 
a source file to end without a newline. Clang has supported this as a 
conforming extension for a long time, so this suppresses the diagnotic in C2y 
mode but continues to diagnose as an extension in earlier language modes. It 
also continues to diagnose if the user passes -Wnewline-eof explicitly.

>From 517b2b64e8dc67cf33b5e1aaef8d17c567b6b5d7 Mon Sep 17 00:00:00 2001
From: Aaron Ballman 
Date: Thu, 6 Mar 2025 16:43:38 -0500
Subject: [PATCH] [C2y] Implement WG14 N3411

This paper allows a source file to end without a newline. Clang has
supported this as a conforming extension for a long time, so this
suppresses the diagnotic in C2y mode but continues to diagnose as an
extension in earlier language modes. It also continues to diagnose if
the user passes -Wnewline-eof explicitly.
---
 clang/docs/ReleaseNotes.rst |  3 +++
 clang/lib/Lex/Lexer.cpp | 15 +++
 clang/test/C/C2y/n3411.c| 14 ++
 clang/www/c_status.html |  2 +-
 4 files changed, 25 insertions(+), 9 deletions(-)
 create mode 100644 clang/test/C/C2y/n3411.c

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 38b5bdf1dd46b..36aeb6c736627 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -108,6 +108,9 @@ C Language Changes
 
 C2y Feature Support
 ^^^
+- Implemented N3411 which allows a source file to not end with a newline
+  character. This is still reported as a conforming extension in earlier
+  language modes.
 
 C23 Feature Support
 ^^^
diff --git a/clang/lib/Lex/Lexer.cpp b/clang/lib/Lex/Lexer.cpp
index 087c6f13aea66..c62a9f5041183 100644
--- a/clang/lib/Lex/Lexer.cpp
+++ b/clang/lib/Lex/Lexer.cpp
@@ -3192,23 +3192,22 @@ bool Lexer::LexEndOfFile(Token &Result, const char 
*CurPtr) {
   if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
 DiagnosticsEngine &Diags = PP->getDiagnostics();
 SourceLocation EndLoc = getSourceLocation(BufferEnd);
-unsigned DiagID;
+unsigned DiagID = diag::warn_no_newline_eof;
 
 if (LangOpts.CPlusPlus11) {
   // C++11 [lex.phases] 2.2 p2
   // Prefer the C++98 pedantic compatibility warning over the generic,
   // non-extension, user-requested "missing newline at EOF" warning.
-  if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
+  if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc))
 DiagID = diag::warn_cxx98_compat_no_newline_eof;
-  } else {
-DiagID = diag::warn_no_newline_eof;
-  }
 } else {
-  DiagID = diag::ext_no_newline_eof;
+  // This is conforming in C2y, but is an extension in earlier language
+  // modes.
+  if (!LangOpts.C2y)
+DiagID = diag::ext_no_newline_eof;
 }
 
-Diag(BufferEnd, DiagID)
-  << FixItHint::CreateInsertion(EndLoc, "\n");
+Diag(BufferEnd, DiagID) << FixItHint::CreateInsertion(EndLoc, "\n");
   }
 
   BufferPtr = CurPtr;
diff --git a/clang/test/C/C2y/n3411.c b/clang/test/C/C2y/n3411.c
new file mode 100644
index 0..edfc1c16fe365
--- /dev/null
+++ b/clang/test/C/C2y/n3411.c
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -verify=c2y -std=c2y -Wall -pedantic %s
+// RUN: %clang_cc1 -verify -Wnewline-eof -std=c2y -Wall -pedantic %s
+// RUN: %clang_cc1 -verify -std=c23 -Wall -pedantic %s
+
+/* WG14 N3411: Yes
+ * Slay Some Earthly Demons XII
+ *
+ * Allow a non-empty source file to end without a final newline character. Note
+ * that this file intentionally does not end with a trailing newline.
+ */
+// c2y-no-diagnostics
+
+int x; // Ensure the file contains at least one declaration.
+// expected-warning {{no newline at end of file}}
\ No newline at end of file
diff --git a/clang/www/c_status.html b/clang/www/c_status.html
index 4e912987b69c6..e8b50a37093f9 100644
--- a/clang/www/c_status.html
+++ b/clang/www/c_status.html
@@ -294,7 +294,7 @@ C2y implementation status
 
   Slay Some Earthly Demons XII
   https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3411.pdf";>N3411
-  Unknown
+  Clang 21

 
   Slay Some Earthly Demons XIII

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


[clang] [alpha.webkit.NoUnretainedMemberChecker] Add a new WebKit checker for unretained member variables and ivars. (PR #128641)

2025-03-08 Thread Rashmi Mudduluru via cfe-commits


@@ -0,0 +1,57 @@
+// RUN: %clang_analyze_cc1 
-analyzer-checker=alpha.webkit.NoUnretainedMemberChecker -verify %s
+
+#include "objc-mock-types.h"
+
+namespace members {
+
+  struct Foo {
+  private:
+SomeObj* a = nullptr;
+// expected-warning@-1{{Member variable 'a' in 'members::Foo' is a raw pointer 
to retainable type}}
+
+[[clang::suppress]]

t-rasmud wrote:

Maybe add a comment here stating what warnings are being suppressed?

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


[clang] [clang][modules][deps] Add mutex as an alternative to file lock (PR #129751)

2025-03-08 Thread Michael Spencer via cfe-commits


@@ -95,6 +96,10 @@ class DependencyScanningService {
 return SharedCache;
   }
 
+  ModuleCacheMutexes &getSharedModuleCacheMutexes() {

Bigcheese wrote:

I don't think we need shared_ptr here, the lifetime of workers is already bound 
to the service.

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


[clang] CodeGen: support static linking for libclosure (PR #125384)

2025-03-08 Thread Saleem Abdulrasool via cfe-commits

compnerd wrote:

@steakhal bleh, is the "New Features" a sub item of "Static Analyzer"?

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


[clang] [clang] Fix typos in options text. (PR #130129)

2025-03-08 Thread Mariya Podchishchaeva via cfe-commits


@@ -515,7 +515,7 @@ VALUE_LANGOPT(FuchsiaAPILevel, 32, 0, "Fuchsia API level")
 // on large _BitInts.
 BENIGN_VALUE_LANGOPT(MaxBitIntWidth, 32, 128, "Maximum width of a _BitInt")
 
-COMPATIBLE_LANGOPT(IncrementalExtensions, 1, 0, " True if we want to process 
statements"
+COMPATIBLE_LANGOPT(IncrementalExtensions, 1, 0, " True if we want to process 
statements "

Fznamznon wrote:

I'm not entirely sure where description of langoption goes, but I think a space 
in the beginning is not needed.
```suggestion
COMPATIBLE_LANGOPT(IncrementalExtensions, 1, 0, "True if we want to process 
statements "
```

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


[clang] Fobbid co_await and co_yield in invalid expr context (PR #130455)

2025-03-08 Thread via cfe-commits

https://github.com/NewSigma created 
https://github.com/llvm/llvm-project/pull/130455

Fix #78426 

C++26 introduced braced initializer lists as template arguments. However, such 
contexts should be considered invalid for co_await and co_yield. This commit 
explicitly rules out the possibility of using these exprs in template arguments.

>From 85a40587375533ac8fcd842395c923895c5debaf Mon Sep 17 00:00:00 2001
From: NewSigma 
Date: Sun, 9 Mar 2025 10:27:24 +0800
Subject: [PATCH] Fobbid co_await in invalid expr context

---
 clang/lib/Sema/SemaCoroutine.cpp | 7 +--
 1 file changed, 5 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaCoroutine.cpp b/clang/lib/Sema/SemaCoroutine.cpp
index 0e4f3b20c78cd..53536b0d14037 100644
--- a/clang/lib/Sema/SemaCoroutine.cpp
+++ b/clang/lib/Sema/SemaCoroutine.cpp
@@ -788,7 +788,11 @@ static bool checkSuspensionContext(Sema &S, SourceLocation 
Loc,
   // First emphasis of [expr.await]p2: must be a potentially evaluated context.
   // That is, 'co_await' and 'co_yield' cannot appear in subexpressions of
   // \c sizeof.
-  if (S.isUnevaluatedContext()) {
+  const auto ExprContext = S.currentEvaluationContext().ExprContext;
+  const bool BadContext =
+  S.isUnevaluatedContext() ||
+  ExprContext != Sema::ExpressionEvaluationContextRecord::EK_Other;
+  if (BadContext) {
 S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
 return false;
   }
@@ -798,7 +802,6 @@ static bool checkSuspensionContext(Sema &S, SourceLocation 
Loc,
 S.Diag(Loc, diag::err_coroutine_within_handler) << Keyword;
 return false;
   }
-
   return true;
 }
 

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


[clang-tools-extra] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init check (PR #129370)

2025-03-08 Thread Congcong Cai via cfe-commits


@@ -159,6 +159,12 @@ static bool sameValue(const Expr *E1, const Expr *E2) {
   case Stmt::UnaryOperatorClass:
 return sameValue(cast(E1)->getSubExpr(),
  cast(E2)->getSubExpr());
+  case Stmt::BinaryOperatorClass: {

HerrCai0907 wrote:

Should we compare BinaryOp here?

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


[clang-tools-extra] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init check (PR #129370)

2025-03-08 Thread Congcong Cai via cfe-commits

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


[clang] [clang][analyzer][NFC] Fix typos in comments (PR #130456)

2025-03-08 Thread Ben Shi via cfe-commits

https://github.com/benshi001 created 
https://github.com/llvm/llvm-project/pull/130456

None

>From 256a8383066dcc20f87296bc0ec659a9b5764a64 Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Thu, 20 Feb 2025 18:01:42 +0800
Subject: [PATCH] [clang][analyzer][NFC] Fix typos in comments

---
 .../Core/PathSensitive/CheckerContext.h  |  6 +++---
 .../Core/PathSensitive/CoreEngine.h  |  2 +-
 .../Core/PathSensitive/ExplodedGraph.h   |  6 +++---
 .../Core/PathSensitive/ExprEngine.h  | 16 
 .../Core/PathSensitive/ProgramState.h|  5 ++---
 .../StaticAnalyzer/Core/PathSensitive/SMTConv.h  |  2 +-
 6 files changed, 18 insertions(+), 19 deletions(-)

diff --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
index 168983fd5cb68..bb33a6912bec7 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
@@ -7,7 +7,7 @@
 
//===--===//
 //
 //  This file defines CheckerContext that provides contextual info for
-// path-sensitive checkers.
+//  path-sensitive checkers.
 //
 
//===--===//
 
@@ -152,7 +152,7 @@ class CheckerContext {
   }
 
   /// Returns true if the value of \p E is greater than or equal to \p
-  /// Val under unsigned comparison
+  /// Val under unsigned comparison.
   bool isGreaterOrEqual(const Expr *E, unsigned long long Val);
 
   /// Returns true if the value of \p E is negative.
@@ -392,7 +392,7 @@ class CheckerContext {
   /// hardened variant that's not yet covered by it.
   static bool isHardenedVariantOf(const FunctionDecl *FD, StringRef Name);
 
-  /// Depending on wither the location corresponds to a macro, return
+  /// Depending on whether the location corresponds to a macro, return
   /// either the macro name or the token spelling.
   ///
   /// This could be useful when checkers' logic depends on whether a function
diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
index 80b79fd4e928f..b2b4e8729af25 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
@@ -156,7 +156,7 @@ class CoreEngine {
   void dispatchWorkItem(ExplodedNode* Pred, ProgramPoint Loc,
 const WorkListUnit& WU);
 
-  // Functions for external checking of whether we have unfinished work
+  // Functions for external checking of whether we have unfinished work.
   bool wasBlockAborted() const { return !blocksAborted.empty(); }
   bool wasBlocksExhausted() const { return !blocksExhausted.empty(); }
   bool hasWorkRemaining() const { return wasBlocksExhausted() ||
diff --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
index 2fb05ac46e8fa..967b25e5696f6 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
@@ -7,7 +7,7 @@
 
//===--===//
 //
 //  This file defines the template classes ExplodedNode and ExplodedGraph,
-//  which represent a path-sensitive, intra-procedural "exploded graph."
+//  which represent a path-sensitive, intra-procedural "exploded graph".
 //  See "Precise interprocedural dataflow analysis via graph reachability"
 //  by Reps, Horwitz, and Sagiv
 //  (http://portal.acm.org/citation.cfm?id=199462) for the definition of an
@@ -426,8 +426,8 @@ class ExplodedGraph {
   ///
   /// \param Nodes The nodes which must appear in the final graph. Presumably
   ///  these are end-of-path nodes (i.e. they have no successors).
-  /// \param[out] ForwardMap A optional map from nodes in this graph to nodes 
in
-  ///the returned graph.
+  /// \param[out] ForwardMap An optional map from nodes in this graph to nodes
+  ///in the returned graph.
   /// \param[out] InverseMap An optional map from nodes in the returned graph 
to
   ///nodes in this graph.
   /// \returns The trimmed graph
diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
index 804fc74b009df..2c95a6d16afe7 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
@@ -429,7 +429,7 @@ class ExprEngine {
 
   DataTag::Factory &getDataTags() { return Engine.getDataTags(); }
 
-  // Functions for external checki

[clang] Better diagnostics when assertion fails in `consteval` (PR #130458)

2025-03-08 Thread JJ Marr via cfe-commits

https://github.com/jj-marr created 
https://github.com/llvm/llvm-project/pull/130458

Take this piece of code:
```cpp
#include 

consteval int square(int x) {
  int result = x * x;
  assert(result == 42);
  return result;
}

void test() {
  auto val = square(2);
}
```
The assertion will fail, and `clang++` will output 
(https://godbolt.org/z/hjz3KbTTv):
```cpp
:10:14: error: call to consteval function 'square' is not a constant 
expression
   10 |   auto val = square(2);
  |  ^
:5:3: note: non-constexpr function '__assert_fail' cannot be used in a 
constant expression
5 |   assert(result == 42);
  |   ^
/usr/include/assert.h:95:9: note: expanded from macro 'assert'
   95 |   : __assert_fail (#expr, __FILE__, __LINE__, __ASSERT_FUNCTION))
  | ^
:10:14: note: in call to 'square(2)'
   10 |   auto val = square(2);
  |  ^
/usr/include/assert.h:69:13: note: declared here
   69 | extern void __assert_fail (const char *__assertion, const char *__file,
  | ^
1 error generated.
Compiler returned: 1
```
This is confusing because it implies that the issue was using an assertion in a 
constant-evaluted context, and not that the assertion failed (`assert()` is OK 
in constant evaluation). This PR changes the error message to:
```cpp
test.cpp:10:14: error: call to consteval function 'square' is not a constant 
expression
   10 |   auto val = square(2);
  |  ^
test.cpp:5:3: note: assertion failed in consteval context: 'result == 42'
5 |   assert(result == 42);
  |   ^
/nix/store/lw21wr626v5sdcaxxkv2k4zf1121hfc9-glibc-2.40-36-dev/include/assert.h:102:9:
 note: expanded from macro 'assert'
  102 |   : __assert_fail (#expr, __ASSERT_FILE, __ASSERT_LINE, 
\
  | ^
test.cpp:10:14: note: in call to 'square(2)'
   10 |   auto val = square(2);
  |  ^
1 error generated.```

>From 8a09c78d3fdb151c86785822da6cb451025b4654 Mon Sep 17 00:00:00 2001
From: JJ Marr 
Date: Sat, 8 Mar 2025 22:00:45 -0500
Subject: [PATCH 1/2] Explain which assertion failed during consteval

---
 clang/include/clang/Basic/DiagnosticSemaKinds.td |  2 ++
 clang/lib/AST/ExprConstant.cpp   | 11 +++
 2 files changed, 13 insertions(+)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 21be7c358a61d..ff5f88d6ac572 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -107,6 +107,8 @@ def err_ice_too_large : Error<
   "integer constant expression evaluates to value %0 that cannot be "
   "represented in a %1-bit %select{signed|unsigned}2 integer type">;
 def err_expr_not_string_literal : Error<"expression is not a string literal">;
+def note_constexpr_assert_failed : Note<
+  "assertion failed in consteval context: '%0'">;
 
 // Semantic analysis of constant literals.
 def ext_predef_outside_function : Warning<
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index d9a1e5bb42343..7013f0b143a0a 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -8361,6 +8361,17 @@ class ExprEvaluatorBase
 return false;
 }
 
+// If an assertion fails during constant evaluation, give a specific note 
explaining that
+if (FD->getName() == "__assert_fail") {
+  const Expr *AssertionExpr = E->getArg(0);
+  const StringLiteral *AssertionText = 
dyn_cast(AssertionExpr->IgnoreParens()->IgnoreParenImpCasts());
+
+  Info.FFDiag(E->getBeginLoc(), diag::note_constexpr_assert_failed)
+  << (AssertionText ? AssertionText->getString() : "");
+
+  return false;
+}
+
 SmallVector CovariantAdjustmentPath;
 if (This) {
   auto *NamedMember = dyn_cast(FD);

>From c8fe23e62a6a0090ef050a3ca3ac9abe549b0aa6 Mon Sep 17 00:00:00 2001
From: JJ Marr 
Date: Sat, 8 Mar 2025 22:36:26 -0500
Subject: [PATCH 2/2] Add unit test

---
 clang/test/SemaCXX/consteval_assert.cpp | 20 
 1 file changed, 20 insertions(+)
 create mode 100644 clang/test/SemaCXX/consteval_assert.cpp

diff --git a/clang/test/SemaCXX/consteval_assert.cpp 
b/clang/test/SemaCXX/consteval_assert.cpp
new file mode 100644
index 0..94ca9ffd4888d
--- /dev/null
+++ b/clang/test/SemaCXX/consteval_assert.cpp
@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 -std=c++23 -verify=expected,cxx20_plus %s
+
+#ifdef __ASSERT_FUNCTION
+#undef __ASSERT_FUNCTION
+#endif
+extern "C" void __assert_fail(const char*, const char*, unsigned, const char*);
+
+#define assert(cond) \
+  ((cond) ? (void)0 : __assert_fail(#cond, __FILE__, __LINE__, __func__))
+
+consteval int square(int x) {
+  int result = x * x;
+  assert(result == 42); // expected-note {{assertion failed in consteval 
context: 'result == 42'}}
+  return result;
+}
+
+void test() {
+  auto val = square(2); // expected-note {{in call to 'square(2)'}} \
+  // expec

[clang] Better diagnostics when assertion fails in `consteval` (PR #130458)

2025-03-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: JJ Marr (jj-marr)


Changes

Take this piece of code:
```cpp
#include 

consteval int square(int x) {
  int result = x * x;
  assert(result == 42);
  return result;
}

void test() {
  auto val = square(2);
}
```
The assertion will fail, and `clang++` will output 
(https://godbolt.org/z/hjz3KbTTv):
```cpp
:10:14: error: call to consteval function 'square' is not a 
constant expression
   10 |   auto val = square(2);
  |  ^
:5:3: note: non-constexpr function '__assert_fail' cannot be used 
in a constant expression
5 |   assert(result == 42);
  |   ^
/usr/include/assert.h:95:9: note: expanded from macro 'assert'
   95 |   : __assert_fail (#expr, __FILE__, __LINE__, __ASSERT_FUNCTION))
  | ^
:10:14: note: in call to 'square(2)'
   10 |   auto val = square(2);
  |  ^
/usr/include/assert.h:69:13: note: declared here
   69 | extern void __assert_fail (const char *__assertion, const char *__file,
  | ^
1 error generated.
Compiler returned: 1
```
This is confusing because it implies that the issue was using an assertion in a 
constant-evaluted context, and not that the assertion failed (`assert()` is OK 
in constant evaluation). This PR changes the error message to:
```cpp
test.cpp:10:14: error: call to consteval function 'square' is not a constant 
expression
   10 |   auto val = square(2);
  |  ^
test.cpp:5:3: note: assertion failed in consteval context: 'result == 42'
5 |   assert(result == 42);
  |   ^
/nix/store/lw21wr626v5sdcaxxkv2k4zf1121hfc9-glibc-2.40-36-dev/include/assert.h:102:9:
 note: expanded from macro 'assert'
  102 |   : __assert_fail (#expr, __ASSERT_FILE, __ASSERT_LINE, 
\
  | ^
test.cpp:10:14: note: in call to 'square(2)'
   10 |   auto val = square(2);
  |  ^
1 error generated.```

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


3 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+2) 
- (modified) clang/lib/AST/ExprConstant.cpp (+11) 
- (added) clang/test/SemaCXX/consteval_assert.cpp (+20) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 21be7c358a61d..ff5f88d6ac572 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -107,6 +107,8 @@ def err_ice_too_large : Error<
   "integer constant expression evaluates to value %0 that cannot be "
   "represented in a %1-bit %select{signed|unsigned}2 integer type">;
 def err_expr_not_string_literal : Error<"expression is not a string literal">;
+def note_constexpr_assert_failed : Note<
+  "assertion failed in consteval context: '%0'">;
 
 // Semantic analysis of constant literals.
 def ext_predef_outside_function : Warning<
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index d9a1e5bb42343..7013f0b143a0a 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -8361,6 +8361,17 @@ class ExprEvaluatorBase
 return false;
 }
 
+// If an assertion fails during constant evaluation, give a specific note 
explaining that
+if (FD->getName() == "__assert_fail") {
+  const Expr *AssertionExpr = E->getArg(0);
+  const StringLiteral *AssertionText = 
dyn_cast(AssertionExpr->IgnoreParens()->IgnoreParenImpCasts());
+
+  Info.FFDiag(E->getBeginLoc(), diag::note_constexpr_assert_failed)
+  << (AssertionText ? AssertionText->getString() : "");
+
+  return false;
+}
+
 SmallVector CovariantAdjustmentPath;
 if (This) {
   auto *NamedMember = dyn_cast(FD);
diff --git a/clang/test/SemaCXX/consteval_assert.cpp 
b/clang/test/SemaCXX/consteval_assert.cpp
new file mode 100644
index 0..94ca9ffd4888d
--- /dev/null
+++ b/clang/test/SemaCXX/consteval_assert.cpp
@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 -std=c++23 -verify=expected,cxx20_plus %s
+
+#ifdef __ASSERT_FUNCTION
+#undef __ASSERT_FUNCTION
+#endif
+extern "C" void __assert_fail(const char*, const char*, unsigned, const char*);
+
+#define assert(cond) \
+  ((cond) ? (void)0 : __assert_fail(#cond, __FILE__, __LINE__, __func__))
+
+consteval int square(int x) {
+  int result = x * x;
+  assert(result == 42); // expected-note {{assertion failed in consteval 
context: 'result == 42'}}
+  return result;
+}
+
+void test() {
+  auto val = square(2); // expected-note {{in call to 'square(2)'}} \
+  // expected-error {{call to consteval function 'square' is not a constant 
expression}}
+}

``




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


[clang] Better diagnostics when assertion fails in `consteval` (PR #130458)

2025-03-08 Thread JJ Marr via cfe-commits

https://github.com/jj-marr updated 
https://github.com/llvm/llvm-project/pull/130458

>From d61892d8546944000118ad0312886da75cd6509b Mon Sep 17 00:00:00 2001
From: JJ Marr 
Date: Sat, 8 Mar 2025 22:00:45 -0500
Subject: [PATCH] Explain which assertion failed during consteval

---
 .../clang/Basic/DiagnosticSemaKinds.td|  2 ++
 clang/lib/AST/ExprConstant.cpp| 11 ++
 clang/test/SemaCXX/consteval_assert.cpp   | 20 +++
 3 files changed, 33 insertions(+)
 create mode 100644 clang/test/SemaCXX/consteval_assert.cpp

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 21be7c358a61d..ff5f88d6ac572 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -107,6 +107,8 @@ def err_ice_too_large : Error<
   "integer constant expression evaluates to value %0 that cannot be "
   "represented in a %1-bit %select{signed|unsigned}2 integer type">;
 def err_expr_not_string_literal : Error<"expression is not a string literal">;
+def note_constexpr_assert_failed : Note<
+  "assertion failed in consteval context: '%0'">;
 
 // Semantic analysis of constant literals.
 def ext_predef_outside_function : Warning<
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index d9a1e5bb42343..7013f0b143a0a 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -8361,6 +8361,17 @@ class ExprEvaluatorBase
 return false;
 }
 
+// If an assertion fails during constant evaluation, give a specific note 
explaining that
+if (FD->getName() == "__assert_fail") {
+  const Expr *AssertionExpr = E->getArg(0);
+  const StringLiteral *AssertionText = 
dyn_cast(AssertionExpr->IgnoreParens()->IgnoreParenImpCasts());
+
+  Info.FFDiag(E->getBeginLoc(), diag::note_constexpr_assert_failed)
+  << (AssertionText ? AssertionText->getString() : "");
+
+  return false;
+}
+
 SmallVector CovariantAdjustmentPath;
 if (This) {
   auto *NamedMember = dyn_cast(FD);
diff --git a/clang/test/SemaCXX/consteval_assert.cpp 
b/clang/test/SemaCXX/consteval_assert.cpp
new file mode 100644
index 0..94ca9ffd4888d
--- /dev/null
+++ b/clang/test/SemaCXX/consteval_assert.cpp
@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 -std=c++23 -verify=expected,cxx20_plus %s
+
+#ifdef __ASSERT_FUNCTION
+#undef __ASSERT_FUNCTION
+#endif
+extern "C" void __assert_fail(const char*, const char*, unsigned, const char*);
+
+#define assert(cond) \
+  ((cond) ? (void)0 : __assert_fail(#cond, __FILE__, __LINE__, __func__))
+
+consteval int square(int x) {
+  int result = x * x;
+  assert(result == 42); // expected-note {{assertion failed in consteval 
context: 'result == 42'}}
+  return result;
+}
+
+void test() {
+  auto val = square(2); // expected-note {{in call to 'square(2)'}} \
+  // expected-error {{call to consteval function 'square' is not a constant 
expression}}
+}

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


[clang] Fobbid co_await and co_yield in invalid expr context (PR #130455)

2025-03-08 Thread via cfe-commits

github-actions[bot] wrote:



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

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

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

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

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

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

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

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


[clang] Fobbid co_await and co_yield in invalid expr context (PR #130455)

2025-03-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-coroutines

Author: None (NewSigma)


Changes

Fix #78426 

C++26 introduced braced initializer lists as template arguments. However, such 
contexts should be considered invalid for co_await and co_yield. This commit 
explicitly rules out the possibility of using these exprs in template arguments.

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


1 Files Affected:

- (modified) clang/lib/Sema/SemaCoroutine.cpp (+5-2) 


``diff
diff --git a/clang/lib/Sema/SemaCoroutine.cpp b/clang/lib/Sema/SemaCoroutine.cpp
index 0e4f3b20c78cd..53536b0d14037 100644
--- a/clang/lib/Sema/SemaCoroutine.cpp
+++ b/clang/lib/Sema/SemaCoroutine.cpp
@@ -788,7 +788,11 @@ static bool checkSuspensionContext(Sema &S, SourceLocation 
Loc,
   // First emphasis of [expr.await]p2: must be a potentially evaluated context.
   // That is, 'co_await' and 'co_yield' cannot appear in subexpressions of
   // \c sizeof.
-  if (S.isUnevaluatedContext()) {
+  const auto ExprContext = S.currentEvaluationContext().ExprContext;
+  const bool BadContext =
+  S.isUnevaluatedContext() ||
+  ExprContext != Sema::ExpressionEvaluationContextRecord::EK_Other;
+  if (BadContext) {
 S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
 return false;
   }
@@ -798,7 +802,6 @@ static bool checkSuspensionContext(Sema &S, SourceLocation 
Loc,
 S.Diag(Loc, diag::err_coroutine_within_handler) << Keyword;
 return false;
   }
-
   return true;
 }
 

``




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


[clang] Fobbid co_await and co_yield in invalid expr context (PR #130455)

2025-03-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (NewSigma)


Changes

Fix #78426 

C++26 introduced braced initializer lists as template arguments. However, such 
contexts should be considered invalid for co_await and co_yield. This commit 
explicitly rules out the possibility of using these exprs in template arguments.

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


1 Files Affected:

- (modified) clang/lib/Sema/SemaCoroutine.cpp (+5-2) 


``diff
diff --git a/clang/lib/Sema/SemaCoroutine.cpp b/clang/lib/Sema/SemaCoroutine.cpp
index 0e4f3b20c78cd..53536b0d14037 100644
--- a/clang/lib/Sema/SemaCoroutine.cpp
+++ b/clang/lib/Sema/SemaCoroutine.cpp
@@ -788,7 +788,11 @@ static bool checkSuspensionContext(Sema &S, SourceLocation 
Loc,
   // First emphasis of [expr.await]p2: must be a potentially evaluated context.
   // That is, 'co_await' and 'co_yield' cannot appear in subexpressions of
   // \c sizeof.
-  if (S.isUnevaluatedContext()) {
+  const auto ExprContext = S.currentEvaluationContext().ExprContext;
+  const bool BadContext =
+  S.isUnevaluatedContext() ||
+  ExprContext != Sema::ExpressionEvaluationContextRecord::EK_Other;
+  if (BadContext) {
 S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
 return false;
   }
@@ -798,7 +802,6 @@ static bool checkSuspensionContext(Sema &S, SourceLocation 
Loc,
 S.Diag(Loc, diag::err_coroutine_within_handler) << Keyword;
 return false;
   }
-
   return true;
 }
 

``




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


[clang-tools-extra] [clangd] Add `BuiltinHeaders` flag to Config file (PR #129459)

2025-03-08 Thread Nathan Ridge via cfe-commits

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

>From 103a6843690182640d661e71517faf693c9e1c7d Mon Sep 17 00:00:00 2001
From: Khalil Estell 
Date: Sat, 1 Mar 2025 14:29:42 -0800
Subject: [PATCH 1/4] [clangd] Add `BuiltinHeaders` flag to Config file

Usage:

```
CompileFlags:
  BuiltinHeaders: QueryDriver
```

The two supported options are `QueryDriver` and `Clangd`. This Controls
whether Clangd should include its own built-in headers (like stddef.h),
or use only QueryDriver's built-in headers. Use the option value
'Clangd' (default) to use Clangd's headers, and use 'QueryDriver'
to indicate QueryDriver's headers.
---
 clang-tools-extra/clangd/Config.h |  2 +
 clang-tools-extra/clangd/ConfigCompile.cpp| 12 ++
 clang-tools-extra/clangd/ConfigFragment.h |  6 +++
 clang-tools-extra/clangd/ConfigYAML.cpp   |  4 ++
 .../clangd/SystemIncludeExtractor.cpp | 39 ---
 clang-tools-extra/docs/ReleaseNotes.rst   |  7 +++-
 6 files changed, 53 insertions(+), 17 deletions(-)

diff --git a/clang-tools-extra/clangd/Config.h 
b/clang-tools-extra/clangd/Config.h
index 586d031d58481..33718231d9b55 100644
--- a/clang-tools-extra/clangd/Config.h
+++ b/clang-tools-extra/clangd/Config.h
@@ -59,6 +59,7 @@ struct Config {
 std::optional FixedCDBPath;
   };
 
+  enum class BuiltinHeaderPolicy { Clangd, QueryDriver };
   /// Controls how the compile command for the current file is determined.
   struct {
 /// Edits to apply to the compile command, in sequence.
@@ -66,6 +67,7 @@ struct Config {
 Edits;
 /// Where to search for compilation databases for this file's flags.
 CDBSearchSpec CDBSearch = {CDBSearchSpec::Ancestors, std::nullopt};
+BuiltinHeaderPolicy BuiltinHeaders = BuiltinHeaderPolicy::Clangd;
   } CompileFlags;
 
   enum class BackgroundPolicy { Build, Skip };
diff --git a/clang-tools-extra/clangd/ConfigCompile.cpp 
b/clang-tools-extra/clangd/ConfigCompile.cpp
index aa2561e081047..31530c206acd7 100644
--- a/clang-tools-extra/clangd/ConfigCompile.cpp
+++ b/clang-tools-extra/clangd/ConfigCompile.cpp
@@ -290,6 +290,18 @@ struct FragmentCompiler {
   });
 }
 
+if (F.BuiltinHeaders) {
+  if (auto Val =
+  compileEnum("BuiltinHeaders",
+   *F.BuiltinHeaders)
+  .map("Clangd", Config::BuiltinHeaderPolicy::Clangd)
+  .map("QueryDriver", Config::BuiltinHeaderPolicy::QueryDriver)
+  .value())
+Out.Apply.push_back([Val](const Params &, Config &C) {
+  C.CompileFlags.BuiltinHeaders = *Val;
+});
+}
+
 if (F.CompilationDatabase) {
   std::optional Spec;
   if (**F.CompilationDatabase == "Ancestors") {
diff --git a/clang-tools-extra/clangd/ConfigFragment.h 
b/clang-tools-extra/clangd/ConfigFragment.h
index 9535b20253b13..c6b89cde51039 100644
--- a/clang-tools-extra/clangd/ConfigFragment.h
+++ b/clang-tools-extra/clangd/ConfigFragment.h
@@ -170,6 +170,12 @@ struct Fragment {
 /// - Ancestors: search all parent directories (the default)
 /// - std::nullopt: do not use a compilation database, just default flags.
 std::optional> CompilationDatabase;
+
+/// Controls whether Clangd should include its own built-in headers (like
+/// stddef.h), or use only the QueryDriver's built-in headers. Use the
+/// option value 'Clangd' (default) to indicate Clangd's headers, and use
+/// 'QueryDriver' to indicate QueryDriver's headers.
+std::optional> BuiltinHeaders;
   };
   CompileFlagsBlock CompileFlags;
 
diff --git a/clang-tools-extra/clangd/ConfigYAML.cpp 
b/clang-tools-extra/clangd/ConfigYAML.cpp
index 95cc5c1f9f1cf..a46d45df0d319 100644
--- a/clang-tools-extra/clangd/ConfigYAML.cpp
+++ b/clang-tools-extra/clangd/ConfigYAML.cpp
@@ -104,6 +104,10 @@ class Parser {
   if (auto Values = scalarValues(N))
 F.Remove = std::move(*Values);
 });
+Dict.handle("BuiltinHeaders", [&](Node &N) {
+  if (auto BuiltinHeaders = scalarValue(N, "BuiltinHeaders"))
+F.BuiltinHeaders = *BuiltinHeaders;
+});
 Dict.handle("CompilationDatabase", [&](Node &N) {
   F.CompilationDatabase = scalarValue(N, "CompilationDatabase");
 });
diff --git a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp 
b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
index c1c2e9fab9664..e9f4814738afb 100644
--- a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
+++ b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
@@ -30,6 +30,7 @@
 // in the paths that are explicitly included by the user.
 
 #include "CompileCommands.h"
+#include "Config.h"
 #include "GlobalCompilationDatabase.h"
 #include "support/Logger.h"
 #include "support/Threading.h"
@@ -401,22 +402,30 @@ extractSystemIncludesAndTarget(const DriverArgs 
&InputArgs,
   if (!Info)
 return std::nullopt;
 
-  // The built-in headers are tightly coupled to par

[clang] [clang][analyzer][NFC] Fix typos in comments (PR #130456)

2025-03-08 Thread Ben Shi via cfe-commits

https://github.com/benshi001 updated 
https://github.com/llvm/llvm-project/pull/130456

>From 065275c3bb8d3935d66f2b4cf7a2766bccd1 Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Thu, 20 Feb 2025 18:01:42 +0800
Subject: [PATCH] [clang][analyzer][NFC] Fix typos in comments

---
 .../Core/PathSensitive/CheckerContext.h|  6 +++---
 .../Core/PathSensitive/CoreEngine.h|  2 +-
 .../Core/PathSensitive/ExplodedGraph.h |  6 +++---
 .../Core/PathSensitive/ExprEngine.h| 18 +-
 .../Core/PathSensitive/ProgramState.h  |  5 ++---
 .../Core/PathSensitive/SMTConv.h   |  2 +-
 6 files changed, 19 insertions(+), 20 deletions(-)

diff --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
index 168983fd5cb68..bb33a6912bec7 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
@@ -7,7 +7,7 @@
 
//===--===//
 //
 //  This file defines CheckerContext that provides contextual info for
-// path-sensitive checkers.
+//  path-sensitive checkers.
 //
 
//===--===//
 
@@ -152,7 +152,7 @@ class CheckerContext {
   }
 
   /// Returns true if the value of \p E is greater than or equal to \p
-  /// Val under unsigned comparison
+  /// Val under unsigned comparison.
   bool isGreaterOrEqual(const Expr *E, unsigned long long Val);
 
   /// Returns true if the value of \p E is negative.
@@ -392,7 +392,7 @@ class CheckerContext {
   /// hardened variant that's not yet covered by it.
   static bool isHardenedVariantOf(const FunctionDecl *FD, StringRef Name);
 
-  /// Depending on wither the location corresponds to a macro, return
+  /// Depending on whether the location corresponds to a macro, return
   /// either the macro name or the token spelling.
   ///
   /// This could be useful when checkers' logic depends on whether a function
diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
index 80b79fd4e928f..b2b4e8729af25 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
@@ -156,7 +156,7 @@ class CoreEngine {
   void dispatchWorkItem(ExplodedNode* Pred, ProgramPoint Loc,
 const WorkListUnit& WU);
 
-  // Functions for external checking of whether we have unfinished work
+  // Functions for external checking of whether we have unfinished work.
   bool wasBlockAborted() const { return !blocksAborted.empty(); }
   bool wasBlocksExhausted() const { return !blocksExhausted.empty(); }
   bool hasWorkRemaining() const { return wasBlocksExhausted() ||
diff --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
index 2fb05ac46e8fa..967b25e5696f6 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
@@ -7,7 +7,7 @@
 
//===--===//
 //
 //  This file defines the template classes ExplodedNode and ExplodedGraph,
-//  which represent a path-sensitive, intra-procedural "exploded graph."
+//  which represent a path-sensitive, intra-procedural "exploded graph".
 //  See "Precise interprocedural dataflow analysis via graph reachability"
 //  by Reps, Horwitz, and Sagiv
 //  (http://portal.acm.org/citation.cfm?id=199462) for the definition of an
@@ -426,8 +426,8 @@ class ExplodedGraph {
   ///
   /// \param Nodes The nodes which must appear in the final graph. Presumably
   ///  these are end-of-path nodes (i.e. they have no successors).
-  /// \param[out] ForwardMap A optional map from nodes in this graph to nodes 
in
-  ///the returned graph.
+  /// \param[out] ForwardMap An optional map from nodes in this graph to nodes
+  ///in the returned graph.
   /// \param[out] InverseMap An optional map from nodes in the returned graph 
to
   ///nodes in this graph.
   /// \returns The trimmed graph
diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
index 804fc74b009df..5f855251b3cde 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
@@ -429,7 +429,7 @@ class ExprEngine {
 
   DataTag::Factory &getDataTags() { return Engine.getDataTags(); }
 
-  // Functions for external checking of whether we

[clang] [HLSL] select scalar overloads for vector conditions (PR #129396)

2025-03-08 Thread Chris B via cfe-commits


@@ -0,0 +1,71 @@
+//===- hlsl_intrinsic_helpers.h - HLSL helpers intrinsics 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef _HLSL_HLSL_INTRINSIC_HELPERS_H_

llvm-beanz wrote:

hlsl_detail.h is included first in hlsl.h, which makes it included before the 
other headers. These headers are all implementation details, and aren't 
expected to be exposed to user code since hlsl.h is implicitly included in all 
HLSL source files.

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


[clang] [clang][bytecode] Implement __builtin_{memchr,strchr,char_memchr} (PR #130420)

2025-03-08 Thread Timm Baeder via cfe-commits

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

llvm has recently started to use `__builitn_memchr` at compile time, so 
implement this. Still needs some work but the basics are done.

>From 956594d8c47169a9f45eb2aae03085f79d295390 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Sat, 8 Mar 2025 16:11:37 +0100
Subject: [PATCH] [clang][bytecode] Implement
 __builtin_{memchr,strchr,char_memchr}

---
 clang/lib/AST/ByteCode/InterpBuiltin.cpp  | 107 +++-
 clang/test/AST/ByteCode/builtin-functions.cpp | 118 ++
 2 files changed, 224 insertions(+), 1 deletion(-)

diff --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp 
b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index 00f99745862ee..b8c4ef2f48a79 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -1960,13 +1960,103 @@ static bool interp__builtin_memcmp(InterpState &S, 
CodePtr OpPC,
 
   // However, if we read all the available bytes but were instructed to read
   // even more, diagnose this as a "read of dereferenced one-past-the-end
-  // pointer". This is what would happen if we called CheckRead() on every 
array
+  // pointer". This is what would happen if we called CheckLoad() on every 
array
   // element.
   S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_access_past_end)
   << AK_Read << S.Current->getRange(OpPC);
   return false;
 }
 
+static bool interp__builtin_memchr(InterpState &S, CodePtr OpPC,
+   const InterpFrame *Frame,
+   const Function *Func, const CallExpr *Call) 
{
+  unsigned ID = Func->getBuiltinID();
+  if (ID == Builtin::BImemchr || ID == Builtin::BIwcschr ||
+  ID == Builtin::BIstrchr || ID == Builtin::BIwmemchr)
+diagnoseNonConstexprBuiltin(S, OpPC, ID);
+
+  const Pointer &Ptr = getParam(Frame, 0);
+  APSInt Desired;
+  std::optional MaxLength;
+  if (Call->getNumArgs() == 3) {
+MaxLength =
+peekToAPSInt(S.Stk, *S.getContext().classify(Call->getArg(2)), 0);
+Desired = peekToAPSInt(
+S.Stk, *S.getContext().classify(Call->getArg(1)),
+align(primSize(*S.getContext().classify(Call->getArg(2 +
+align(primSize(*S.getContext().classify(Call->getArg(1);
+  } else {
+Desired = peekToAPSInt(S.Stk, *S.getContext().classify(Call->getArg(1)));
+  }
+
+  if (MaxLength && MaxLength->isZero()) {
+S.Stk.push();
+return true;
+  }
+
+  if (Ptr.isDummy())
+return false;
+
+  // Null is only okay if the given size is 0.
+  if (Ptr.isZero()) {
+S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_access_null)
+<< AK_Read;
+return false;
+  }
+
+  QualType ElemTy = Ptr.getFieldDesc()->isArray()
+? Ptr.getFieldDesc()->getElemQualType()
+: Ptr.getFieldDesc()->getType();
+  bool IsRawByte = ID == Builtin::BImemchr || ID == 
Builtin::BI__builtin_memchr;
+
+  // Give up on byte-oriented matching against multibyte elements.
+  if (IsRawByte && !isOneByteCharacterType(ElemTy)) {
+S.FFDiag(S.Current->getSource(OpPC),
+ diag::note_constexpr_memchr_unsupported)
+<< S.getASTContext().BuiltinInfo.getQuotedName(ID) << ElemTy;
+return false;
+  }
+
+  if (ID == Builtin::BIstrchr || ID == Builtin::BI__builtin_strchr) {
+// strchr compares directly to the passed integer, and therefore
+// always fails if given an int that is not a char.
+if (Desired !=
+Desired.trunc(S.getASTContext().getCharWidth()).getSExtValue()) {
+  S.Stk.push();
+  return true;
+}
+  }
+
+  uint64_t DesiredVal =
+  Desired.trunc(S.getASTContext().getCharWidth()).getZExtValue();
+  bool StopAtZero =
+  (ID == Builtin::BIstrchr || ID == Builtin::BI__builtin_strchr);
+
+  size_t Index = Ptr.getIndex();
+  for (;;) {
+const Pointer &ElemPtr = Index > 0 ? Ptr.atIndex(Index) : Ptr;
+
+if (!CheckLoad(S, OpPC, ElemPtr))
+  return false;
+
+unsigned char V = static_cast(ElemPtr.deref());
+if (V == DesiredVal) {
+  S.Stk.push(ElemPtr);
+  return true;
+}
+
+if (StopAtZero && V == 0)
+  break;
+
+++Index;
+if (MaxLength && Index == MaxLength->getZExtValue())
+  break;
+  }
+
+  S.Stk.push();
+  return true;
+}
+
 bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const Function *F,
   const CallExpr *Call, uint32_t BuiltinID) {
   const InterpFrame *Frame = S.Current;
@@ -2445,6 +2535,21 @@ bool InterpretBuiltin(InterpState &S, CodePtr OpPC, 
const Function *F,
   return false;
 break;
 
+  case Builtin::BImemchr:
+  case Builtin::BI__builtin_memchr:
+  case Builtin::BIstrchr:
+  case Builtin::BI__builtin_strchr:
+#if 0
+  case Builtin::BIwcschr:
+  case Builtin::BI__builtin_wcschr:
+  case Builtin::BImemchr:
+  case Builtin::BI__builtin_wmemchr:
+#endif
+  case Builtin::BI__builtin_char_memchr:
+if (!

[clang] [clang][bytecode] Implement __builtin_{memchr,strchr,char_memchr} (PR #130420)

2025-03-08 Thread Timm Baeder via cfe-commits

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


[clang] [clang][bytecode] Surround bcp condition with Start/EndSpeculation (PR #130427)

2025-03-08 Thread Timm Baeder via cfe-commits

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

This is similar to what the current interpreter is doing - the FoldConstant 
RAII object surrounds the entire HandleConditionalOperator call, which means 
the condition and both TrueExpr or FalseExpr.

>From ad5125a082199b51bd1dca65921259c0782e0302 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Sat, 8 Mar 2025 18:09:54 +0100
Subject: [PATCH] [clang][bytecode] Surround bcp condition with
 Start/EndSpeculation

This is similar to what the current interpreter is doing - the
FoldConstant RAII object surrounds the entire HandleConditionalOperator
call, which means the condition and both TrueExpr or FalseExpr.
---
 clang/lib/AST/ByteCode/Compiler.cpp   | 19 +--
 .../test/AST/ByteCode/builtin-constant-p.cpp  |  7 ++-
 2 files changed, 15 insertions(+), 11 deletions(-)

diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index 9a52dd4105437..13b8a3b47add6 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -2309,29 +2309,36 @@ bool 
Compiler::VisitAbstractConditionalOperator(
 return visitChildExpr(FalseExpr);
   }
 
+  bool IsBcpCall = false;
+  if (const auto *CE = dyn_cast(Condition->IgnoreParenCasts());
+  CE && CE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) {
+IsBcpCall = true;
+  }
+
   LabelTy LabelEnd = this->getLabel();   // Label after the operator.
   LabelTy LabelFalse = this->getLabel(); // Label for the false expr.
 
+  if (IsBcpCall) {
+if (!this->emitStartSpeculation(E))
+  return false;
+  }
+
   if (!this->visitBool(Condition))
 return false;
-
   if (!this->jumpFalse(LabelFalse))
 return false;
-
   if (!visitChildExpr(TrueExpr))
 return false;
-
   if (!this->jump(LabelEnd))
 return false;
-
   this->emitLabel(LabelFalse);
-
   if (!visitChildExpr(FalseExpr))
 return false;
-
   this->fallthrough(LabelEnd);
   this->emitLabel(LabelEnd);
 
+  if (IsBcpCall)
+return this->emitEndSpeculation(E);
   return true;
 }
 
diff --git a/clang/test/AST/ByteCode/builtin-constant-p.cpp 
b/clang/test/AST/ByteCode/builtin-constant-p.cpp
index b309fa8296889..ed9e606ed16aa 100644
--- a/clang/test/AST/ByteCode/builtin-constant-p.cpp
+++ b/clang/test/AST/ByteCode/builtin-constant-p.cpp
@@ -59,13 +59,10 @@ template constexpr bool bcp(T t) {
 }
 
 constexpr intptr_t ptr_to_int(const void *p) {
-  return __builtin_constant_p(1) ? (intptr_t)p : (intptr_t)p; // expected-note 
{{cast that performs the conversions of a reinterpret_cast}}
+  return __builtin_constant_p(1) ? (intptr_t)p : (intptr_t)p;
 }
 
-/// This is from test/SemaCXX/builtin-constant-p.cpp, but it makes no sense.
-/// ptr_to_int is called before bcp(), so it fails. GCC does not accept this 
either.
-static_assert(bcp(ptr_to_int("foo"))); // expected-error {{not an integral 
constant expression}} \
-   // expected-note {{in call to}}
+static_assert(bcp(ptr_to_int("foo")));
 
 constexpr bool AndFold(const int &a, const int &b) {
   return __builtin_constant_p(a && b);

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


[clang] [clang][bytecode] Implement __builtin_{memchr,strchr,char_memchr} (PR #130420)

2025-03-08 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder 
`clang-aarch64-sve-vls-2stage` running on `linaro-g3-04` while building `clang` 
at step 12 "ninja check 2".

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


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

```
Step 12 (ninja check 2) failure: stage 2 checked (failure)
 TEST 'LLVM-Unit :: Support/./SupportTests/47/88' FAILED 

Script(shard):
--
GTEST_OUTPUT=json:/home/tcwg-buildbot/worker/clang-aarch64-sve-vls-2stage/stage2/unittests/Support/./SupportTests-LLVM-Unit-3194266-47-88.json
 GTEST_SHUFFLE=0 GTEST_TOTAL_SHARDS=88 GTEST_SHARD_INDEX=47 
/home/tcwg-buildbot/worker/clang-aarch64-sve-vls-2stage/stage2/unittests/Support/./SupportTests
--

Script:
--
/home/tcwg-buildbot/worker/clang-aarch64-sve-vls-2stage/stage2/unittests/Support/./SupportTests
 --gtest_filter=Caching.WriteAfterCommit
--
/home/tcwg-buildbot/worker/clang-aarch64-sve-vls-2stage/llvm/llvm/unittests/Support/Caching.cpp:110:
 Failure
Value of: llvm::detail::TakeError(CFS->commit())
Expected: succeeded
  Actual: failed  (Failed to rename temporary file 
/tmp/lit-tmp-met_qeqb/llvm_test_cache/LLVMTest-014090.tmp.o to 
/tmp/lit-tmp-met_qeqb/llvm_test_cache/llvmcache-foo: No such file or directory
)


/home/tcwg-buildbot/worker/clang-aarch64-sve-vls-2stage/llvm/llvm/unittests/Support/Caching.cpp:110
Value of: llvm::detail::TakeError(CFS->commit())
Expected: succeeded
  Actual: failed  (Failed to rename temporary file 
/tmp/lit-tmp-met_qeqb/llvm_test_cache/LLVMTest-014090.tmp.o to 
/tmp/lit-tmp-met_qeqb/llvm_test_cache/llvmcache-foo: No such file or directory
)






```



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


[clang] CodeGen: support static linking for libclosure (PR #125384)

2025-03-08 Thread Balazs Benics via cfe-commits

steakhal wrote:

> @steakhal bleh, is the "New Features" a sub item of "Static Analyzer"?

Ah you are right. Its at the right place. Nvm.

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


[clang] 46d218d - [clang][bytecode] Implement __builtin_{memchr,strchr,char_memchr} (#130420)

2025-03-08 Thread via cfe-commits

Author: Timm Baeder
Date: 2025-03-08T16:52:06+01:00
New Revision: 46d218d1af5d285a646a1e5d3be6a43940fb4a9d

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

LOG: [clang][bytecode] Implement __builtin_{memchr,strchr,char_memchr} (#130420)

llvm has recently started to use `__builitn_memchr` at compile time, so
implement this. Still needs some work but the basics are done.

Added: 


Modified: 
clang/lib/AST/ByteCode/InterpBuiltin.cpp
clang/test/AST/ByteCode/builtin-functions.cpp

Removed: 




diff  --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp 
b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index 00f99745862ee..b8c4ef2f48a79 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -1960,13 +1960,103 @@ static bool interp__builtin_memcmp(InterpState &S, 
CodePtr OpPC,
 
   // However, if we read all the available bytes but were instructed to read
   // even more, diagnose this as a "read of dereferenced one-past-the-end
-  // pointer". This is what would happen if we called CheckRead() on every 
array
+  // pointer". This is what would happen if we called CheckLoad() on every 
array
   // element.
   S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_access_past_end)
   << AK_Read << S.Current->getRange(OpPC);
   return false;
 }
 
+static bool interp__builtin_memchr(InterpState &S, CodePtr OpPC,
+   const InterpFrame *Frame,
+   const Function *Func, const CallExpr *Call) 
{
+  unsigned ID = Func->getBuiltinID();
+  if (ID == Builtin::BImemchr || ID == Builtin::BIwcschr ||
+  ID == Builtin::BIstrchr || ID == Builtin::BIwmemchr)
+diagnoseNonConstexprBuiltin(S, OpPC, ID);
+
+  const Pointer &Ptr = getParam(Frame, 0);
+  APSInt Desired;
+  std::optional MaxLength;
+  if (Call->getNumArgs() == 3) {
+MaxLength =
+peekToAPSInt(S.Stk, *S.getContext().classify(Call->getArg(2)), 0);
+Desired = peekToAPSInt(
+S.Stk, *S.getContext().classify(Call->getArg(1)),
+align(primSize(*S.getContext().classify(Call->getArg(2 +
+align(primSize(*S.getContext().classify(Call->getArg(1);
+  } else {
+Desired = peekToAPSInt(S.Stk, *S.getContext().classify(Call->getArg(1)));
+  }
+
+  if (MaxLength && MaxLength->isZero()) {
+S.Stk.push();
+return true;
+  }
+
+  if (Ptr.isDummy())
+return false;
+
+  // Null is only okay if the given size is 0.
+  if (Ptr.isZero()) {
+S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_access_null)
+<< AK_Read;
+return false;
+  }
+
+  QualType ElemTy = Ptr.getFieldDesc()->isArray()
+? Ptr.getFieldDesc()->getElemQualType()
+: Ptr.getFieldDesc()->getType();
+  bool IsRawByte = ID == Builtin::BImemchr || ID == 
Builtin::BI__builtin_memchr;
+
+  // Give up on byte-oriented matching against multibyte elements.
+  if (IsRawByte && !isOneByteCharacterType(ElemTy)) {
+S.FFDiag(S.Current->getSource(OpPC),
+ diag::note_constexpr_memchr_unsupported)
+<< S.getASTContext().BuiltinInfo.getQuotedName(ID) << ElemTy;
+return false;
+  }
+
+  if (ID == Builtin::BIstrchr || ID == Builtin::BI__builtin_strchr) {
+// strchr compares directly to the passed integer, and therefore
+// always fails if given an int that is not a char.
+if (Desired !=
+Desired.trunc(S.getASTContext().getCharWidth()).getSExtValue()) {
+  S.Stk.push();
+  return true;
+}
+  }
+
+  uint64_t DesiredVal =
+  Desired.trunc(S.getASTContext().getCharWidth()).getZExtValue();
+  bool StopAtZero =
+  (ID == Builtin::BIstrchr || ID == Builtin::BI__builtin_strchr);
+
+  size_t Index = Ptr.getIndex();
+  for (;;) {
+const Pointer &ElemPtr = Index > 0 ? Ptr.atIndex(Index) : Ptr;
+
+if (!CheckLoad(S, OpPC, ElemPtr))
+  return false;
+
+unsigned char V = static_cast(ElemPtr.deref());
+if (V == DesiredVal) {
+  S.Stk.push(ElemPtr);
+  return true;
+}
+
+if (StopAtZero && V == 0)
+  break;
+
+++Index;
+if (MaxLength && Index == MaxLength->getZExtValue())
+  break;
+  }
+
+  S.Stk.push();
+  return true;
+}
+
 bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const Function *F,
   const CallExpr *Call, uint32_t BuiltinID) {
   const InterpFrame *Frame = S.Current;
@@ -2445,6 +2535,21 @@ bool InterpretBuiltin(InterpState &S, CodePtr OpPC, 
const Function *F,
   return false;
 break;
 
+  case Builtin::BImemchr:
+  case Builtin::BI__builtin_memchr:
+  case Builtin::BIstrchr:
+  case Builtin::BI__builtin_strchr:
+#if 0
+  case Builtin::BIwcschr:
+  case Builtin::BI__builtin_wcschr:
+  case Builtin::BImemchr:
+  case Builtin:

[clang] [clang][bytecode] Surround bcp condition with Start/EndSpeculation (PR #130427)

2025-03-08 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `llvm-clang-x86_64-sie-win` 
running on `sie-win-worker` while building `clang` at step 7 
"test-build-unified-tree-check-all".

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


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

```
Step 7 (test-build-unified-tree-check-all) failure: test (failure)
 TEST 'LLVM-Unit :: Support/./SupportTests.exe/6/44' FAILED 

Script(shard):
--
GTEST_OUTPUT=json:Z:\b\llvm-clang-x86_64-sie-win\build\unittests\Support\.\SupportTests.exe-LLVM-Unit-11736-6-44.json
 GTEST_SHUFFLE=0 GTEST_TOTAL_SHARDS=44 GTEST_SHARD_INDEX=6 
Z:\b\llvm-clang-x86_64-sie-win\build\unittests\Support\.\SupportTests.exe
--

Script:
--
Z:\b\llvm-clang-x86_64-sie-win\build\unittests\Support\.\SupportTests.exe 
--gtest_filter=Caching.NoCommit
--
Z:\b\llvm-clang-x86_64-sie-win\llvm-project\llvm\unittests\Support\Caching.cpp(142):
 error: Value of: AddStream
  Actual: false
Expected: true


Z:\b\llvm-clang-x86_64-sie-win\llvm-project\llvm\unittests\Support\Caching.cpp:142
Value of: AddStream
  Actual: false
Expected: true






```



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


[clang] [clang][bytecode] Surround bcp condition with Start/EndSpeculation (PR #130427)

2025-03-08 Thread Timm Baeder via cfe-commits

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


[clang] Improve the -Wundefined-func-template diagnostic note for invisible template functions (PR #129031)

2025-03-08 Thread Shafik Yaghmour via cfe-commits


@@ -759,13 +759,11 @@ Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
   TemplateArgs);
 }
 
-bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
-  NamedDecl *Instantiation,
-  bool InstantiatedFromMember,
-  const NamedDecl *Pattern,
-  const NamedDecl *PatternDef,
-  TemplateSpecializationKind TSK,
-  bool Complain /*= true*/) {
+bool Sema::DiagnoseUninstantiableTemplate(
+SourceLocation PointOfInstantiation, NamedDecl *Instantiation,
+bool InstantiatedFromMember, const NamedDecl *Pattern,
+const NamedDecl *PatternDef, TemplateSpecializationKind TSK,
+bool Complain /*= true*/, bool *Unreachable) {

shafik wrote:

@AaronBallman I don't think I have seen annotation before, annotating the 
default value in a function definition.

Are there tools that verify this like we have for [argument 
comments?](https://clang.llvm.org/extra/clang-tidy/checks/bugprone/argument-comment.html)
 

Otherwise I don't think these make as much sense, although I sympathize with 
the sentiment behind them. 

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


[clang] [clang][modules][deps] Add mutex as an alternative to file lock (PR #129751)

2025-03-08 Thread Michael Spencer via cfe-commits


@@ -0,0 +1,31 @@
+#ifndef LLVM_CLANG_SERIALIZATION_MODULECACHELOCK_H
+#define LLVM_CLANG_SERIALIZATION_MODULECACHELOCK_H
+
+#include "clang/Basic/LLVM.h"
+#include "llvm/Support/LockFileManager.h"
+
+namespace clang {
+enum class LockResult { Owned, Shared, Error };
+enum class WaitForUnlockResult { Success, OwnerDied, Timeout };
+
+class ModuleCacheLockManager {
+public:
+  virtual operator LockResult() const = 0;
+  virtual WaitForUnlockResult waitForUnlock() = 0;
+  virtual void unsafeRemoveLock() = 0;
+  virtual std::string getErrorMessage() const = 0;
+  virtual ~ModuleCacheLockManager() = default;
+};
+
+class ModuleCacheLock {
+public:
+  virtual void prepareLock(StringRef ModuleFilename) = 0;
+  virtual std::unique_ptr
+  tryLock(StringRef ModuleFilename) = 0;
+  virtual ~ModuleCacheLock() = default;
+};

Bigcheese wrote:

Hmm, `ModuleCacheLockManager` is basically the same interface, and the enums 
are the same. I do think it makes sense to have that part in llvm/Support. I 
think the `ModuleCacheLock` should stay in Clang though.

It would also be nice to modernize the interface (particularly `std::string 
getErrorMessage()`), but I think that can happen separately.

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


[clang] [SPARC][Driver] Set correct IAS mode defaults for Linux and Free/OpenBSD (PR #130108)

2025-03-08 Thread Kurt Miller via cfe-commits

bsdkurt wrote:

I back ported this to llvm 19 and confirm it works to set VIS by default on 
OpenBSD. Thanks for the fix.

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


[clang] [llvm] [alpha.webkit.UnretainedLambdaCapturesChecker] Add a WebKit checker for lambda capturing NS or CF types. (PR #128651)

2025-03-08 Thread Rashmi Mudduluru via cfe-commits


@@ -3487,6 +3487,18 @@ Raw pointers and references to an object which supports 
CheckedPtr or CheckedRef
 
 See `WebKit Guidelines for Safer C++ Programming 
`_ for details.
 
+alpha.webkit.UnretainedLambdaCapturesChecker
+
+Raw pointers and references to unretained types can't be captured in lambdas. 
Only RetainPtr is allowed.

t-rasmud wrote:

Add a note about what happens when ARC is enabled.

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


[clang] [llvm] [alpha.webkit.UnretainedLambdaCapturesChecker] Add a WebKit checker for lambda capturing NS or CF types. (PR #128651)

2025-03-08 Thread Rashmi Mudduluru via cfe-commits


@@ -0,0 +1,296 @@
+// RUN: %clang_analyze_cc1 
-analyzer-checker=alpha.webkit.UnretainedLambdaCapturesChecker -verify %s
+
+#include "objc-mock-types.h"
+
+namespace std {
+
+template 
+class unique_ptr {
+private:
+  T *t;
+
+public:
+  unique_ptr() : t(nullptr) { }
+  unique_ptr(T *t) : t(t) { }
+  ~unique_ptr() {
+if (t)
+  delete t;
+  }
+  template  unique_ptr(unique_ptr&& u)
+: t(u.t)
+  {
+u.t = nullptr;
+  }
+  T *get() const { return t; }
+  T *operator->() const { return t; }
+  T &operator*() const { return *t; }
+  unique_ptr &operator=(T *) { return *this; }
+  explicit operator bool() const { return !!t; }
+};
+
+};
+
+namespace WTF {
+
+namespace Detail {
+
+template
+class CallableWrapperBase {
+public:
+virtual ~CallableWrapperBase() { }
+virtual Out call(In...) = 0;
+};
+
+template class CallableWrapper;
+
+template
+class CallableWrapper : public CallableWrapperBase {
+public:
+explicit CallableWrapper(CallableType& callable)
+: m_callable(callable) { }
+Out call(In... in) final { return m_callable(in...); }
+
+private:
+CallableType m_callable;
+};
+
+} // namespace Detail
+
+template class Function;
+
+template Function 
adopt(Detail::CallableWrapperBase*);
+
+template 
+class Function {
+public:
+using Impl = Detail::CallableWrapperBase;
+
+Function() = default;
+
+template
+Function(FunctionType f)
+: m_callableWrapper(new Detail::CallableWrapper(f)) { }
+
+Out operator()(In... in) const { return m_callableWrapper->call(in...); }
+explicit operator bool() const { return !!m_callableWrapper; }
+
+private:
+enum AdoptTag { Adopt };
+Function(Impl* impl, AdoptTag)
+: m_callableWrapper(impl)
+{
+}
+
+friend Function adopt(Impl*);
+
+std::unique_ptr m_callableWrapper;
+};
+
+template Function 
adopt(Detail::CallableWrapperBase* impl)
+{
+return Function(impl, Function::Adopt);
+}
+
+template 
+class HashMap {
+public:
+  HashMap();
+  HashMap([[clang::noescape]] const Function&);
+  void ensure(const KeyType&, [[clang::noescape]] const 
Function&);
+  bool operator+([[clang::noescape]] const Function&) const;
+  static void ifAny(HashMap, [[clang::noescape]] const 
Function&);
+
+private:
+  ValueType* m_table { nullptr };
+};
+
+} // namespace WTF
+
+struct A {
+  static void b();
+};
+
+SomeObj* make_obj();
+CFMutableArrayRef make_cf();
+
+void someFunction();
+template  void call(Callback callback) {
+  someFunction();
+  callback();
+}
+void callAsync(const WTF::Function&);
+
+void raw_ptr() {
+  SomeObj* obj = make_obj();
+  auto foo1 = [obj](){
+// expected-warning@-1{{Captured raw-pointer 'obj' to unretained type is 
unsafe [alpha.webkit.UnretainedLambdaCapturesChecker]}}
+[obj doWork];
+  };
+  call(foo1);
+
+  auto foo2 = [&obj](){
+// expected-warning@-1{{Captured raw-pointer 'obj' to unretained type is 
unsafe [alpha.webkit.UnretainedLambdaCapturesChecker]}}
+[obj doWork];
+  };
+  auto foo3 = [&](){
+[obj doWork];
+// expected-warning@-1{{Implicitly captured raw-pointer 'obj' to 
unretained type is unsafe [alpha.webkit.UnretainedLambdaCapturesChecker]}}
+obj = nullptr;
+  };
+  auto foo4 = [=](){
+[obj doWork];
+// expected-warning@-1{{Implicitly captured raw-pointer 'obj' to 
unretained type is unsafe [alpha.webkit.UnretainedLambdaCapturesChecker]}}
+  };
+  
+  auto cf = make_cf();
+  auto bar1 = [cf](){
+// expected-warning@-1{{Captured reference 'cf' to unretained type is 
unsafe [alpha.webkit.UnretainedLambdaCapturesChecker]}}
+CFArrayAppendValue(cf, nullptr);
+  };
+  auto bar2 = [&cf](){
+// expected-warning@-1{{Captured reference 'cf' to unretained type is 
unsafe [alpha.webkit.UnretainedLambdaCapturesChecker]}}
+CFArrayAppendValue(cf, nullptr);
+  };
+  auto bar3 = [&](){
+CFArrayAppendValue(cf, nullptr);
+// expected-warning@-1{{Implicitly captured reference 'cf' to unretained 
type is unsafe [alpha.webkit.UnretainedLambdaCapturesChecker]}}
+cf = nullptr;
+  };
+  auto bar4 = [=](){
+CFArrayAppendValue(cf, nullptr);
+// expected-warning@-1{{Implicitly captured reference 'cf' to unretained 
type is unsafe [alpha.webkit.UnretainedLambdaCapturesChecker]}}
+  };
+
+  call(foo1);
+  call(foo2);
+  call(foo3);
+  call(foo4);
+
+  call(bar1);
+  call(bar2);
+  call(bar3);
+  call(bar4);
+
+  // Confirm that the checker respects [[clang::suppress]].
+  SomeObj* suppressed_obj = nullptr;
+  [[clang::suppress]] auto foo5 = [suppressed_obj](){
+[suppressed_obj doWork];
+  };
+  // no warning.
+  call(foo5);
+
+  // Confirm that the checker respects [[clang::suppress]].
+  CFMutableArrayRef suppressed_cf = nullptr;
+  [[clang::suppress]] auto bar5 = [suppressed_cf](){
+CFArrayAppendValue(suppressed_cf, nullptr);
+  };
+  // no warning.
+  call(bar5);
+}
+
+void quiet() {
+// This code is not expected to trigger any warnings.
+  SomeObj *obj;
+
+  auto foo3 = [&]() {};
+  a

[clang] [llvm] [alpha.webkit.UnretainedLambdaCapturesChecker] Add a WebKit checker for lambda capturing NS or CF types. (PR #128651)

2025-03-08 Thread Rashmi Mudduluru via cfe-commits

https://github.com/t-rasmud approved this pull request.

LGTM!

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


[clang] [HLSL][Driver] Use temporary files correctly (PR #130436)

2025-03-08 Thread Justin Bogner via cfe-commits

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


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


[clang] [clang] fix matching of nested template template parameters (PR #130447)

2025-03-08 Thread Matheus Izvekov via cfe-commits

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

When checking the template template parameters of template template parameters, 
the PartialOrdering context was not correctly propagated.

This also has a few drive-by fixes, such as checking the template parameter 
lists of template template parameters, which was previously missing and would 
have been it's own bug, but we need to fix it in order to prevent crashes in 
error recovery in a simple way.

Fixes #130362

>From f83e8284a308f6946ee5569d2ebe3c37bae91a86 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Sat, 8 Mar 2025 20:32:14 -0300
Subject: [PATCH] [clang] fix matching of nested template template parameters

When checking the template template parameters of template template
parameters, the PartialOrdering context was not correctly propagated.

This also has a few drive-by fixes, such as checking the template parameter
lists of template template parameters, which was previously missing and
would have been it's own bug, but we need to fix it in order to
prevent crashes in error recovery in a simple way.

Fixes #130362
---
 clang/docs/ReleaseNotes.rst   |  7 ++--
 clang/include/clang/Sema/Sema.h   |  9 +++--
 clang/lib/Sema/SemaDecl.cpp   |  2 +-
 clang/lib/Sema/SemaDeclCXX.cpp|  2 +-
 clang/lib/Sema/SemaTemplate.cpp   | 36 ---
 clang/lib/Sema/SemaTemplateDeduction.cpp  | 16 +
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  |  2 +-
 clang/test/SemaTemplate/cwg2398.cpp   | 17 -
 .../SemaTemplate/temp_arg_template_p0522.cpp  |  3 +-
 clang/unittests/AST/DeclPrinterTest.cpp   | 16 -
 10 files changed, 64 insertions(+), 46 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7859871b0493a..d6627d21e5e3d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -161,8 +161,8 @@ related warnings within the method body.
   ``__attribute__((model("large")))`` on non-TLS globals in x86-64 
compilations.
   This forces the global to be considered small or large in regards to the
   x86-64 code model, regardless of the code model specified for the 
compilation.
-- Clang now emits a warning ``-Wreserved-init-priority`` instead of a hard 
error 
-  when ``__attribute__((init_priority(n)))`` is used with values of n in the 
+- Clang now emits a warning ``-Wreserved-init-priority`` instead of a hard 
error
+  when ``__attribute__((init_priority(n)))`` is used with values of n in the
   reserved range [0, 100]. The warning will be treated as an error by default.
 
 - There is a new ``format_matches`` attribute to complement the existing
@@ -294,6 +294,9 @@ Bug Fixes to C++ Support
   direct-list-initialized from an array is corrected to direct-initialization.
 - Clang no longer crashes when a coroutine is declared ``[[noreturn]]``. 
(#GH127327)
 - Clang now uses the parameter location for abbreviated function templates in 
``extern "C"``. (#GH46386)
+- Fixes matching of nested template template parameters. (#GH130362)
+- Correctly diagnoses template template paramters which have a pack parameter
+  not in the last position.
 
 Improvements to C++ diagnostics
 ^^^
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index fdef57e84ee3d..9d26df7075c80 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -11363,14 +11363,17 @@ class Sema final : public SemaBase {
 
   /// The context in which we are checking a template parameter list.
   enum TemplateParamListContext {
-TPC_ClassTemplate,
-TPC_VarTemplate,
+// For this context, Class, Variable, TypeAlias, and non-pack Template
+// Template
+// Parameters are the same.
+TPC_Normal,
+
 TPC_FunctionTemplate,
 TPC_ClassTemplateMember,
 TPC_FriendClassTemplate,
 TPC_FriendFunctionTemplate,
 TPC_FriendFunctionTemplateDefinition,
-TPC_TypeAliasTemplate
+TPC_TemplateTemplateParameterPack
   };
 
   /// Checks the validity of a template parameter list, possibly
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 5716eb61d4ae8..01f44de589fb8 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -8165,7 +8165,7 @@ NamedDecl *Sema::ActOnVariableDeclarator(
   (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
DC->isDependentContext())
   ? TPC_ClassTemplateMember
-  : TPC_VarTemplate))
+  : TPC_Normal))
 NewVD->setInvalidDecl();
 
   // If we are providing an explicit specialization of a static variable
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index fd5f0443fa894..bcd29c95c2ca4 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -13586,7 +13586,7 @@ Decl *Sema::A

[clang] [clang] fix matching of nested template template parameters (PR #130447)

2025-03-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Matheus Izvekov (mizvekov)


Changes

When checking the template template parameters of template template parameters, 
the PartialOrdering context was not correctly propagated.

This also has a few drive-by fixes, such as checking the template parameter 
lists of template template parameters, which was previously missing and would 
have been it's own bug, but we need to fix it in order to prevent crashes in 
error recovery in a simple way.

Fixes #130362

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


10 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+5-2) 
- (modified) clang/include/clang/Sema/Sema.h (+6-3) 
- (modified) clang/lib/Sema/SemaDecl.cpp (+1-1) 
- (modified) clang/lib/Sema/SemaDeclCXX.cpp (+1-1) 
- (modified) clang/lib/Sema/SemaTemplate.cpp (+24-12) 
- (modified) clang/lib/Sema/SemaTemplateDeduction.cpp (+9-7) 
- (modified) clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (+1-1) 
- (modified) clang/test/SemaTemplate/cwg2398.cpp (+7-10) 
- (modified) clang/test/SemaTemplate/temp_arg_template_p0522.cpp (+2-1) 
- (modified) clang/unittests/AST/DeclPrinterTest.cpp (+8-8) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7859871b0493a..d6627d21e5e3d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -161,8 +161,8 @@ related warnings within the method body.
   ``__attribute__((model("large")))`` on non-TLS globals in x86-64 
compilations.
   This forces the global to be considered small or large in regards to the
   x86-64 code model, regardless of the code model specified for the 
compilation.
-- Clang now emits a warning ``-Wreserved-init-priority`` instead of a hard 
error 
-  when ``__attribute__((init_priority(n)))`` is used with values of n in the 
+- Clang now emits a warning ``-Wreserved-init-priority`` instead of a hard 
error
+  when ``__attribute__((init_priority(n)))`` is used with values of n in the
   reserved range [0, 100]. The warning will be treated as an error by default.
 
 - There is a new ``format_matches`` attribute to complement the existing
@@ -294,6 +294,9 @@ Bug Fixes to C++ Support
   direct-list-initialized from an array is corrected to direct-initialization.
 - Clang no longer crashes when a coroutine is declared ``[[noreturn]]``. 
(#GH127327)
 - Clang now uses the parameter location for abbreviated function templates in 
``extern "C"``. (#GH46386)
+- Fixes matching of nested template template parameters. (#GH130362)
+- Correctly diagnoses template template paramters which have a pack parameter
+  not in the last position.
 
 Improvements to C++ diagnostics
 ^^^
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index fdef57e84ee3d..9d26df7075c80 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -11363,14 +11363,17 @@ class Sema final : public SemaBase {
 
   /// The context in which we are checking a template parameter list.
   enum TemplateParamListContext {
-TPC_ClassTemplate,
-TPC_VarTemplate,
+// For this context, Class, Variable, TypeAlias, and non-pack Template
+// Template
+// Parameters are the same.
+TPC_Normal,
+
 TPC_FunctionTemplate,
 TPC_ClassTemplateMember,
 TPC_FriendClassTemplate,
 TPC_FriendFunctionTemplate,
 TPC_FriendFunctionTemplateDefinition,
-TPC_TypeAliasTemplate
+TPC_TemplateTemplateParameterPack
   };
 
   /// Checks the validity of a template parameter list, possibly
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 5716eb61d4ae8..01f44de589fb8 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -8165,7 +8165,7 @@ NamedDecl *Sema::ActOnVariableDeclarator(
   (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
DC->isDependentContext())
   ? TPC_ClassTemplateMember
-  : TPC_VarTemplate))
+  : TPC_Normal))
 NewVD->setInvalidDecl();
 
   // If we are providing an explicit specialization of a static variable
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index fd5f0443fa894..bcd29c95c2ca4 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -13586,7 +13586,7 @@ Decl *Sema::ActOnAliasDeclaration(Scope *S, 
AccessSpecifier AS,
 // Merge any previous default template arguments into our parameters,
 // and check the parameter list.
 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
-   TPC_TypeAliasTemplate))
+   TPC_Normal))
   return nullptr;
 
 TypeAliasTemplateDecl *NewDecl =
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 0caabc6573361..2c44bbe1e0f34 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/S

[clang-tools-extra] 85d60a4 - [clangd] Add `BuiltinHeaders` config option (#129459)

2025-03-08 Thread via cfe-commits

Author: Khalil Estell
Date: 2025-03-08T19:16:37-05:00
New Revision: 85d60a441ab810e25605fb4555971b1d0a996e5c

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

LOG: [clangd] Add `BuiltinHeaders` config option (#129459)

This option, under `CompileFlags`, governs whether clangd uses its own
built-in headers (`Clangd` option value) or the built-in headers of the driver
in the file's compile command (`QueryDriver` option value, applicable to
cases where `--query-driver` is used to instruct clangd to ask the driver
for its system include paths).

The default value is `Clangd`, preserving clangd's current defaut behaviour.

Fixes clangd/clangd#2074

Added: 


Modified: 
clang-tools-extra/clangd/Config.h
clang-tools-extra/clangd/ConfigCompile.cpp
clang-tools-extra/clangd/ConfigFragment.h
clang-tools-extra/clangd/ConfigYAML.cpp
clang-tools-extra/clangd/SystemIncludeExtractor.cpp
clang-tools-extra/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang-tools-extra/clangd/Config.h 
b/clang-tools-extra/clangd/Config.h
index 586d031d58481..3f8a3c9b060f6 100644
--- a/clang-tools-extra/clangd/Config.h
+++ b/clang-tools-extra/clangd/Config.h
@@ -59,6 +59,7 @@ struct Config {
 std::optional FixedCDBPath;
   };
 
+  enum class BuiltinHeaderPolicy { Clangd, QueryDriver };
   /// Controls how the compile command for the current file is determined.
   struct {
 /// Edits to apply to the compile command, in sequence.
@@ -66,6 +67,10 @@ struct Config {
 Edits;
 /// Where to search for compilation databases for this file's flags.
 CDBSearchSpec CDBSearch = {CDBSearchSpec::Ancestors, std::nullopt};
+
+/// Whether to use clangd's own builtin headers, or ones from the system
+/// include extractor, if available.
+BuiltinHeaderPolicy BuiltinHeaders = BuiltinHeaderPolicy::Clangd;
   } CompileFlags;
 
   enum class BackgroundPolicy { Build, Skip };

diff  --git a/clang-tools-extra/clangd/ConfigCompile.cpp 
b/clang-tools-extra/clangd/ConfigCompile.cpp
index aa2561e081047..31530c206acd7 100644
--- a/clang-tools-extra/clangd/ConfigCompile.cpp
+++ b/clang-tools-extra/clangd/ConfigCompile.cpp
@@ -290,6 +290,18 @@ struct FragmentCompiler {
   });
 }
 
+if (F.BuiltinHeaders) {
+  if (auto Val =
+  compileEnum("BuiltinHeaders",
+   *F.BuiltinHeaders)
+  .map("Clangd", Config::BuiltinHeaderPolicy::Clangd)
+  .map("QueryDriver", Config::BuiltinHeaderPolicy::QueryDriver)
+  .value())
+Out.Apply.push_back([Val](const Params &, Config &C) {
+  C.CompileFlags.BuiltinHeaders = *Val;
+});
+}
+
 if (F.CompilationDatabase) {
   std::optional Spec;
   if (**F.CompilationDatabase == "Ancestors") {

diff  --git a/clang-tools-extra/clangd/ConfigFragment.h 
b/clang-tools-extra/clangd/ConfigFragment.h
index 9535b20253b13..6f95474b9c008 100644
--- a/clang-tools-extra/clangd/ConfigFragment.h
+++ b/clang-tools-extra/clangd/ConfigFragment.h
@@ -170,6 +170,14 @@ struct Fragment {
 /// - Ancestors: search all parent directories (the default)
 /// - std::nullopt: do not use a compilation database, just default flags.
 std::optional> CompilationDatabase;
+
+/// Controls whether Clangd should use its own built-in system headers 
(like
+/// stddef.h), or use the system headers from the query driver. Use the
+/// option value 'Clangd' (default) to indicate Clangd's headers, and use
+/// 'QueryDriver' to indicate QueryDriver's headers. `Clangd` is the
+/// fallback if no query driver is supplied or if the query driver regex
+/// string fails to match the compiler used in the CDB.
+std::optional> BuiltinHeaders;
   };
   CompileFlagsBlock CompileFlags;
 

diff  --git a/clang-tools-extra/clangd/ConfigYAML.cpp 
b/clang-tools-extra/clangd/ConfigYAML.cpp
index 95cc5c1f9f1cf..a46d45df0d319 100644
--- a/clang-tools-extra/clangd/ConfigYAML.cpp
+++ b/clang-tools-extra/clangd/ConfigYAML.cpp
@@ -104,6 +104,10 @@ class Parser {
   if (auto Values = scalarValues(N))
 F.Remove = std::move(*Values);
 });
+Dict.handle("BuiltinHeaders", [&](Node &N) {
+  if (auto BuiltinHeaders = scalarValue(N, "BuiltinHeaders"))
+F.BuiltinHeaders = *BuiltinHeaders;
+});
 Dict.handle("CompilationDatabase", [&](Node &N) {
   F.CompilationDatabase = scalarValue(N, "CompilationDatabase");
 });

diff  --git a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp 
b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
index c1c2e9fab9664..9399b910025b6 100644
--- a/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
+++ b/clang-tools-extra/clangd/SystemIncludeExtractor.cpp
@@

[clang-tools-extra] [clangd] Add `BuiltinHeaders` flag to Config file (PR #129459)

2025-03-08 Thread via cfe-commits

github-actions[bot] wrote:



@kammce Congratulations on having your first Pull Request (PR) merged into the 
LLVM Project!

Your changes will be combined with recent changes from other authors, then 
tested by our [build bots](https://lab.llvm.org/buildbot/). If there is a 
problem with a build, you may receive a report in an email or a comment on this 
PR.

Please check whether problems have been caused by your change specifically, as 
the builds can include changes from many authors. It is not uncommon for your 
change to be included in a build that fails due to someone else's changes, or 
infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail 
[here](https://llvm.org/docs/MyFirstTypoFix.html#myfirsttypofix-issues-after-landing-your-pr).

If your change does cause a problem, it may be reverted, or you can revert it 
yourself. This is a normal part of [LLVM 
development](https://llvm.org/docs/DeveloperPolicy.html#patch-reversion-policy).
 You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are 
working as expected, well done!


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


[clang-tools-extra] [clangd] Add `BuiltinHeaders` flag to Config file (PR #129459)

2025-03-08 Thread Nathan Ridge via cfe-commits

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


[clang-tools-extra] [clangd] Add `BuiltinHeaders` flag to Config file (PR #129459)

2025-03-08 Thread Nathan Ridge via cfe-commits

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

Thanks!

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


[clang-tools-extra] [clang-tidy] Avoid processing declarations in system headers (PR #128150)

2025-03-08 Thread Carlos Galvez via cfe-commits
Carlos =?utf-8?q?Gálvez?= ,
Carlos =?utf-8?q?Gálvez?= 
Message-ID:
In-Reply-To: 


carlosgalvezp wrote:

Thank you for the discussion, I'm okey with changing the code based on the 
feedback, namely: 

- move the logic to ASTMatchers, off by default
- clang tidy actively enables it
- document technical debt with FIXME/GH ticket

> Properly update the documentation and changelog

I did that in the release notes. It's there anything else you believe is 
missing? I will update the AST documentation accordingly as well.

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


[clang] [HLSL] Add "or" intrinsic (PR #128979)

2025-03-08 Thread Farzon Lotfi via cfe-commits

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


[clang] Better diagnostics when assertion fails in `consteval` (PR #130458)

2025-03-08 Thread via cfe-commits

github-actions[bot] wrote:



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

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

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

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

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

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

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

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


[clang] [clang][CodeComplete] Add code completion for if constexpr and consteval (PR #124315)

2025-03-08 Thread Nathan Ridge via cfe-commits


@@ -6749,6 +6749,21 @@ void SemaCodeCompletion::CodeCompleteInitializer(Scope 
*S, Decl *D) {
   CodeCompleteExpression(S, Data);
 }
 
+void SemaCodeCompletion::CodeCompleteIfConstExpr(Scope *S) const {
+  ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
+CodeCompleter->getCodeCompletionTUInfo(),
+CodeCompletionContext::CCC_SymbolOrNewName);
+  Results.EnterNewScope();

HighCommander4 wrote:

I agree with @zyn0217. I looked at what `EnterNewScope()` does and it seems to 
be related to names/declarations, and thus not applicable if all the results we 
add are keywords or patterns with no associated declarations.

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


[clang] [clang][bytecode][NFC] Bail out on non constant evaluated builtins (PR #130431)

2025-03-08 Thread Timm Baeder via cfe-commits

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


[clang] [clang][CodeComplete] Add code completion for if constexpr and consteval (PR #124315)

2025-03-08 Thread Nathan Ridge via cfe-commits

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

Thanks! I tried out the patch with clangd and it seems to be working pretty 
well.

A further enhancement that occurs to me is that we could offer these patterns 
slightly earlier, e.g. when you're at the beginning of an empty line and invoke 
code completion and then type `if` to filter the results, you see the `if 
(condition) {statements}` pattern as the first result -- we could have `if 
constexpr (condition) {statements}` as another result there already. But that 
can be a future enhancement for another time.

The implementation looks pretty good, just have some minor comments.

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


[clang-tools-extra] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init check (PR #129370)

2025-03-08 Thread David Rivera via cfe-commits

https://github.com/RiverDave updated 
https://github.com/llvm/llvm-project/pull/129370

>From e3c5641ee3a398d8fe12c0dcd030ee84667cc86e Mon Sep 17 00:00:00 2001
From: David Rivera 
Date: Sat, 1 Mar 2025 02:09:02 -0500
Subject: [PATCH] [clang-tidy] detect arithmetic operations within member list
 initialization in modernize-use-default-member-init

---
 .../modernize/UseDefaultMemberInitCheck.cpp   | 27 +--
 clang-tools-extra/docs/ReleaseNotes.rst   |  6 -
 .../modernize/use-default-member-init.cpp | 26 ++
 3 files changed, 50 insertions(+), 9 deletions(-)

diff --git 
a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
index 6c06b0af342f6..8b0d499a96811 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
@@ -159,6 +159,13 @@ static bool sameValue(const Expr *E1, const Expr *E2) {
   case Stmt::UnaryOperatorClass:
 return sameValue(cast(E1)->getSubExpr(),
  cast(E2)->getSubExpr());
+  case Stmt::BinaryOperatorClass: {
+const auto *BinOp1 = cast(E1);
+const auto *BinOp2 = cast(E2);
+return sameValue(BinOp1->getLHS(), BinOp2->getLHS()) &&
+   sameValue(BinOp1->getRHS(), BinOp2->getRHS()) &&
+   BinOp1->getOpcode() == BinOp2->getOpcode();
+  }
   case Stmt::CharacterLiteralClass:
 return cast(E1)->getValue() ==
cast(E2)->getValue();
@@ -194,15 +201,19 @@ void UseDefaultMemberInitCheck::storeOptions(
 }
 
 void UseDefaultMemberInitCheck::registerMatchers(MatchFinder *Finder) {
+  auto NumericLiteral = anyOf(integerLiteral(), floatLiteral());
+  auto UnaryNumericLiteral = unaryOperator(hasAnyOperatorName("+", "-"),
+   hasUnaryOperand(NumericLiteral));
+  auto EnumRef = declRefExpr(to(enumConstantDecl()));
+
+  auto BinaryNumericExpr = binaryOperator(
+  hasOperands(anyOf(NumericLiteral, EnumRef, binaryOperator()),
+  anyOf(NumericLiteral, EnumRef, binaryOperator(;
+
   auto InitBase =
-  anyOf(stringLiteral(), characterLiteral(), integerLiteral(),
-unaryOperator(hasAnyOperatorName("+", "-"),
-  hasUnaryOperand(integerLiteral())),
-floatLiteral(),
-unaryOperator(hasAnyOperatorName("+", "-"),
-  hasUnaryOperand(floatLiteral())),
-cxxBoolLiteral(), cxxNullPtrLiteralExpr(), implicitValueInitExpr(),
-declRefExpr(to(enumConstantDecl(;
+  anyOf(stringLiteral(), characterLiteral(), NumericLiteral,
+UnaryNumericLiteral, cxxBoolLiteral(), cxxNullPtrLiteralExpr(),
+implicitValueInitExpr(), EnumRef, BinaryNumericExpr);
 
   auto Init =
   anyOf(initListExpr(anyOf(allOf(initCountIs(1), hasInit(0, InitBase)),
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 951b7f20af4c8..dd46494687eff 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -132,11 +132,15 @@ Changes in existing checks
   ` check by providing additional
   examples and fixing some macro related false positives.
 
+- Improved :doc:`modernize-use-default-member-init
+  ` check by matching
+  arithmetic operations within member list initialization.
+
 - Improved :doc:`misc-use-internal-linkage
   ` check by fix false positives
   for function or variable in header file which contains macro expansion.
 
-- Improved :doc:`performance/unnecessary-value-param
+- Improved :doc:`performance-unnecessary-value-param
   ` check performance by
   tolerating fix-it breaking compilation when functions is used as pointers
   to avoid matching usage of functions within the current compilation unit.
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp
index 81c980e0217e6..ff8c80b682bdb 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp
@@ -518,3 +518,29 @@ class ArrayBraceInitMultipleValues {
 };
 
 } // namespace PR63285
+
+namespace PR122480 {
+
+#define ARITHMETIC_MACRO (44 - 2)
+
+class DefaultMemberInitWithArithmetic {
+  DefaultMemberInitWithArithmetic() : a{1 + 1},  b{1 + 11 + 123 + 1234},  c{2 
+ (4 / 2) + 3 + (7 / 11)},  d{ARITHMETIC_MACRO * 2}, e{1.2 + 3.4} {}
+  // CHECK-MESSAGES: :[[@LINE-1]]:39: warning: member initializer for 'a' is 
redundant [modernize-use-default-member-init]
+  // CHECK-FIXES: DefaultMemberInitWithArithmetic()  {}
+
+  int a{1 + 1};
+  int b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer 
for 'b' [modernize-use-default-member-init]
+  // CHECK-FIXES

[clang] 227f954 - [clang][bytecode][NFC] Bail out on non constant evaluated builtins (#130431)

2025-03-08 Thread via cfe-commits

Author: Timm Baeder
Date: 2025-03-09T06:35:19+01:00
New Revision: 227f9544a4d4bf9ab4da8a78cc801de697d4bc6d

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

LOG: [clang][bytecode][NFC] Bail out on non constant evaluated builtins 
(#130431)

If the ASTContext says so, don't bother trying to constant evaluate the
given builtin.

Added: 


Modified: 
clang/lib/AST/ByteCode/InterpBuiltin.cpp

Removed: 




diff  --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp 
b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index b8c4ef2f48a79..14e716daa3f12 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -2059,6 +2059,9 @@ static bool interp__builtin_memchr(InterpState &S, 
CodePtr OpPC,
 
 bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const Function *F,
   const CallExpr *Call, uint32_t BuiltinID) {
+  if (!S.getASTContext().BuiltinInfo.isConstantEvaluated(BuiltinID))
+return false;
+
   const InterpFrame *Frame = S.Current;
 
   std::optional ReturnT = S.getContext().classify(Call);



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


[clang-tools-extra] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init check (PR #129370)

2025-03-08 Thread David Rivera via cfe-commits


@@ -159,6 +159,12 @@ static bool sameValue(const Expr *E1, const Expr *E2) {
   case Stmt::UnaryOperatorClass:
 return sameValue(cast(E1)->getSubExpr(),
  cast(E2)->getSubExpr());
+  case Stmt::BinaryOperatorClass: {

RiverDave wrote:

That's a good edge case I hadn't thought about. yeah we totally need to make 
sure `BinaryOp` is the same to prevent cases where both expressions are 
numerically identical with different operands. should be fixed now, let me know 
if test cases are needed for that.

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


[clang-tools-extra] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init check (PR #129370)

2025-03-08 Thread David Rivera via cfe-commits

https://github.com/RiverDave updated 
https://github.com/llvm/llvm-project/pull/129370

>From 236cd9f21bd71b118a79356eb859dda31031bf80 Mon Sep 17 00:00:00 2001
From: David Rivera 
Date: Sat, 1 Mar 2025 02:09:02 -0500
Subject: [PATCH] [clang-tidy] detect arithmetic operations within member list
 initialization in modernize-use-default-member-init

---
 .../modernize/UseDefaultMemberInitCheck.cpp   | 27 +--
 clang-tools-extra/docs/ReleaseNotes.rst   |  6 -
 .../modernize/use-default-member-init.cpp | 26 ++
 3 files changed, 50 insertions(+), 9 deletions(-)

diff --git 
a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
index 6c06b0af342f6..6ce6c6af3fbb2 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
@@ -159,6 +159,13 @@ static bool sameValue(const Expr *E1, const Expr *E2) {
   case Stmt::UnaryOperatorClass:
 return sameValue(cast(E1)->getSubExpr(),
  cast(E2)->getSubExpr());
+  case Stmt::BinaryOperatorClass: {
+const auto *BinOp1 = cast(E1);
+const auto *BinOp2 = cast(E2);
+return BinOp1->getOpcode() == BinOp2->getOpcode() &&
+   sameValue(BinOp1->getLHS(), BinOp2->getLHS()) &&
+   sameValue(BinOp1->getRHS(), BinOp2->getRHS());
+  }
   case Stmt::CharacterLiteralClass:
 return cast(E1)->getValue() ==
cast(E2)->getValue();
@@ -194,15 +201,19 @@ void UseDefaultMemberInitCheck::storeOptions(
 }
 
 void UseDefaultMemberInitCheck::registerMatchers(MatchFinder *Finder) {
+  auto NumericLiteral = anyOf(integerLiteral(), floatLiteral());
+  auto UnaryNumericLiteral = unaryOperator(hasAnyOperatorName("+", "-"),
+   hasUnaryOperand(NumericLiteral));
+  auto EnumRef = declRefExpr(to(enumConstantDecl()));
+
+  auto BinaryNumericExpr = binaryOperator(
+  hasOperands(anyOf(NumericLiteral, EnumRef, binaryOperator()),
+  anyOf(NumericLiteral, EnumRef, binaryOperator(;
+
   auto InitBase =
-  anyOf(stringLiteral(), characterLiteral(), integerLiteral(),
-unaryOperator(hasAnyOperatorName("+", "-"),
-  hasUnaryOperand(integerLiteral())),
-floatLiteral(),
-unaryOperator(hasAnyOperatorName("+", "-"),
-  hasUnaryOperand(floatLiteral())),
-cxxBoolLiteral(), cxxNullPtrLiteralExpr(), implicitValueInitExpr(),
-declRefExpr(to(enumConstantDecl(;
+  anyOf(stringLiteral(), characterLiteral(), NumericLiteral,
+UnaryNumericLiteral, cxxBoolLiteral(), cxxNullPtrLiteralExpr(),
+implicitValueInitExpr(), EnumRef, BinaryNumericExpr);
 
   auto Init =
   anyOf(initListExpr(anyOf(allOf(initCountIs(1), hasInit(0, InitBase)),
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 951b7f20af4c8..dd46494687eff 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -132,11 +132,15 @@ Changes in existing checks
   ` check by providing additional
   examples and fixing some macro related false positives.
 
+- Improved :doc:`modernize-use-default-member-init
+  ` check by matching
+  arithmetic operations within member list initialization.
+
 - Improved :doc:`misc-use-internal-linkage
   ` check by fix false positives
   for function or variable in header file which contains macro expansion.
 
-- Improved :doc:`performance/unnecessary-value-param
+- Improved :doc:`performance-unnecessary-value-param
   ` check performance by
   tolerating fix-it breaking compilation when functions is used as pointers
   to avoid matching usage of functions within the current compilation unit.
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp
index 81c980e0217e6..ff8c80b682bdb 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp
@@ -518,3 +518,29 @@ class ArrayBraceInitMultipleValues {
 };
 
 } // namespace PR63285
+
+namespace PR122480 {
+
+#define ARITHMETIC_MACRO (44 - 2)
+
+class DefaultMemberInitWithArithmetic {
+  DefaultMemberInitWithArithmetic() : a{1 + 1},  b{1 + 11 + 123 + 1234},  c{2 
+ (4 / 2) + 3 + (7 / 11)},  d{ARITHMETIC_MACRO * 2}, e{1.2 + 3.4} {}
+  // CHECK-MESSAGES: :[[@LINE-1]]:39: warning: member initializer for 'a' is 
redundant [modernize-use-default-member-init]
+  // CHECK-FIXES: DefaultMemberInitWithArithmetic()  {}
+
+  int a{1 + 1};
+  int b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer 
for 'b' [modernize-use-default-member-init]
+  // CHECK-FIXES

[clang] [clang][CodeComplete] Add code completion for if constexpr and consteval (PR #124315)

2025-03-08 Thread Nathan Ridge via cfe-commits


@@ -6749,6 +6749,55 @@ void SemaCodeCompletion::CodeCompleteInitializer(Scope 
*S, Decl *D) {
   CodeCompleteExpression(S, Data);
 }
 
+void SemaCodeCompletion::CodeCompleteIfConst(Scope *S,

HighCommander4 wrote:

The function does not use the `S` parameter, please remove it

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


[clang] [clang][CodeComplete] Add code completion for if constexpr and consteval (PR #124315)

2025-03-08 Thread Nathan Ridge via cfe-commits


@@ -0,0 +1,26 @@
+template 
+void test() {
+  if constexpr (Flag) {
+return;
+  }
+  // RUN: %clang_cc1 -fsyntax-only -std=c++17 -code-completion-at=%s:3:7 %s | 
FileCheck -check-prefix=CHECK-CXX17 %s
+  // RUN: %clang_cc1 -fsyntax-only -std=c++17 -code-completion-patterns 
-code-completion-at=%s:3:7 %s | FileCheck -check-prefix=CHECK-PATTERN-CXX17 %s
+  // RUN: %clang_cc1 -fsyntax-only -std=c++23 -code-completion-at=%s:3:7 %s | 
FileCheck -check-prefix=CHECK-CXX23 %s
+  // RUN: %clang_cc1 -fsyntax-only -std=c++23 -code-completion-patterns 
-code-completion-at=%s:3:7 %s | FileCheck -check-prefix=CHECK-PATTERN-CXX23 %s
+  // CHECK-CXX17: COMPLETION: constexpr
+  // CHECK-PATTERN-CXX17: COMPLETION: Pattern : constexpr (<#condition#>) {
+  // CHECK-PATTERN-CXX17: <#statements#>
+  // CHECK-PATTERN-CXX17: }
+  // CHECK-CXX23: COMPLETION: consteval

HighCommander4 wrote:

Could you add:

```
  // CHECK-CXX23: COMPLETION: constexpr
```

as well?  This expresses the intent that in C++23 mode, we should get both, not 
just `consteval`.

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


[clang] [clang][CodeComplete] Add code completion for if constexpr and consteval (PR #124315)

2025-03-08 Thread Nathan Ridge via cfe-commits


@@ -0,0 +1,26 @@
+template 
+void test() {
+  if constexpr (Flag) {
+return;
+  }
+  // RUN: %clang_cc1 -fsyntax-only -std=c++17 -code-completion-at=%s:3:7 %s | 
FileCheck -check-prefix=CHECK-CXX17 %s
+  // RUN: %clang_cc1 -fsyntax-only -std=c++17 -code-completion-patterns 
-code-completion-at=%s:3:7 %s | FileCheck -check-prefix=CHECK-PATTERN-CXX17 %s
+  // RUN: %clang_cc1 -fsyntax-only -std=c++23 -code-completion-at=%s:3:7 %s | 
FileCheck -check-prefix=CHECK-CXX23 %s
+  // RUN: %clang_cc1 -fsyntax-only -std=c++23 -code-completion-patterns 
-code-completion-at=%s:3:7 %s | FileCheck -check-prefix=CHECK-PATTERN-CXX23 %s
+  // CHECK-CXX17: COMPLETION: constexpr
+  // CHECK-PATTERN-CXX17: COMPLETION: Pattern : constexpr (<#condition#>) {
+  // CHECK-PATTERN-CXX17: <#statements#>
+  // CHECK-PATTERN-CXX17: }
+  // CHECK-CXX23: COMPLETION: consteval
+  // CHECK-PATTERN-CXX23: COMPLETION: Pattern : consteval {
+  // CHECK-PATTERN-CXX23: <#statements#>
+  // CHECK-PATTERN-CXX23: }

HighCommander4 wrote:

And likewise here:

```
  // CHECK-PATTERN-CXX23: COMPLETION: Pattern : constexpr (<#condition#>) {
  // CHECK-PATTERN-CXX23: <#statements#>
  // CHECK-PATTERN-CXX23: }
```

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


[clang] [clang][CodeComplete] Add code completion for if constexpr and consteval (PR #124315)

2025-03-08 Thread Nathan Ridge via cfe-commits


@@ -6749,6 +6749,55 @@ void SemaCodeCompletion::CodeCompleteInitializer(Scope 
*S, Decl *D) {
   CodeCompleteExpression(S, Data);
 }
 
+void SemaCodeCompletion::CodeCompleteIfConst(Scope *S,
+ bool AfterExclaim) const {

HighCommander4 wrote:

`CodeCompleteKeywordAfterIf` would make more sense to me ("code-complete a 
keyword [namely, `constexpr` or `consteval`] that comes after `if`")

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


[clang] [clang][CodeComplete] Add code completion for if constexpr and consteval (PR #124315)

2025-03-08 Thread Nathan Ridge via cfe-commits

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


[clang] [clang] Implement address sanitizer on AIX (1/3) (PR #129925)

2025-03-08 Thread Jake Egan via cfe-commits

https://github.com/jakeegan updated 
https://github.com/llvm/llvm-project/pull/129925

>From 072f4eca3825729d69d423d774c8a3298cb624a8 Mon Sep 17 00:00:00 2001
From: Jake Egan 
Date: Wed, 5 Mar 2025 01:57:38 -0500
Subject: [PATCH 1/2] [clang] Implement address sanitizer on AIX (1/3)

The PR includes clang changes needed for the address sanitizer on AIX. Will 
also post llvm and
compiler-rt PRs following this.
---
 .../clang/Basic/DiagnosticDriverKinds.td  |   2 +
 clang/include/clang/Driver/Options.td |   2 +-
 clang/lib/CodeGen/BackendUtil.cpp |   5 +-
 clang/lib/Driver/ToolChain.cpp|   2 +-
 clang/lib/Driver/ToolChains/AIX.cpp   |  45 
 clang/lib/Driver/ToolChains/AIX.h |   2 +
 clang/lib/Driver/ToolChains/CommonArgs.cpp|  36 +-
 .../lib/aix/asan.link_with_main_exec.txt  |   0
 .../lib/aix/asan_cxx.link_with_main_exec.txt  |   0
 clang/test/Driver/sanitizer-ld.c  | 104 ++
 10 files changed, 189 insertions(+), 9 deletions(-)
 create mode 100644 
clang/test/Driver/Inputs/resource_dir/lib/aix/asan.link_with_main_exec.txt
 create mode 100644 
clang/test/Driver/Inputs/resource_dir/lib/aix/asan_cxx.link_with_main_exec.txt

diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 8d599c96eb4fb..c44d364d244bc 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -257,6 +257,8 @@ def err_drv_malformed_sanitizer_metadata_ignorelist : Error<
   "malformed sanitizer metadata ignorelist: '%0'">;
 def err_drv_unsupported_static_sanitizer_darwin : Error<
   "static %0 runtime is not supported on darwin">;
+def err_drv_unsupported_shared_sanitizer_aix : Error<
+  "shared %0 runtime is not supported on AIX">;
 def err_drv_duplicate_config : Error<
   "no more than one option '--config' is allowed">;
 def err_drv_cannot_open_config_file : Error<
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 0ab923fcdd583..66959279d3fcf 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1542,7 +1542,7 @@ defm xl_pragma_pack : BoolFOption<"xl-pragma-pack",
   "Enable IBM XL #pragma pack handling">,
   NegFlag>;
 def shared_libsan : Flag<["-"], "shared-libsan">,
-  HelpText<"Dynamically link the sanitizer runtime">;
+  HelpText<"Dynamically link the sanitizer runtime (Not supported for ASan on 
AIX)">;
 def static_libsan : Flag<["-"], "static-libsan">,
   HelpText<"Statically link the sanitizer runtime (Not supported for ASan, 
TSan or UBSan on darwin)">;
 def : Flag<["-"], "shared-libasan">, Alias;
diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 97e9bbccd61ef..b47aff95f2430 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -275,13 +275,14 @@ static bool asanUseGlobalsGC(const Triple &T, const 
CodeGenOptions &CGOpts) {
 return !CGOpts.DisableIntegratedAS;
   case Triple::GOFF:
 llvm::report_fatal_error("ASan not implemented for GOFF");
-  case Triple::XCOFF:
-llvm::report_fatal_error("ASan not implemented for XCOFF.");
   case Triple::Wasm:
   case Triple::DXContainer:
   case Triple::SPIRV:
   case Triple::UnknownObjectFormat:
 break;
+  case Triple::XCOFF:
+// FIXME: try to enable GC-friendly instrumentation for globals on AIX.
+return false;
   }
   return false;
 }
diff --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp
index ebc982096595e..d4aa71d031ba9 100644
--- a/clang/lib/Driver/ToolChain.cpp
+++ b/clang/lib/Driver/ToolChain.cpp
@@ -749,7 +749,7 @@ std::string ToolChain::buildCompilerRTBasename(const 
llvm::opt::ArgList &Args,
   case ToolChain::FT_Shared:
 Suffix = TT.isOSWindows()
  ? (TT.isWindowsGNUEnvironment() ? ".dll.a" : ".lib")
- : ".so";
+ : (TT.isOSAIX() ? ".a" : ".so");
 break;
   }
 
diff --git a/clang/lib/Driver/ToolChains/AIX.cpp 
b/clang/lib/Driver/ToolChains/AIX.cpp
index 09a8dc2f4fa5d..30db6f45c7e81 100644
--- a/clang/lib/Driver/ToolChains/AIX.cpp
+++ b/clang/lib/Driver/ToolChains/AIX.cpp
@@ -20,6 +20,7 @@
 #include 
 
 using AIX = clang::driver::toolchains::AIX;
+using namespace clang;
 using namespace clang::driver;
 using namespace clang::driver::tools;
 using namespace clang::driver::toolchains;
@@ -233,6 +234,44 @@ void aix::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
   // Specify linker input file(s).
   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
 
+  // Add sanitizer libraries.
+  const SanitizerArgs &Sanitize = ToolChain.getSanitizerArgs(Args);
+  const char *sanitizer = nullptr;
+  bool NeedsSanitizerDeps = false;
+  // For now, only support address sanitizer.
+  if (Sanitize.needsAsanRt())
+sanitizer = "AddressSanitizer";
+
+  if (sanitizer) {
+  

[clang-tools-extra] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init check (PR #129370)

2025-03-08 Thread David Rivera via cfe-commits

https://github.com/RiverDave updated 
https://github.com/llvm/llvm-project/pull/129370

>From 64cec5f09ff2a9b2cb3811d52c66fabae90887be Mon Sep 17 00:00:00 2001
From: David Rivera 
Date: Sat, 1 Mar 2025 02:09:02 -0500
Subject: [PATCH] [clang-tidy] detect arithmetic operations within member list
 initialization in modernize-use-default-member-init

---
 .../modernize/UseDefaultMemberInitCheck.cpp   | 26 +--
 clang-tools-extra/docs/ReleaseNotes.rst   |  6 -
 .../modernize/use-default-member-init.cpp | 26 +++
 3 files changed, 49 insertions(+), 9 deletions(-)

diff --git 
a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
index 6c06b0af342f6..ab6946588991e 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
@@ -159,6 +159,12 @@ static bool sameValue(const Expr *E1, const Expr *E2) {
   case Stmt::UnaryOperatorClass:
 return sameValue(cast(E1)->getSubExpr(),
  cast(E2)->getSubExpr());
+  case Stmt::BinaryOperatorClass: {
+const auto *BinOp1 = cast(E1);
+const auto *BinOp2 = cast(E2);
+return sameValue(BinOp1->getLHS(), BinOp2->getLHS()) &&
+   sameValue(BinOp1->getRHS(), BinOp2->getRHS()) && 
BinOp1->getOpcode() == BinOp2->getOpcode();
+  }
   case Stmt::CharacterLiteralClass:
 return cast(E1)->getValue() ==
cast(E2)->getValue();
@@ -194,15 +200,19 @@ void UseDefaultMemberInitCheck::storeOptions(
 }
 
 void UseDefaultMemberInitCheck::registerMatchers(MatchFinder *Finder) {
+  auto NumericLiteral = anyOf(integerLiteral(), floatLiteral());
+  auto UnaryNumericLiteral = unaryOperator(hasAnyOperatorName("+", "-"),
+   hasUnaryOperand(NumericLiteral));
+  auto EnumRef = declRefExpr(to(enumConstantDecl()));
+
+  auto BinaryNumericExpr = binaryOperator(
+  hasOperands(anyOf(NumericLiteral, EnumRef, binaryOperator()),
+  anyOf(NumericLiteral, EnumRef, binaryOperator(;
+
   auto InitBase =
-  anyOf(stringLiteral(), characterLiteral(), integerLiteral(),
-unaryOperator(hasAnyOperatorName("+", "-"),
-  hasUnaryOperand(integerLiteral())),
-floatLiteral(),
-unaryOperator(hasAnyOperatorName("+", "-"),
-  hasUnaryOperand(floatLiteral())),
-cxxBoolLiteral(), cxxNullPtrLiteralExpr(), implicitValueInitExpr(),
-declRefExpr(to(enumConstantDecl(;
+  anyOf(stringLiteral(), characterLiteral(), NumericLiteral,
+UnaryNumericLiteral, cxxBoolLiteral(), cxxNullPtrLiteralExpr(),
+implicitValueInitExpr(), EnumRef, BinaryNumericExpr);
 
   auto Init =
   anyOf(initListExpr(anyOf(allOf(initCountIs(1), hasInit(0, InitBase)),
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 951b7f20af4c8..dd46494687eff 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -132,11 +132,15 @@ Changes in existing checks
   ` check by providing additional
   examples and fixing some macro related false positives.
 
+- Improved :doc:`modernize-use-default-member-init
+  ` check by matching
+  arithmetic operations within member list initialization.
+
 - Improved :doc:`misc-use-internal-linkage
   ` check by fix false positives
   for function or variable in header file which contains macro expansion.
 
-- Improved :doc:`performance/unnecessary-value-param
+- Improved :doc:`performance-unnecessary-value-param
   ` check performance by
   tolerating fix-it breaking compilation when functions is used as pointers
   to avoid matching usage of functions within the current compilation unit.
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp
index 81c980e0217e6..ff8c80b682bdb 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp
@@ -518,3 +518,29 @@ class ArrayBraceInitMultipleValues {
 };
 
 } // namespace PR63285
+
+namespace PR122480 {
+
+#define ARITHMETIC_MACRO (44 - 2)
+
+class DefaultMemberInitWithArithmetic {
+  DefaultMemberInitWithArithmetic() : a{1 + 1},  b{1 + 11 + 123 + 1234},  c{2 
+ (4 / 2) + 3 + (7 / 11)},  d{ARITHMETIC_MACRO * 2}, e{1.2 + 3.4} {}
+  // CHECK-MESSAGES: :[[@LINE-1]]:39: warning: member initializer for 'a' is 
redundant [modernize-use-default-member-init]
+  // CHECK-FIXES: DefaultMemberInitWithArithmetic()  {}
+
+  int a{1 + 1};
+  int b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer 
for 'b' [modernize-use-default-member-init]
+  // CHECK-FIXES:  int b{1

[clang] [clang][CodeComplete] Add code completion for if constexpr and consteval (PR #124315)

2025-03-08 Thread Nathan Ridge via cfe-commits


@@ -1553,6 +1553,13 @@ StmtResult Parser::ParseIfStatement(SourceLocation 
*TrailingElseLoc) {
   IsConsteval = true;
   ConstevalLoc = ConsumeToken();
 }
+
+if (Tok.is(tok::code_completion)) {

HighCommander4 wrote:

This needs to go in an `else` after the `Tok.is(tok::kw_consteval)`. Otherwise, 
if you invoke completion **after** `consteval`, e.g.:

`if consteval ^` <-- here

then you incorrectly get `constexpr` and `consteval` suggested.

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


[clang] [clang-format] Don't remove parentheses separated from ellipsis by comma (PR #130471)

2025-03-08 Thread Owen Pan via cfe-commits

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

Also clean up `case tok::r_paren` in UnwrappedLineParser::parseParens()

Fix #130359

>From 1f12041d3e28ee0de3277f6718967fd5d84e2161 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sat, 8 Mar 2025 22:41:51 -0800
Subject: [PATCH] [clang-format] Don't remove parentheses separated from
 ellipsis by comma

Also clean up `case tok::r_paren` in UnwrappedLineParser::parseParens()

Fix #130359
---
 clang/lib/Format/UnwrappedLineParser.cpp | 86 ++--
 clang/unittests/Format/FormatTest.cpp|  4 ++
 2 files changed, 55 insertions(+), 35 deletions(-)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 6854e224c2631..a6e0596add5d2 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2562,12 +2562,12 @@ bool UnwrappedLineParser::parseBracedList(bool 
IsAngleBracket, bool IsEnum) {
 /// Returns whether there is a `=` token between the parentheses.
 bool UnwrappedLineParser::parseParens(TokenType AmpAmpTokenType) {
   assert(FormatTok->is(tok::l_paren) && "'(' expected.");
-  auto *LeftParen = FormatTok;
+  auto *LParen = FormatTok;
   bool SeenComma = false;
   bool SeenEqual = false;
   bool MightBeFoldExpr = false;
-  const bool MightBeStmtExpr = Tokens->peekNextToken()->is(tok::l_brace);
   nextToken();
+  const bool MightBeStmtExpr = FormatTok->is(tok::l_brace);
   do {
 switch (FormatTok->Tok.getKind()) {
 case tok::l_paren:
@@ -2577,44 +2577,60 @@ bool UnwrappedLineParser::parseParens(TokenType 
AmpAmpTokenType) {
 parseChildBlock();
   break;
 case tok::r_paren: {
-  auto *Prev = LeftParen->Previous;
-  if (!MightBeStmtExpr && !MightBeFoldExpr && !Line->InMacroBody &&
-  Style.RemoveParentheses > FormatStyle::RPS_Leave) {
-const auto *Next = Tokens->peekNextToken();
-const bool DoubleParens =
-Prev && Prev->is(tok::l_paren) && Next && Next->is(tok::r_paren);
-const bool CommaSeparated =
-!DoubleParens && Prev && Prev->isOneOf(tok::l_paren, tok::comma) &&
-Next && Next->isOneOf(tok::comma, tok::r_paren);
-const auto *PrevPrev = Prev ? Prev->getPreviousNonComment() : nullptr;
-const bool Excluded =
-PrevPrev &&
-(PrevPrev->isOneOf(tok::kw___attribute, tok::kw_decltype) ||
- SeenComma ||
- (SeenEqual &&
-  (PrevPrev->isOneOf(tok::kw_if, tok::kw_while) ||
-   PrevPrev->endsSequence(tok::kw_constexpr, tok::kw_if;
-const bool ReturnParens =
-Style.RemoveParentheses == FormatStyle::RPS_ReturnStatement &&
-((NestedLambdas.empty() && !IsDecltypeAutoFunction) ||
- (!NestedLambdas.empty() && !NestedLambdas.back())) &&
-Prev && Prev->isOneOf(tok::kw_return, tok::kw_co_return) && Next &&
-Next->is(tok::semi);
-if ((DoubleParens && !Excluded) || (CommaSeparated && !SeenComma) ||
-ReturnParens) {
-  LeftParen->Optional = true;
-  FormatTok->Optional = true;
-}
-  }
+  auto *Prev = LParen->Previous;
+  auto *RParen = FormatTok;
+  nextToken();
   if (Prev) {
+auto OptionalParens = [&] {
+  if (MightBeStmtExpr || MightBeFoldExpr || Line->InMacroBody ||
+  SeenComma || Style.RemoveParentheses == FormatStyle::RPS_Leave) {
+return false;
+  }
+  const bool DoubleParens =
+  Prev->is(tok::l_paren) && FormatTok->is(tok::r_paren);
+  if (DoubleParens) {
+const auto *PrevPrev = Prev->getPreviousNonComment();
+const bool Excluded =
+PrevPrev &&
+(PrevPrev->isOneOf(tok::kw___attribute, tok::kw_decltype) ||
+ (SeenEqual &&
+  (PrevPrev->isOneOf(tok::kw_if, tok::kw_while) ||
+   PrevPrev->endsSequence(tok::kw_constexpr, tok::kw_if;
+if (!Excluded)
+  return true;
+  } else {
+const bool CommaSeparated =
+Prev->isOneOf(tok::l_paren, tok::comma) &&
+FormatTok->isOneOf(tok::comma, tok::r_paren);
+if (CommaSeparated &&
+// LParen is not preceded by ellipsis, comma.
+!Prev->endsSequence(tok::comma, tok::ellipsis) &&
+// RParen is not followed by comma, ellipsis.
+!(FormatTok->is(tok::comma) &&
+  Tokens->peekNextToken()->is(tok::ellipsis))) {
+  return true;
+}
+const bool ReturnParens =
+Style.RemoveParentheses == FormatStyle::RPS_ReturnStatement &&
+((NestedLambdas.empty() && !IsDecltypeAutoFunction) ||
+ (!NestedLambdas.empty() && !NestedLambdas.back())) &&
+Prev->isOneOf(to

[clang] [clang-format] Don't remove parentheses separated from ellipsis by comma (PR #130471)

2025-03-08 Thread Owen Pan via cfe-commits

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


[clang] [clang][CodeComplete] Add code completion for if constexpr and consteval (PR #124315)

2025-03-08 Thread Nathan Ridge via cfe-commits


@@ -6749,6 +6749,55 @@ void SemaCodeCompletion::CodeCompleteInitializer(Scope 
*S, Decl *D) {
   CodeCompleteExpression(S, Data);
 }
 
+void SemaCodeCompletion::CodeCompleteIfConst(Scope *S,
+ bool AfterExclaim) const {
+  ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
+CodeCompleter->getCodeCompletionTUInfo(),
+CodeCompletionContext::CCC_Other);

HighCommander4 wrote:

Looking at the similar function `CodeCompleteAfterIf`, I think 
`mapCodeCompletionContext(SemaRef, PCC_Statement)` would be more appropriate 
here than `CodeCompletionContext::CCC_Other`

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


[clang] [clang][CodeComplete] Use HeuristicResolver in getAsRecordDecl() (PR #130473)

2025-03-08 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 created 
https://github.com/llvm/llvm-project/pull/130473

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

>From 0999f2fb15b6703fc9f5c4ba5c9e21c14a90b4ed Mon Sep 17 00:00:00 2001
From: Nathan Ridge 
Date: Sun, 9 Mar 2025 01:36:25 -0500
Subject: [PATCH 1/4] Change the parameter type of resolveTypeToTagDecl() to
 QualType

---
 clang/lib/Sema/HeuristicResolver.cpp | 18 --
 1 file changed, 8 insertions(+), 10 deletions(-)

diff --git a/clang/lib/Sema/HeuristicResolver.cpp 
b/clang/lib/Sema/HeuristicResolver.cpp
index 7aecd2a73b539..3c7918165ee42 100644
--- a/clang/lib/Sema/HeuristicResolver.cpp
+++ b/clang/lib/Sema/HeuristicResolver.cpp
@@ -75,7 +75,7 @@ class HeuristicResolverImpl {
   // Helper function for HeuristicResolver::resolveDependentMember()
   // which takes a possibly-dependent type `T` and heuristically
   // resolves it to a TagDecl in which we can try name lookup.
-  TagDecl *resolveTypeToTagDecl(const Type *T);
+  TagDecl *resolveTypeToTagDecl(QualType T);
 
   // Helper function for simplifying a type.
   // `Type` is the type to simplify.
@@ -132,8 +132,10 @@ TemplateName getReferencedTemplateName(const Type *T) {
 // Helper function for HeuristicResolver::resolveDependentMember()
 // which takes a possibly-dependent type `T` and heuristically
 // resolves it to a CXXRecordDecl in which we can try name lookup.
-TagDecl *HeuristicResolverImpl::resolveTypeToTagDecl(const Type *T) {
-  assert(T);
+TagDecl *HeuristicResolverImpl::resolveTypeToTagDecl(QualType QT) {
+  const Type *T = QT.getTypePtrOrNull();
+  if (!T)
+return nullptr;
 
   // Unwrap type sugar such as type aliases.
   T = T->getCanonicalTypeInternal().getTypePtr();
@@ -315,8 +317,7 @@ HeuristicResolverImpl::resolveTypeOfCallExpr(const CallExpr 
*CE) {
   if (const auto *FnTypePtr = CalleeType->getAs())
 CalleeType = FnTypePtr->getPointeeType();
   if (const FunctionType *FnType = CalleeType->getAs()) {
-if (const auto *D =
-resolveTypeToTagDecl(FnType->getReturnType().getTypePtr())) {
+if (const auto *D = resolveTypeToTagDecl(FnType->getReturnType())) {
   return {D};
 }
   }
@@ -427,7 +428,7 @@ bool findOrdinaryMember(const CXXRecordDecl *RD, 
CXXBasePath &Path,
 bool HeuristicResolverImpl::findOrdinaryMemberInDependentClasses(
 const CXXBaseSpecifier *Specifier, CXXBasePath &Path,
 DeclarationName Name) {
-  TagDecl *TD = resolveTypeToTagDecl(Specifier->getType().getTypePtr());
+  TagDecl *TD = resolveTypeToTagDecl(Specifier->getType());
   if (const auto *RD = dyn_cast_if_present(TD)) {
 return findOrdinaryMember(RD, Path, Name);
   }
@@ -470,10 +471,7 @@ std::vector 
HeuristicResolverImpl::lookupDependentName(
 std::vector HeuristicResolverImpl::resolveDependentMember(
 QualType QT, DeclarationName Name,
 llvm::function_ref Filter) {
-  const Type *T = QT.getTypePtrOrNull();
-  if (!T)
-return {};
-  TagDecl *TD = resolveTypeToTagDecl(T);
+  TagDecl *TD = resolveTypeToTagDecl(QT);
   if (!TD)
 return {};
   if (auto *ED = dyn_cast(TD)) {

>From a3c77212039245d9f4704567fd426f36a29e947f Mon Sep 17 00:00:00 2001
From: Nathan Ridge 
Date: Sun, 9 Mar 2025 01:43:25 -0500
Subject: [PATCH 2/4] Expose resolveTypeToTagDecl() publically in
 HeuristicResolver

---
 clang/include/clang/Sema/HeuristicResolver.h | 4 
 clang/lib/Sema/HeuristicResolver.cpp | 9 -
 2 files changed, 8 insertions(+), 5 deletions(-)

diff --git a/clang/include/clang/Sema/HeuristicResolver.h 
b/clang/include/clang/Sema/HeuristicResolver.h
index f511815b40199..c971b9a6a7b51 100644
--- a/clang/include/clang/Sema/HeuristicResolver.h
+++ b/clang/include/clang/Sema/HeuristicResolver.h
@@ -81,6 +81,10 @@ class HeuristicResolver {
   // could look up the name appearing on the RHS.
   const QualType getPointeeType(QualType T) const;
 
+  // Heuristically resolve a possibly-dependent type `T` to a TagDecl
+  // in which a member's name can be looked up.
+  TagDecl *resolveTypeToTagDecl(QualType T) const;
+
 private:
   ASTContext &Ctx;
 };
diff --git a/clang/lib/Sema/HeuristicResolver.cpp 
b/clang/lib/Sema/HeuristicResolver.cpp
index 3c7918165ee42..11fe786fa91c6 100644
--- a/clang/lib/Sema/HeuristicResolver.cpp
+++ b/clang/lib/Sema/HeuristicResolver.cpp
@@ -47,6 +47,7 @@ class HeuristicResolverImpl {
   std::vector
   lookupDependentName(CXXRecordDecl *RD, DeclarationName Name,
   llvm::function_ref Filter);
+  TagDecl *resolveTypeToTagDecl(QualType T);
 
 private:
   ASTContext &Ctx;
@@ -72,11 +73,6 @@ class HeuristicResolverImpl {
   QualType resolveExprToType(const Expr *E);
   std::vector resolveExprToDecls(const Expr *E);
 
-  // Helper function for HeuristicResolver::resolveDependentMember()
-  // which takes a possibly-dependent type `T` and heuristically
-  // resolves it to a TagDecl in which we can try name lookup.
-  TagDecl *resolveTypeToTagDecl(QualType T);
-
   // Helper function for simplifying a

[clang-tools-extra] [clang-tidy] Add check on constexpr & static values in modernize-use-default-member-init (PR #129425)

2025-03-08 Thread David Rivera via cfe-commits

RiverDave wrote:

Ping

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


[clang] 2172a5e - [clang][analyzer][NFC] Fix typos in comments (#130456)

2025-03-08 Thread via cfe-commits

Author: Ben Shi
Date: 2025-03-09T08:23:51+01:00
New Revision: 2172a5edcf9357d24006a3c1032f2d52e199915d

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

LOG: [clang][analyzer][NFC] Fix typos in comments (#130456)

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
clang/include/clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h
clang/include/clang/StaticAnalyzer/Core/PathSensitive/SMTConv.h

Removed: 




diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
index 168983fd5cb68..bb33a6912bec7 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
@@ -7,7 +7,7 @@
 
//===--===//
 //
 //  This file defines CheckerContext that provides contextual info for
-// path-sensitive checkers.
+//  path-sensitive checkers.
 //
 
//===--===//
 
@@ -152,7 +152,7 @@ class CheckerContext {
   }
 
   /// Returns true if the value of \p E is greater than or equal to \p
-  /// Val under unsigned comparison
+  /// Val under unsigned comparison.
   bool isGreaterOrEqual(const Expr *E, unsigned long long Val);
 
   /// Returns true if the value of \p E is negative.
@@ -392,7 +392,7 @@ class CheckerContext {
   /// hardened variant that's not yet covered by it.
   static bool isHardenedVariantOf(const FunctionDecl *FD, StringRef Name);
 
-  /// Depending on wither the location corresponds to a macro, return
+  /// Depending on whether the location corresponds to a macro, return
   /// either the macro name or the token spelling.
   ///
   /// This could be useful when checkers' logic depends on whether a function

diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
index 80b79fd4e928f..b2b4e8729af25 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CoreEngine.h
@@ -156,7 +156,7 @@ class CoreEngine {
   void dispatchWorkItem(ExplodedNode* Pred, ProgramPoint Loc,
 const WorkListUnit& WU);
 
-  // Functions for external checking of whether we have unfinished work
+  // Functions for external checking of whether we have unfinished work.
   bool wasBlockAborted() const { return !blocksAborted.empty(); }
   bool wasBlocksExhausted() const { return !blocksExhausted.empty(); }
   bool hasWorkRemaining() const { return wasBlocksExhausted() ||

diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
index 2fb05ac46e8fa..967b25e5696f6 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h
@@ -7,7 +7,7 @@
 
//===--===//
 //
 //  This file defines the template classes ExplodedNode and ExplodedGraph,
-//  which represent a path-sensitive, intra-procedural "exploded graph."
+//  which represent a path-sensitive, intra-procedural "exploded graph".
 //  See "Precise interprocedural dataflow analysis via graph reachability"
 //  by Reps, Horwitz, and Sagiv
 //  (http://portal.acm.org/citation.cfm?id=199462) for the definition of an
@@ -426,8 +426,8 @@ class ExplodedGraph {
   ///
   /// \param Nodes The nodes which must appear in the final graph. Presumably
   ///  these are end-of-path nodes (i.e. they have no successors).
-  /// \param[out] ForwardMap A optional map from nodes in this graph to nodes 
in
-  ///the returned graph.
+  /// \param[out] ForwardMap An optional map from nodes in this graph to nodes
+  ///in the returned graph.
   /// \param[out] InverseMap An optional map from nodes in the returned graph 
to
   ///nodes in this graph.
   /// \returns The trimmed graph

diff  --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
index 804fc74b009df..5f855251b3cde 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
+++ b/clang/

[clang] [clang][analyzer][NFC] Fix typos in comments (PR #130456)

2025-03-08 Thread Balazs Benics via cfe-commits

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


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


[clang-tools-extra] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init check (PR #129370)

2025-03-08 Thread David Rivera via cfe-commits

https://github.com/RiverDave edited 
https://github.com/llvm/llvm-project/pull/129370
___
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 on constexpr & static values in modernize-use-default-member-init (PR #129425)

2025-03-08 Thread David Rivera via cfe-commits

https://github.com/RiverDave updated 
https://github.com/llvm/llvm-project/pull/129425

>From 4f25319a076bddd11de886dbb35693cbfd2a3a73 Mon Sep 17 00:00:00 2001
From: David Rivera 
Date: Sun, 2 Mar 2025 01:12:05 -0500
Subject: [PATCH] [clang-tidy] Add check on constexpr & static values on member
 initialization in modernize-use-default-member-init

---
 .../modernize/UseDefaultMemberInitCheck.cpp   |  4 +++-
 clang-tools-extra/docs/ReleaseNotes.rst   |  4 
 .../modernize/use-default-member-init.cpp | 19 +++
 3 files changed, 26 insertions(+), 1 deletion(-)

diff --git 
a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
index 6c06b0af342f6..5b0b9b59d4e3b 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
@@ -194,6 +194,8 @@ void UseDefaultMemberInitCheck::storeOptions(
 }
 
 void UseDefaultMemberInitCheck::registerMatchers(MatchFinder *Finder) {
+  auto ConstExpRef = varDecl(anyOf(isConstexpr(), isStaticStorageClass()));
+
   auto InitBase =
   anyOf(stringLiteral(), characterLiteral(), integerLiteral(),
 unaryOperator(hasAnyOperatorName("+", "-"),
@@ -202,7 +204,7 @@ void 
UseDefaultMemberInitCheck::registerMatchers(MatchFinder *Finder) {
 unaryOperator(hasAnyOperatorName("+", "-"),
   hasUnaryOperand(floatLiteral())),
 cxxBoolLiteral(), cxxNullPtrLiteralExpr(), implicitValueInitExpr(),
-declRefExpr(to(enumConstantDecl(;
+declRefExpr(to(anyOf(enumConstantDecl(), ConstExpRef;
 
   auto Init =
   anyOf(initListExpr(anyOf(allOf(initCountIs(1), hasInit(0, InitBase)),
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 951b7f20af4c8..ccd0856c905e0 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -136,6 +136,10 @@ Changes in existing checks
   ` check by fix false positives
   for function or variable in header file which contains macro expansion.
 
+- Improved :doc:`modernize-use-default-member-init
+  ` check by matching
+  ``constexpr`` and ``static`` values on member initialization.
+
 - Improved :doc:`performance/unnecessary-value-param
   ` check performance by
   tolerating fix-it breaking compilation when functions is used as pointers
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp
index 81c980e0217e6..e97c521832e81 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp
@@ -518,3 +518,22 @@ class ArrayBraceInitMultipleValues {
 };
 
 } // namespace PR63285
+
+namespace PR122480 {
+
+  static int STATIC_VAL = 23;
+  static constexpr const char* CONSTEXPR_REF = "Static";
+
+  class StaticConstExprInit {
+
+StaticConstExprInit() : a{CONSTEXPR_REF}, b{STATIC_VAL}{}
+// CHECK-FIXES: StaticConstExprInit()  {}
+const char* a;
+// CHECK-MESSAGES: :[[@LINE-1]]:17: warning: use default member 
initializer for 'a' [modernize-use-default-member-init]
+// CHECK-FIXES: const char* a{CONSTEXPR_REF};
+int b;
+// CHECK-MESSAGES: :[[@LINE-1]]:9: warning: use default member initializer 
for 'b' [modernize-use-default-member-init]
+// CHECK-FIXES: int b{STATIC_VAL};
+  };
+
+} //namespace PR122480

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


[clang] [clang-format] Don't remove parentheses separated from ellipsis by comma (PR #130471)

2025-03-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Owen Pan (owenca)


Changes

Also clean up `case tok::r_paren` in UnwrappedLineParser::parseParens()

Fix #130359

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


2 Files Affected:

- (modified) clang/lib/Format/UnwrappedLineParser.cpp (+51-35) 
- (modified) clang/unittests/Format/FormatTest.cpp (+4) 


``diff
diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 6854e224c2631..a6e0596add5d2 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2562,12 +2562,12 @@ bool UnwrappedLineParser::parseBracedList(bool 
IsAngleBracket, bool IsEnum) {
 /// Returns whether there is a `=` token between the parentheses.
 bool UnwrappedLineParser::parseParens(TokenType AmpAmpTokenType) {
   assert(FormatTok->is(tok::l_paren) && "'(' expected.");
-  auto *LeftParen = FormatTok;
+  auto *LParen = FormatTok;
   bool SeenComma = false;
   bool SeenEqual = false;
   bool MightBeFoldExpr = false;
-  const bool MightBeStmtExpr = Tokens->peekNextToken()->is(tok::l_brace);
   nextToken();
+  const bool MightBeStmtExpr = FormatTok->is(tok::l_brace);
   do {
 switch (FormatTok->Tok.getKind()) {
 case tok::l_paren:
@@ -2577,44 +2577,60 @@ bool UnwrappedLineParser::parseParens(TokenType 
AmpAmpTokenType) {
 parseChildBlock();
   break;
 case tok::r_paren: {
-  auto *Prev = LeftParen->Previous;
-  if (!MightBeStmtExpr && !MightBeFoldExpr && !Line->InMacroBody &&
-  Style.RemoveParentheses > FormatStyle::RPS_Leave) {
-const auto *Next = Tokens->peekNextToken();
-const bool DoubleParens =
-Prev && Prev->is(tok::l_paren) && Next && Next->is(tok::r_paren);
-const bool CommaSeparated =
-!DoubleParens && Prev && Prev->isOneOf(tok::l_paren, tok::comma) &&
-Next && Next->isOneOf(tok::comma, tok::r_paren);
-const auto *PrevPrev = Prev ? Prev->getPreviousNonComment() : nullptr;
-const bool Excluded =
-PrevPrev &&
-(PrevPrev->isOneOf(tok::kw___attribute, tok::kw_decltype) ||
- SeenComma ||
- (SeenEqual &&
-  (PrevPrev->isOneOf(tok::kw_if, tok::kw_while) ||
-   PrevPrev->endsSequence(tok::kw_constexpr, tok::kw_if;
-const bool ReturnParens =
-Style.RemoveParentheses == FormatStyle::RPS_ReturnStatement &&
-((NestedLambdas.empty() && !IsDecltypeAutoFunction) ||
- (!NestedLambdas.empty() && !NestedLambdas.back())) &&
-Prev && Prev->isOneOf(tok::kw_return, tok::kw_co_return) && Next &&
-Next->is(tok::semi);
-if ((DoubleParens && !Excluded) || (CommaSeparated && !SeenComma) ||
-ReturnParens) {
-  LeftParen->Optional = true;
-  FormatTok->Optional = true;
-}
-  }
+  auto *Prev = LParen->Previous;
+  auto *RParen = FormatTok;
+  nextToken();
   if (Prev) {
+auto OptionalParens = [&] {
+  if (MightBeStmtExpr || MightBeFoldExpr || Line->InMacroBody ||
+  SeenComma || Style.RemoveParentheses == FormatStyle::RPS_Leave) {
+return false;
+  }
+  const bool DoubleParens =
+  Prev->is(tok::l_paren) && FormatTok->is(tok::r_paren);
+  if (DoubleParens) {
+const auto *PrevPrev = Prev->getPreviousNonComment();
+const bool Excluded =
+PrevPrev &&
+(PrevPrev->isOneOf(tok::kw___attribute, tok::kw_decltype) ||
+ (SeenEqual &&
+  (PrevPrev->isOneOf(tok::kw_if, tok::kw_while) ||
+   PrevPrev->endsSequence(tok::kw_constexpr, tok::kw_if;
+if (!Excluded)
+  return true;
+  } else {
+const bool CommaSeparated =
+Prev->isOneOf(tok::l_paren, tok::comma) &&
+FormatTok->isOneOf(tok::comma, tok::r_paren);
+if (CommaSeparated &&
+// LParen is not preceded by ellipsis, comma.
+!Prev->endsSequence(tok::comma, tok::ellipsis) &&
+// RParen is not followed by comma, ellipsis.
+!(FormatTok->is(tok::comma) &&
+  Tokens->peekNextToken()->is(tok::ellipsis))) {
+  return true;
+}
+const bool ReturnParens =
+Style.RemoveParentheses == FormatStyle::RPS_ReturnStatement &&
+((NestedLambdas.empty() && !IsDecltypeAutoFunction) ||
+ (!NestedLambdas.empty() && !NestedLambdas.back())) &&
+Prev->isOneOf(tok::kw_return, tok::kw_co_return) &&
+FormatTok->is(tok::semi);
+if (ReturnParens)
+  return true;
+  }
+  return false;
+};
 if (Prev->is(TT_TypenameMacro)) {
-  LeftP

[clang] [clang][analyzer][NFC] Fix typos in comments (PR #130456)

2025-03-08 Thread Balazs Benics via cfe-commits

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


[clang] disable unary, vector mask (PR #130400)

2025-03-08 Thread via cfe-commits

https://github.com/wsehjk updated 
https://github.com/llvm/llvm-project/pull/130400

>From 2bae9c70106ffb96dc237ee539dd7e3438025b01 Mon Sep 17 00:00:00 2001
From: wang shiwen 
Date: Sat, 8 Mar 2025 15:40:22 +0800
Subject: [PATCH] disable unary, vector mask

---
 clang/lib/Sema/SemaChecking.cpp  | 24 +---
 clang/test/Sema/constant_builtins_vector.cpp |  4 
 2 files changed, 10 insertions(+), 18 deletions(-)

diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 9cac9cf5c4df7..d30ded065228d 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -5169,16 +5169,15 @@ bool Sema::BuiltinComplex(CallExpr *TheCall) {
 
 /// BuiltinShuffleVector - Handle __builtin_shufflevector.
 // This is declared to take (...), so we have to check everything.
+// disable unary, vector mask: (lhs, mask)
+// allow binary, scalar mask: (lhs, rhs, index, ..., index)
 ExprResult Sema::BuiltinShuffleVector(CallExpr *TheCall) {
-  if (TheCall->getNumArgs() < 2)
+  if (TheCall->getNumArgs() <= 2)
 return ExprError(Diag(TheCall->getEndLoc(),
   diag::err_typecheck_call_too_few_args_at_least)
- << 0 /*function call*/ << 2 << TheCall->getNumArgs()
+ << 0 /*function call*/ << 3 << TheCall->getNumArgs()
  << /*is non object*/ 0 << TheCall->getSourceRange());
 
-  // Determine which of the following types of shufflevector we're checking:
-  // 1) unary, vector mask: (lhs, mask)
-  // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
   QualType resType = TheCall->getArg(0)->getType();
   unsigned numElements = 0;
 
@@ -5197,19 +5196,8 @@ ExprResult Sema::BuiltinShuffleVector(CallExpr *TheCall) 
{
 numElements = LHSType->castAs()->getNumElements();
 unsigned numResElements = TheCall->getNumArgs() - 2;
 
-// Check to see if we have a call with 2 vector arguments, the unary 
shuffle
-// with mask.  If so, verify that RHS is an integer vector type with the
-// same number of elts as lhs.
-if (TheCall->getNumArgs() == 2) {
-  if (!RHSType->hasIntegerRepresentation() ||
-  RHSType->castAs()->getNumElements() != numElements)
-return ExprError(Diag(TheCall->getBeginLoc(),
-  diag::err_vec_builtin_incompatible_vector)
- << TheCall->getDirectCallee()
- << /*isMorethantwoArgs*/ false
- << SourceRange(TheCall->getArg(1)->getBeginLoc(),
-TheCall->getArg(1)->getEndLoc()));
-} else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
+
+if (!Context.hasSameUnqualifiedType(LHSType, RHSType) ) {
   return ExprError(Diag(TheCall->getBeginLoc(),
 diag::err_vec_builtin_incompatible_vector)
<< TheCall->getDirectCallee()
diff --git a/clang/test/Sema/constant_builtins_vector.cpp 
b/clang/test/Sema/constant_builtins_vector.cpp
index 8659fa9e46612..d74b1d828c09c 100644
--- a/clang/test/Sema/constant_builtins_vector.cpp
+++ b/clang/test/Sema/constant_builtins_vector.cpp
@@ -692,6 +692,10 @@ constexpr vector4char vector4charConst1 = {0, 1, 2, 3};
 constexpr vector4char vector4charConst2 = {4, 5, 6, 7};
 constexpr vector8char vector8intConst = {8, 9, 10, 11, 12, 13, 14, 15};
 
+
+constexpr vector4char vectorShuffle =
+__builtin_shufflevector(vector4charConst1, vector4charConst2);// 
expected-error {{too few arguments to function call, expected at least 3, have 
2}}
+
 constexpr vector4char vectorShuffle1 =
 __builtin_shufflevector(vector4charConst1, vector4charConst2, 0, 1, 2, 3);
 static_assert(__builtin_bit_cast(unsigned, vectorShuffle1) ==

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


[clang-tools-extra] [clang-tidy] Avoid processing declarations in system headers (PR #128150)

2025-03-08 Thread Balazs Benics via cfe-commits
Carlos =?utf-8?q?Gálvez?= ,
Carlos =?utf-8?q?Gálvez?= 
Message-ID:
In-Reply-To: 


steakhal wrote:

>  I highly discourage implicit slowdowns
> -  If I understand correctly, you mean that this patch could lead to people 
> manually traversing the AST instead of using the MatchFinder, thus making 
> specific checks very slow. Correct? I'm not quite sure how to act upon this, 
> do you have a specific suggestion? I would hope deviating from the "standard 
> pattern" would be caught during code review. Otherwise, this would come out 
> as a bug report fairly soon, as it's easy to profile. So I don't see it as 
> high risk.

and 

> @steakhal was against the checks implicitly triggering the "full analysis".

If I'm not mistaken, currently the PR does not propose an alternative "full 
analysis" mode that we would silently switch to. So, this makes my concern 
void. What I wanted to highlight was that we should definitely not silently 
switch to doing something a lot more expensive. If we wanted to do something 
like that, we should have a clear way delivering log message or diagnostic to 
the user that we are falling back which will likely be a lot slower than it 
could be and this switch was caused by XYZ check.
This would make it actionable from the user's perspective. But like I said, 
it's irrelevant, as we don't have this silent switch.

That said, it would be probably nice to mention in the docs that enabling the 
`SystemHeaders` would likely incur some/significant performance penalty.

I hope I clarified the misunderstanding that my comment may have caused. Sorry 
about that.

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


[clang] [clang][bytecode] Loosen assertion This() for array elements (PR #130399)

2025-03-08 Thread Timm Baeder via cfe-commits

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


[clang] [clang][bytecode] Loosen assertion This() for array elements (PR #130399)

2025-03-08 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `llvm-clang-x86_64-sie-win` 
running on `sie-win-worker` while building `clang` at step 7 
"test-build-unified-tree-check-all".

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


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

```
Step 7 (test-build-unified-tree-check-all) failure: test (failure)
 TEST 'LLVM-Unit :: Support/./SupportTests.exe/6/44' FAILED 

Script(shard):
--
GTEST_OUTPUT=json:Z:\b\llvm-clang-x86_64-sie-win\build\unittests\Support\.\SupportTests.exe-LLVM-Unit-17416-6-44.json
 GTEST_SHUFFLE=0 GTEST_TOTAL_SHARDS=44 GTEST_SHARD_INDEX=6 
Z:\b\llvm-clang-x86_64-sie-win\build\unittests\Support\.\SupportTests.exe
--

Script:
--
Z:\b\llvm-clang-x86_64-sie-win\build\unittests\Support\.\SupportTests.exe 
--gtest_filter=Caching.NoCommit
--
Z:\b\llvm-clang-x86_64-sie-win\llvm-project\llvm\unittests\Support\Caching.cpp(142):
 error: Value of: AddStream
  Actual: false
Expected: true


Z:\b\llvm-clang-x86_64-sie-win\llvm-project\llvm\unittests\Support\Caching.cpp:142
Value of: AddStream
  Actual: false
Expected: true






```



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


[clang-tools-extra] [clang-tidy] `modernize-use-trailing-return-type`: add an option to apply to `void`-returning functions as well (PR #129406)

2025-03-08 Thread Congcong Cai via cfe-commits

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


[clang-tools-extra] added Conflicting Global Accesses checker (PR #130421)

2025-03-08 Thread via cfe-commits

https://github.com/ConcreteCactus created 
https://github.com/llvm/llvm-project/pull/130421

None

>From a166904d772319901abd3ca5f71b32d4d5607f7b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=C3=81ron=20H=C3=A1rn=C3=A1si?= 
Date: Fri, 22 Nov 2024 21:43:04 +0100
Subject: [PATCH] added Conflicting Global Accesses checker

---
 .../bugprone/BugproneTidyModule.cpp   |   3 +
 .../clang-tidy/bugprone/CMakeLists.txt|   1 +
 .../bugprone/ConflictingGlobalAccesses.cpp| 722 ++
 .../bugprone/ConflictingGlobalAccesses.h  |  62 ++
 .../bugprone/conflicting-global-accesses.cpp  | 267 +++
 5 files changed, 1055 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/ConflictingGlobalAccesses.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/ConflictingGlobalAccesses.h
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/conflicting-global-accesses.cpp

diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index 0a3376949b6e5..5418e718a404e 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -19,6 +19,7 @@
 #include "CastingThroughVoidCheck.h"
 #include "ChainedComparisonCheck.h"
 #include "ComparePointerToMemberVirtualFunctionCheck.h"
+#include "ConflictingGlobalAccesses.h"
 #include "CopyConstructorInitCheck.h"
 #include "CrtpConstructorAccessibilityCheck.h"
 #include "DanglingHandleCheck.h"
@@ -124,6 +125,8 @@ class BugproneModule : public ClangTidyModule {
 "bugprone-chained-comparison");
 CheckFactories.registerCheck(
 "bugprone-compare-pointer-to-member-virtual-function");
+CheckFactories.registerCheck(
+"bugprone-conflicting-global-accesses");
 CheckFactories.registerCheck(
 "bugprone-copy-constructor-init");
 CheckFactories.registerCheck(
diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
index dab139b77c770..b66ef8ea3634b 100644
--- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
@@ -15,6 +15,7 @@ add_clang_library(clangTidyBugproneModule STATIC
   CastingThroughVoidCheck.cpp
   ChainedComparisonCheck.cpp
   ComparePointerToMemberVirtualFunctionCheck.cpp
+  ConflictingGlobalAccesses.cpp
   CopyConstructorInitCheck.cpp
   CrtpConstructorAccessibilityCheck.cpp
   DanglingHandleCheck.cpp
diff --git 
a/clang-tools-extra/clang-tidy/bugprone/ConflictingGlobalAccesses.cpp 
b/clang-tools-extra/clang-tidy/bugprone/ConflictingGlobalAccesses.cpp
new file mode 100644
index 0..da84864c6947a
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/ConflictingGlobalAccesses.cpp
@@ -0,0 +1,722 @@
+//===--===//
+//
+// 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 "ConflictingGlobalAccesses.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+// An AccesKind represents one access to a global variable.
+//
+// The unchecked versions represent reads/writes that are not handled by
+// -Wunsequenced. (e.g. accesses inside functions).
+using AccessKind = uint8_t;
+static constexpr AccessKind AkRead = 0;
+static constexpr AccessKind AkWrite = 1;
+static constexpr AccessKind AkUncheckedRead = 2;
+static constexpr AccessKind AkUncheckedWrite = 3;
+
+static constexpr uint8_t AkCount = 4;
+
+// The TraversalResultKind represents a set of accesses.
+// Bits are corresponding to the AccessKind enum values.
+using TraversalResultKind = uint8_t;
+static constexpr TraversalResultKind TrInvalid = 0;
+static constexpr TraversalResultKind TrRead = 1 << AkRead;
+static constexpr TraversalResultKind TrWrite = 1 << AkWrite;
+static constexpr TraversalResultKind TrUncheckedWrite = 1 << AkUncheckedWrite;
+
+// To represent fields in structs or unions we use numbered FieldIndices. The
+// FieldIndexArray represents one field inside a global struct/union system.
+// The FieldIndexArray can be thought of as a path inside a tree.
+using FieldIndex = uint16_t;
+static constexpr FieldIndex FiUnion = 0x8000;
+
+// Note: This bit signals whether the field is a *field of* a struct or a
+// union, not whether the type of the field itself is a struct or a union.
+using FieldIndexArray = SmallVector;
+
+/// One traversal recurses into one side of a binary expression or one
+/// parameter of a function call. At least two of these traversals are used to
+/// find conflicting accesses.
+///
+/// A TraversalResult represents one traversal.
+struct Travers

[clang] [llvm] [AArch64][SVE] Improve fixed-length addressing modes. (PR #129732)

2025-03-08 Thread Ricardo Jesus via cfe-commits

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


[clang] [clang][bytecode] Implement __builtin_{memchr,strchr,char_memchr} (PR #130420)

2025-03-08 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `llvm-clang-win-x-aarch64` 
running on `as-builder-2` while building `clang` at step 9 "test-check-llvm".

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


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

```
Step 9 (test-check-llvm) failure: Test just built components: check-llvm 
completed (failure)
 TEST 'LLVM-Unit :: Support/./SupportTests.exe/51/87' 
FAILED 
Script(shard):
--
GTEST_OUTPUT=json:C:\buildbot\as-builder-2\x-aarch64\build\unittests\Support\.\SupportTests.exe-LLVM-Unit-10400-51-87.json
 GTEST_SHUFFLE=0 GTEST_TOTAL_SHARDS=87 GTEST_SHARD_INDEX=51 
C:\buildbot\as-builder-2\x-aarch64\build\unittests\Support\.\SupportTests.exe
--

Script:
--
C:\buildbot\as-builder-2\x-aarch64\build\unittests\Support\.\SupportTests.exe 
--gtest_filter=Caching.NoCommit
--
C:\buildbot\as-builder-2\x-aarch64\llvm-project\llvm\unittests\Support\Caching.cpp(142):
 error: Value of: AddStream
  Actual: false
Expected: true


C:\buildbot\as-builder-2\x-aarch64\llvm-project\llvm\unittests\Support\Caching.cpp:142
Value of: AddStream
  Actual: false
Expected: true






```



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


[clang] [clang][bytecode][NFC] Check conditional op condition for ConstantExprs (PR #130425)

2025-03-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

Same thing we now do in if statements. Check the condition of a conditional 
operator for a statically known true/false value.

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


1 Files Affected:

- (modified) clang/lib/AST/ByteCode/Compiler.cpp (+29-19) 


``diff
diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index d192b8b91c72e..9a52dd4105437 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -25,6 +25,16 @@ using APSInt = llvm::APSInt;
 namespace clang {
 namespace interp {
 
+static std::optional getBoolValue(const Expr *E) {
+  if (const auto *CE = dyn_cast_if_present(E);
+  CE && CE->hasAPValueResult() &&
+  CE->getResultAPValueKind() == APValue::ValueKind::Int) {
+return CE->getResultAsAPSInt().getBoolValue();
+  }
+
+  return std::nullopt;
+}
+
 /// Scope used to handle temporaries in toplevel variable declarations.
 template  class DeclScope final : public LocalScope {
 public:
@@ -2286,6 +2296,19 @@ bool Compiler::VisitAbstractConditionalOperator(
   const Expr *TrueExpr = E->getTrueExpr();
   const Expr *FalseExpr = E->getFalseExpr();
 
+  auto visitChildExpr = [&](const Expr *E) -> bool {
+LocalScope S(this);
+if (!this->delegate(E))
+  return false;
+return S.destroyLocals();
+  };
+
+  if (std::optional BoolValue = getBoolValue(Condition)) {
+if (BoolValue)
+  return visitChildExpr(TrueExpr);
+return visitChildExpr(FalseExpr);
+  }
+
   LabelTy LabelEnd = this->getLabel();   // Label after the operator.
   LabelTy LabelFalse = this->getLabel(); // Label for the false expr.
 
@@ -2295,26 +2318,16 @@ bool 
Compiler::VisitAbstractConditionalOperator(
   if (!this->jumpFalse(LabelFalse))
 return false;
 
-  {
-LocalScope S(this);
-if (!this->delegate(TrueExpr))
-  return false;
-if (!S.destroyLocals())
-  return false;
-  }
+  if (!visitChildExpr(TrueExpr))
+return false;
 
   if (!this->jump(LabelEnd))
 return false;
 
   this->emitLabel(LabelFalse);
 
-  {
-LocalScope S(this);
-if (!this->delegate(FalseExpr))
-  return false;
-if (!S.destroyLocals())
-  return false;
-  }
+  if (!visitChildExpr(FalseExpr))
+return false;
 
   this->fallthrough(LabelEnd);
   this->emitLabel(LabelEnd);
@@ -5207,11 +5220,8 @@ template  bool 
Compiler::visitIfStmt(const IfStmt *IS) {
   // stataically known to be either true or false. We could look at more cases
   // here, but I think all the ones that actually happen are using a
   // ConstantExpr.
-  if (const auto *CE = dyn_cast_if_present(IS->getCond());
-  CE && CE->hasAPValueResult() &&
-  CE->getResultAPValueKind() == APValue::ValueKind::Int) {
-APSInt Value = CE->getResultAsAPSInt();
-if (Value.getBoolValue())
+  if (std::optional BoolValue = getBoolValue(IS->getCond())) {
+if (*BoolValue)
   return visitChildStmt(IS->getThen());
 else if (const Stmt *Else = IS->getElse())
   return visitChildStmt(Else);

``




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


[clang] [clang][bytecode][NFC] Check conditional op condition for ConstantExprs (PR #130425)

2025-03-08 Thread Timm Baeder via cfe-commits

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

Same thing we now do in if statements. Check the condition of a conditional 
operator for a statically known true/false value.

>From 6543c75f7b5ea03b6061637f18b8a97c3ce48410 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Sat, 8 Mar 2025 18:00:38 +0100
Subject: [PATCH] [clang][bytecode][NFC] Check conditional op condition for
 ConstantExprs

Same thing we now do in if statements. Check the condition of a
conditional operator for a statically known true/false value.
---
 clang/lib/AST/ByteCode/Compiler.cpp | 48 +
 1 file changed, 29 insertions(+), 19 deletions(-)

diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index d192b8b91c72e..9a52dd4105437 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -25,6 +25,16 @@ using APSInt = llvm::APSInt;
 namespace clang {
 namespace interp {
 
+static std::optional getBoolValue(const Expr *E) {
+  if (const auto *CE = dyn_cast_if_present(E);
+  CE && CE->hasAPValueResult() &&
+  CE->getResultAPValueKind() == APValue::ValueKind::Int) {
+return CE->getResultAsAPSInt().getBoolValue();
+  }
+
+  return std::nullopt;
+}
+
 /// Scope used to handle temporaries in toplevel variable declarations.
 template  class DeclScope final : public LocalScope {
 public:
@@ -2286,6 +2296,19 @@ bool Compiler::VisitAbstractConditionalOperator(
   const Expr *TrueExpr = E->getTrueExpr();
   const Expr *FalseExpr = E->getFalseExpr();
 
+  auto visitChildExpr = [&](const Expr *E) -> bool {
+LocalScope S(this);
+if (!this->delegate(E))
+  return false;
+return S.destroyLocals();
+  };
+
+  if (std::optional BoolValue = getBoolValue(Condition)) {
+if (BoolValue)
+  return visitChildExpr(TrueExpr);
+return visitChildExpr(FalseExpr);
+  }
+
   LabelTy LabelEnd = this->getLabel();   // Label after the operator.
   LabelTy LabelFalse = this->getLabel(); // Label for the false expr.
 
@@ -2295,26 +2318,16 @@ bool 
Compiler::VisitAbstractConditionalOperator(
   if (!this->jumpFalse(LabelFalse))
 return false;
 
-  {
-LocalScope S(this);
-if (!this->delegate(TrueExpr))
-  return false;
-if (!S.destroyLocals())
-  return false;
-  }
+  if (!visitChildExpr(TrueExpr))
+return false;
 
   if (!this->jump(LabelEnd))
 return false;
 
   this->emitLabel(LabelFalse);
 
-  {
-LocalScope S(this);
-if (!this->delegate(FalseExpr))
-  return false;
-if (!S.destroyLocals())
-  return false;
-  }
+  if (!visitChildExpr(FalseExpr))
+return false;
 
   this->fallthrough(LabelEnd);
   this->emitLabel(LabelEnd);
@@ -5207,11 +5220,8 @@ template  bool 
Compiler::visitIfStmt(const IfStmt *IS) {
   // stataically known to be either true or false. We could look at more cases
   // here, but I think all the ones that actually happen are using a
   // ConstantExpr.
-  if (const auto *CE = dyn_cast_if_present(IS->getCond());
-  CE && CE->hasAPValueResult() &&
-  CE->getResultAPValueKind() == APValue::ValueKind::Int) {
-APSInt Value = CE->getResultAsAPSInt();
-if (Value.getBoolValue())
+  if (std::optional BoolValue = getBoolValue(IS->getCond())) {
+if (*BoolValue)
   return visitChildStmt(IS->getThen());
 else if (const Stmt *Else = IS->getElse())
   return visitChildStmt(Else);

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


[clang] e4fe22a - [clang][bytecode][NFC] Check conditional op condition for ConstantExprs (#130425)

2025-03-08 Thread via cfe-commits

Author: Timm Baeder
Date: 2025-03-08T18:29:19+01:00
New Revision: e4fe22a8bd1853331d4811546ac038252baee79d

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

LOG: [clang][bytecode][NFC] Check conditional op condition for ConstantExprs 
(#130425)

Same thing we now do in if statements. Check the condition of a
conditional operator for a statically known true/false value.

Added: 


Modified: 
clang/lib/AST/ByteCode/Compiler.cpp

Removed: 




diff  --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index d192b8b91c72e..9a52dd4105437 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -25,6 +25,16 @@ using APSInt = llvm::APSInt;
 namespace clang {
 namespace interp {
 
+static std::optional getBoolValue(const Expr *E) {
+  if (const auto *CE = dyn_cast_if_present(E);
+  CE && CE->hasAPValueResult() &&
+  CE->getResultAPValueKind() == APValue::ValueKind::Int) {
+return CE->getResultAsAPSInt().getBoolValue();
+  }
+
+  return std::nullopt;
+}
+
 /// Scope used to handle temporaries in toplevel variable declarations.
 template  class DeclScope final : public LocalScope {
 public:
@@ -2286,6 +2296,19 @@ bool Compiler::VisitAbstractConditionalOperator(
   const Expr *TrueExpr = E->getTrueExpr();
   const Expr *FalseExpr = E->getFalseExpr();
 
+  auto visitChildExpr = [&](const Expr *E) -> bool {
+LocalScope S(this);
+if (!this->delegate(E))
+  return false;
+return S.destroyLocals();
+  };
+
+  if (std::optional BoolValue = getBoolValue(Condition)) {
+if (BoolValue)
+  return visitChildExpr(TrueExpr);
+return visitChildExpr(FalseExpr);
+  }
+
   LabelTy LabelEnd = this->getLabel();   // Label after the operator.
   LabelTy LabelFalse = this->getLabel(); // Label for the false expr.
 
@@ -2295,26 +2318,16 @@ bool 
Compiler::VisitAbstractConditionalOperator(
   if (!this->jumpFalse(LabelFalse))
 return false;
 
-  {
-LocalScope S(this);
-if (!this->delegate(TrueExpr))
-  return false;
-if (!S.destroyLocals())
-  return false;
-  }
+  if (!visitChildExpr(TrueExpr))
+return false;
 
   if (!this->jump(LabelEnd))
 return false;
 
   this->emitLabel(LabelFalse);
 
-  {
-LocalScope S(this);
-if (!this->delegate(FalseExpr))
-  return false;
-if (!S.destroyLocals())
-  return false;
-  }
+  if (!visitChildExpr(FalseExpr))
+return false;
 
   this->fallthrough(LabelEnd);
   this->emitLabel(LabelEnd);
@@ -5207,11 +5220,8 @@ template  bool 
Compiler::visitIfStmt(const IfStmt *IS) {
   // stataically known to be either true or false. We could look at more cases
   // here, but I think all the ones that actually happen are using a
   // ConstantExpr.
-  if (const auto *CE = dyn_cast_if_present(IS->getCond());
-  CE && CE->hasAPValueResult() &&
-  CE->getResultAPValueKind() == APValue::ValueKind::Int) {
-APSInt Value = CE->getResultAsAPSInt();
-if (Value.getBoolValue())
+  if (std::optional BoolValue = getBoolValue(IS->getCond())) {
+if (*BoolValue)
   return visitChildStmt(IS->getThen());
 else if (const Stmt *Else = IS->getElse())
   return visitChildStmt(Else);



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


[clang] [clang][bytecode][NFC] Check conditional op condition for ConstantExprs (PR #130425)

2025-03-08 Thread Timm Baeder via cfe-commits

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


[clang] [clang][bytecode] Surround bcp condition with Start/EndSpeculation (PR #130427)

2025-03-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

This is similar to what the current interpreter is doing - the FoldConstant 
RAII object surrounds the entire HandleConditionalOperator call, which means 
the condition and both TrueExpr or FalseExpr.

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


2 Files Affected:

- (modified) clang/lib/AST/ByteCode/Compiler.cpp (+13-6) 
- (modified) clang/test/AST/ByteCode/builtin-constant-p.cpp (+2-5) 


``diff
diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index 9a52dd4105437..13b8a3b47add6 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -2309,29 +2309,36 @@ bool 
Compiler::VisitAbstractConditionalOperator(
 return visitChildExpr(FalseExpr);
   }
 
+  bool IsBcpCall = false;
+  if (const auto *CE = dyn_cast(Condition->IgnoreParenCasts());
+  CE && CE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) {
+IsBcpCall = true;
+  }
+
   LabelTy LabelEnd = this->getLabel();   // Label after the operator.
   LabelTy LabelFalse = this->getLabel(); // Label for the false expr.
 
+  if (IsBcpCall) {
+if (!this->emitStartSpeculation(E))
+  return false;
+  }
+
   if (!this->visitBool(Condition))
 return false;
-
   if (!this->jumpFalse(LabelFalse))
 return false;
-
   if (!visitChildExpr(TrueExpr))
 return false;
-
   if (!this->jump(LabelEnd))
 return false;
-
   this->emitLabel(LabelFalse);
-
   if (!visitChildExpr(FalseExpr))
 return false;
-
   this->fallthrough(LabelEnd);
   this->emitLabel(LabelEnd);
 
+  if (IsBcpCall)
+return this->emitEndSpeculation(E);
   return true;
 }
 
diff --git a/clang/test/AST/ByteCode/builtin-constant-p.cpp 
b/clang/test/AST/ByteCode/builtin-constant-p.cpp
index b309fa8296889..ed9e606ed16aa 100644
--- a/clang/test/AST/ByteCode/builtin-constant-p.cpp
+++ b/clang/test/AST/ByteCode/builtin-constant-p.cpp
@@ -59,13 +59,10 @@ template constexpr bool bcp(T t) {
 }
 
 constexpr intptr_t ptr_to_int(const void *p) {
-  return __builtin_constant_p(1) ? (intptr_t)p : (intptr_t)p; // expected-note 
{{cast that performs the conversions of a reinterpret_cast}}
+  return __builtin_constant_p(1) ? (intptr_t)p : (intptr_t)p;
 }
 
-/// This is from test/SemaCXX/builtin-constant-p.cpp, but it makes no sense.
-/// ptr_to_int is called before bcp(), so it fails. GCC does not accept this 
either.
-static_assert(bcp(ptr_to_int("foo"))); // expected-error {{not an integral 
constant expression}} \
-   // expected-note {{in call to}}
+static_assert(bcp(ptr_to_int("foo")));
 
 constexpr bool AndFold(const int &a, const int &b) {
   return __builtin_constant_p(a && b);

``




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


[clang] aff6ab9 - [clang][bytecode] Surround bcp condition with Start/EndSpeculation (#130427)

2025-03-08 Thread via cfe-commits

Author: Timm Baeder
Date: 2025-03-08T19:37:20+01:00
New Revision: aff6ab9d90d23c46bc5f4b909d54bfa9c95c9f03

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

LOG: [clang][bytecode] Surround bcp condition with Start/EndSpeculation 
(#130427)

This is similar to what the current interpreter is doing - the
FoldConstant RAII object surrounds the entire HandleConditionalOperator
call, which means the condition and both TrueExpr or FalseExpr.

Added: 


Modified: 
clang/lib/AST/ByteCode/Compiler.cpp
clang/test/AST/ByteCode/builtin-constant-p.cpp

Removed: 




diff  --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index 9a52dd4105437..13b8a3b47add6 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -2309,29 +2309,36 @@ bool 
Compiler::VisitAbstractConditionalOperator(
 return visitChildExpr(FalseExpr);
   }
 
+  bool IsBcpCall = false;
+  if (const auto *CE = dyn_cast(Condition->IgnoreParenCasts());
+  CE && CE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) {
+IsBcpCall = true;
+  }
+
   LabelTy LabelEnd = this->getLabel();   // Label after the operator.
   LabelTy LabelFalse = this->getLabel(); // Label for the false expr.
 
+  if (IsBcpCall) {
+if (!this->emitStartSpeculation(E))
+  return false;
+  }
+
   if (!this->visitBool(Condition))
 return false;
-
   if (!this->jumpFalse(LabelFalse))
 return false;
-
   if (!visitChildExpr(TrueExpr))
 return false;
-
   if (!this->jump(LabelEnd))
 return false;
-
   this->emitLabel(LabelFalse);
-
   if (!visitChildExpr(FalseExpr))
 return false;
-
   this->fallthrough(LabelEnd);
   this->emitLabel(LabelEnd);
 
+  if (IsBcpCall)
+return this->emitEndSpeculation(E);
   return true;
 }
 

diff  --git a/clang/test/AST/ByteCode/builtin-constant-p.cpp 
b/clang/test/AST/ByteCode/builtin-constant-p.cpp
index b309fa8296889..ed9e606ed16aa 100644
--- a/clang/test/AST/ByteCode/builtin-constant-p.cpp
+++ b/clang/test/AST/ByteCode/builtin-constant-p.cpp
@@ -59,13 +59,10 @@ template constexpr bool bcp(T t) {
 }
 
 constexpr intptr_t ptr_to_int(const void *p) {
-  return __builtin_constant_p(1) ? (intptr_t)p : (intptr_t)p; // expected-note 
{{cast that performs the conversions of a reinterpret_cast}}
+  return __builtin_constant_p(1) ? (intptr_t)p : (intptr_t)p;
 }
 
-/// This is from test/SemaCXX/builtin-constant-p.cpp, but it makes no sense.
-/// ptr_to_int is called before bcp(), so it fails. GCC does not accept this 
either.
-static_assert(bcp(ptr_to_int("foo"))); // expected-error {{not an integral 
constant expression}} \
-   // expected-note {{in call to}}
+static_assert(bcp(ptr_to_int("foo")));
 
 constexpr bool AndFold(const int &a, const int &b) {
   return __builtin_constant_p(a && b);



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


[clang] Change `ASTUnit::getASTContext() const` to return a non-const `ASTContext` (PR #130096)

2025-03-08 Thread Boaz Brickner via cfe-commits

bricknerb wrote:

Thanks for the feedback!

Is there a way to call `ASTContext::createMangleContext()` when I have a `const 
ASTUnit`?
I've tried to make `ASTContext::createMangleContext()` const but this failed as 
it seems to actually call methods that potentially modify the context.

However, when I have a `const Decl`, I can just call 
`getAstContext().createMangleContext()`.

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


[clang] [compiler-rt] [llvm] [SystemZ] Add support for half (fp16) (PR #109164)

2025-03-08 Thread Ulrich Weigand via cfe-commits


@@ -0,0 +1,27 @@
+//===-- lib/extendhfdf2.c - half -> single conversion -*- 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
+//
+//===--===//
+
+#define SRC_HALF
+#define DST_DOUBLE
+#include "fp_extend_impl.inc"
+
+// Use a forwarding definition and noinline to implement a poor man's alias,
+// as there isn't a good cross-platform way of defining one.
+COMPILER_RT_ABI NOINLINE float __extendhfdf2(src_t a) {
+  return __extendXfYf2__(a);
+}
+
+COMPILER_RT_ABI float __gnu_h2d_ieee(src_t a) { return __extendhfdf2(a); }

uweigand wrote:

I don't think you should define the `__gnu_h2d_ieee` or the `__aeabi_h2d` names 
here - those are not defined by the ARM standard or by other compilers today.  
This function should *only* be present under the `__extendhfdf2` name.

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


[clang] [clang] Fix FP -Wformat in functions with 2+ attribute((format)) (PR #129954)

2025-03-08 Thread via cfe-commits

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

Successfully tested this locally! Thanks for the fix!

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


[clang] 3b8f9a2 - [clang][bytecode] Loosen assertion This() for array elements (#130399)

2025-03-08 Thread via cfe-commits

Author: Timm Baeder
Date: 2025-03-08T13:13:52+01:00
New Revision: 3b8f9a228c5f12f282778b18117b9a88c07e87cb

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

LOG: [clang][bytecode] Loosen assertion This() for array elements (#130399)

getRecord() returns null on array elements, even for composite arrays.
The assertion here was overly restrictive and having an array element as
instance pointer should be fine otherwise.

Added: 


Modified: 
clang/lib/AST/ByteCode/Interp.h
clang/test/AST/ByteCode/placement-new.cpp

Removed: 




diff  --git a/clang/lib/AST/ByteCode/Interp.h b/clang/lib/AST/ByteCode/Interp.h
index 401bbefaf9a92..f2ddeac99cd7e 100644
--- a/clang/lib/AST/ByteCode/Interp.h
+++ b/clang/lib/AST/ByteCode/Interp.h
@@ -2432,9 +2432,12 @@ inline bool This(InterpState &S, CodePtr OpPC) {
   // Ensure the This pointer has been cast to the correct base.
   if (!This.isDummy()) {
 assert(isa(S.Current->getFunction()->getDecl()));
-assert(This.getRecord());
+[[maybe_unused]] const Record *R = This.getRecord();
+if (!R)
+  R = This.narrow().getRecord();
+assert(R);
 assert(
-This.getRecord()->getDecl() ==
+R->getDecl() ==
 cast(S.Current->getFunction()->getDecl())->getParent());
   }
 

diff  --git a/clang/test/AST/ByteCode/placement-new.cpp 
b/clang/test/AST/ByteCode/placement-new.cpp
index 7a4fc89a27dac..c353162a7aab0 100644
--- a/clang/test/AST/ByteCode/placement-new.cpp
+++ b/clang/test/AST/ByteCode/placement-new.cpp
@@ -339,6 +339,30 @@ namespace PR48606 {
   static_assert(f());
 }
 
+/// This used to crash because of an assertion in the implementation
+/// of the This instruction.
+namespace ExplicitThisOnArrayElement {
+  struct S {
+int a = 12;
+constexpr S(int a) {
+  this->a = a;
+}
+  };
+
+  template 
+  constexpr void construct_at(_Tp *__location, _Args &&...__args) {
+new (__location) _Tp(__args...);
+  }
+
+  constexpr bool foo() {
+auto *M = std::allocator().allocate(13); // both-note {{allocation 
performed here was not deallocated}}
+construct_at(M, 12);
+return true;
+  }
+
+  static_assert(foo()); // both-error {{not an integral constant expression}}
+}
+
 #ifdef BYTECODE
 constexpr int N = [] // expected-error {{must be initialized by a constant 
expression}} \
  // expected-note {{assignment to dereferenced 
one-past-the-end pointer is not allowed in a constant expression}} \



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


[clang] [ARM] Using cp15 while mtp =auto and arch is arm_arch6k and support thumb2 (PR #130027)

2025-03-08 Thread via cfe-commits


@@ -208,10 +208,17 @@ bool arm::useAAPCSForMachO(const llvm::Triple &T) {
 bool arm::isHardTPSupported(const llvm::Triple &Triple) {
   int Ver = getARMSubArchVersionNumber(Triple);
   llvm::ARM::ArchKind AK = llvm::ARM::parseArch(Triple.getArchName());
-  return Triple.isARM() || AK == llvm::ARM::ArchKind::ARMV6T2 ||
- (Ver >= 7 && AK != llvm::ARM::ArchKind::ARMV8MBaseline);
+  return Triple.isARM() || (Ver >= 7 && AK != 
llvm::ARM::ArchKind::ARMV8MBaseline);
 }
 
+
+// We follow GCC mtp=auto when arch is arm_arch6k and support thumb2
+bool arm::isHardTPAndThumb2(const llvm::Triple &Triple) {
+  llvm::ARM::ArchKind AK = llvm::ARM::parseArch(Triple.getArchName());
+  return Triple.isARM() && AK >= llvm::ARM::ArchKind::ARMV6K && AK != 
llvm::ARM::ArchKind::ARMV8MBaseline;

Zhenhang1213 wrote:

yes,I want to rewrite this interface

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


[clang] [Clang] Treat `ext_vector_type` as a regular type attribute (PR #130177)

2025-03-08 Thread Joseph Huber via cfe-commits

https://github.com/jhuber6 updated 
https://github.com/llvm/llvm-project/pull/130177

>From 728e1bd9cccb56a0acaf5abb35fe64cacc5b4ae9 Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Thu, 6 Mar 2025 15:08:25 -0600
Subject: [PATCH 1/7] [Clang] Treat `ext_vector_type` as a regular type
 attribute

Summary:
This attribute is mostly borrowed from OpenCL, but is useful in general
for accessing the LLVM vector types. Previously the only way to use it
was through typedefs. This patch changes that to allow use as a regular
type attribute, similar to address spaces.
---
 clang/docs/ReleaseNotes.rst   |  1 +
 clang/include/clang/Basic/Attr.td | 13 +++--
 clang/include/clang/Basic/AttrDocs.td | 23 +++
 clang/lib/Sema/SemaDeclAttr.cpp   |  3 ++-
 clang/test/CodeGenCUDA/amdgpu-bf16.cu | 12 
 clang/test/Sema/types.c   |  2 +-
 6 files changed, 34 insertions(+), 20 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 86bf836b4a999..695c458b36702 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -145,6 +145,7 @@ Adding [[clang::unsafe_buffer_usage]] attribute to a method 
definition now turns
 related warnings within the method body.
 
 - The ``no_sanitize`` attribute now accepts both ``gnu`` and ``clang`` names.
+- The ``ext_vector_type(n)`` attribute can now be used as a generic type 
attribute.
 - Clang now diagnoses use of declaration attributes on void parameters. 
(#GH108819)
 - Clang now allows ``__attribute__((model("small")))`` and
   ``__attribute__((model("large")))`` on non-TLS globals in x86-64 
compilations.
diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index dc9b462126125..161a4fe8e0f12 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1721,17 +1721,10 @@ def EnableIf : InheritableAttr {
   let Documentation = [EnableIfDocs];
 }
 
-def ExtVectorType : Attr {
-  // This is an OpenCL-related attribute and does not receive a [[]] spelling.
-  let Spellings = [GNU<"ext_vector_type">];
-  // FIXME: This subject list is wrong; this is a type attribute.
-  let Subjects = SubjectList<[TypedefName], ErrorDiag>;
+def ExtVectorType : TypeAttr {
+  let Spellings = [Clang<"ext_vector_type">];
   let Args = [ExprArgument<"NumElements">];
-  let ASTNode = 0;
-  let Documentation = [Undocumented];
-  // This is a type attribute with an incorrect subject list, so should not be
-  // permitted by #pragma clang attribute.
-  let PragmaAttributeSupport = 0;
+  let Documentation = [ExtVectorTypeDocs];
 }
 
 def FallThrough : StmtAttr {
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index f44fad95423ee..c309b4849b731 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -1113,6 +1113,29 @@ template instantiation, so the value for ``T::number`` 
is known.
   }];
 }
 
+def ExtVectorTypeDocs : Documentation {
+  let Category = DocCatFunction;
+  let Content = [{
+
+The ext_vector_type(N) attribute specifies that a type is a vector with N
+elements, directly mapping to an LLVM vector type. Originally from OpenCL, it
+allows element access via [] or x, y, z, w for graphics-style indexing. This
+attribute enables efficient SIMD operations and is usable in general-purpose
+code.
+
+.. code-block:: c++
+
+  template 
+  constexpr T simd_reduce(T [[clang::ext_vector_type(N)]] v) {
+T sum{};
+for (uint32_t i = 0; i < N; ++i) {
+  sum += v[i];
+}
+return sum;
+  }
+  }];
+}
+
 def DiagnoseIfDocs : Documentation {
   let Category = DocCatFunction;
   let Content = [{
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index 1405ee5341dcf..d32320c581656 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -1191,7 +1191,8 @@ static void handleTestTypestateAttr(Sema &S, Decl *D, 
const ParsedAttr &AL) {
 
 static void handleExtVectorTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
   // Remember this typedef decl, we will need it later for diagnostics.
-  S.ExtVectorDecls.push_back(cast(D));
+  if (isa(D))
+S.ExtVectorDecls.push_back(cast(D));
 }
 
 static void handlePackedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
diff --git a/clang/test/CodeGenCUDA/amdgpu-bf16.cu 
b/clang/test/CodeGenCUDA/amdgpu-bf16.cu
index 4610b4ae3cbe5..f6533d7faf296 100644
--- a/clang/test/CodeGenCUDA/amdgpu-bf16.cu
+++ b/clang/test/CodeGenCUDA/amdgpu-bf16.cu
@@ -111,19 +111,15 @@ __device__ __bf16 test_call( __bf16 in) {
 // CHECK-NEXT:ret void
 //
 __device__ void test_vec_assign() {
-  typedef __attribute__((ext_vector_type(2))) __bf16 bf16_x2;
-  bf16_x2 vec2_a, vec2_b;
+  __bf16 [[clang::ext_vector_type(2)]] vec2_a, vec2_b;
   vec2_a = vec2_b;
 
-  typedef __attribute__((ext_vector_type(4))) __bf16 bf16_x4;
-  bf16_x4 vec4_a, vec4_b;
+  __bf16 [[clang::ext_vector_type(4)]] v

[clang] c4ed0ad - [Clang] Fix typo 'dereferencable' to 'dereferenceable' (#116761)

2025-03-08 Thread via cfe-commits

Author: Liberty
Date: 2025-03-08T19:35:20Z
New Revision: c4ed0ad1f52a7bec7377bbaf75f812527ec739bd

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

LOG: [Clang] Fix typo 'dereferencable' to 'dereferenceable' (#116761)

This patch corrects the typo 'dereferencable' to 'dereferenceable' in
CGCall.cpp.
The typo is located within a comment inside the `void
CodeGenModule::ConstructAttributeList` function.

Added: 


Modified: 
clang/lib/CodeGen/CGCall.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index bfcbc273dbda7..7aa77e55dbfcc 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -2705,7 +2705,7 @@ void CodeGenModule::ConstructAttributeList(StringRef Name,
 llvm::AttributeSet::get(getLLVMContext(), Attrs);
   }
 
-  // Apply `nonnull`, `dereferencable(N)` and `align N` to the `this` argument,
+  // Apply `nonnull`, `dereferenceable(N)` and `align N` to the `this` 
argument,
   // unless this is a thunk function.
   // FIXME: fix this properly, https://reviews.llvm.org/D100388
   if (FI.isInstanceMethod() && !IRFunctionArgs.hasInallocaArg() &&



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


[clang] [Clang] Fix typo 'dereferencable' to 'dereferenceable' (PR #116761)

2025-03-08 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder 
`openmp-offload-amdgpu-runtime-2` running on `rocm-worker-hw-02` while building 
`clang` at step 8 "Add check check-llvm".

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


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

```
Step 8 (Add check check-llvm) failure: test (failure)
 TEST 'LLVM-Unit :: Support/./SupportTests/134/175' FAILED 

Script(shard):
--
GTEST_OUTPUT=json:/home/botworker/builds/openmp-offload-amdgpu-runtime-2/llvm.build/unittests/Support/./SupportTests-LLVM-Unit-679404-134-175.json
 GTEST_SHUFFLE=0 GTEST_TOTAL_SHARDS=175 GTEST_SHARD_INDEX=134 
/home/botworker/builds/openmp-offload-amdgpu-runtime-2/llvm.build/unittests/Support/./SupportTests
--

Script:
--
/home/botworker/builds/openmp-offload-amdgpu-runtime-2/llvm.build/unittests/Support/./SupportTests
 --gtest_filter=Caching.Normal
--
/home/botworker/builds/openmp-offload-amdgpu-runtime-2/llvm.src/llvm/unittests/Support/Caching.cpp:55:
 Failure
Value of: AddStream
  Actual: false
Expected: true


/home/botworker/builds/openmp-offload-amdgpu-runtime-2/llvm.src/llvm/unittests/Support/Caching.cpp:55
Value of: AddStream
  Actual: false
Expected: true






```



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


[clang] [clang][bytecode][NFC] Bail out on non constant evaluated builtins (PR #130431)

2025-03-08 Thread Timm Baeder via cfe-commits

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

If the ASTContext says so, don't bother trying to constant evaluate the given 
builtin.

>From 1a085cf37983ca5acef83939371a5fee9d5f1813 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Sat, 8 Mar 2025 20:09:41 +0100
Subject: [PATCH] [clang][bytecode][NFC] Bail out on non constant evaluated
 builtins

If the ASTContext says so, don't bother trying to constant evaluate the
given builtin.
---
 clang/lib/AST/ByteCode/InterpBuiltin.cpp | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp 
b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index b8c4ef2f48a79..14e716daa3f12 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -2059,6 +2059,9 @@ static bool interp__builtin_memchr(InterpState &S, 
CodePtr OpPC,
 
 bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const Function *F,
   const CallExpr *Call, uint32_t BuiltinID) {
+  if (!S.getASTContext().BuiltinInfo.isConstantEvaluated(BuiltinID))
+return false;
+
   const InterpFrame *Frame = S.Current;
 
   std::optional ReturnT = S.getContext().classify(Call);

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


[clang] [clang][bytecode][NFC] Bail out on non constant evaluated builtins (PR #130431)

2025-03-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

If the ASTContext says so, don't bother trying to constant evaluate the given 
builtin.

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


1 Files Affected:

- (modified) clang/lib/AST/ByteCode/InterpBuiltin.cpp (+3) 


``diff
diff --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp 
b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index b8c4ef2f48a79..14e716daa3f12 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -2059,6 +2059,9 @@ static bool interp__builtin_memchr(InterpState &S, 
CodePtr OpPC,
 
 bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const Function *F,
   const CallExpr *Call, uint32_t BuiltinID) {
+  if (!S.getASTContext().BuiltinInfo.isConstantEvaluated(BuiltinID))
+return false;
+
   const InterpFrame *Frame = S.Current;
 
   std::optional ReturnT = S.getContext().classify(Call);

``




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


[clang] [Clang] Fix typo 'dereferencable' to 'dereferenceable' (PR #116761)

2025-03-08 Thread via cfe-commits

github-actions[bot] wrote:



@kordood Congratulations on having your first Pull Request (PR) merged into the 
LLVM Project!

Your changes will be combined with recent changes from other authors, then 
tested by our [build bots](https://lab.llvm.org/buildbot/). If there is a 
problem with a build, you may receive a report in an email or a comment on this 
PR.

Please check whether problems have been caused by your change specifically, as 
the builds can include changes from many authors. It is not uncommon for your 
change to be included in a build that fails due to someone else's changes, or 
infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail 
[here](https://llvm.org/docs/MyFirstTypoFix.html#myfirsttypofix-issues-after-landing-your-pr).

If your change does cause a problem, it may be reverted, or you can revert it 
yourself. This is a normal part of [LLVM 
development](https://llvm.org/docs/DeveloperPolicy.html#patch-reversion-policy).
 You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are 
working as expected, well done!


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


[clang] [Clang] Fix typo 'dereferencable' to 'dereferenceable' (PR #116761)

2025-03-08 Thread Benjamin Maxwell via cfe-commits

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


[clang-tools-extra] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init check (PR #129370)

2025-03-08 Thread David Rivera via cfe-commits

RiverDave wrote:

Ping

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


[clang-tools-extra] [clang-tidy] detect explicit casting within modernize-use-default-member-init (PR #129408)

2025-03-08 Thread David Rivera via cfe-commits

RiverDave wrote:

ping

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


[clang] [HLSL][Driver] Use temporary files correctly (PR #130436)

2025-03-08 Thread Chris B via cfe-commits

https://github.com/llvm-beanz created 
https://github.com/llvm/llvm-project/pull/130436

This updates the DXV and Metal Converter actions to properly use temporary 
files created by the driver. I've abstracted away a check to determine if an 
action is the last in the sequence because we may have between 1 and 3 actions 
depending on the arguments and environment.

>From 0055f432469fa0eedf333e1a2d50025d822301cd Mon Sep 17 00:00:00 2001
From: Chris Bieneman 
Date: Sat, 8 Mar 2025 14:20:07 -0600
Subject: [PATCH] [HLSL][Driver] Use temporary files correctly

This updates the DXV and Metal Converter actions to properly use
temporary files created by the driver. I've abstracted away a check to
determine if an action is the last in the sequence because we may have
between 1 and 3 actions depending on the arguments and environment.
---
 clang/lib/Driver/Driver.cpp | 34 +
 clang/lib/Driver/ToolChains/HLSL.cpp| 26 +---
 clang/lib/Driver/ToolChains/HLSL.h  |  2 ++
 clang/test/Driver/HLSL/metal-converter.hlsl | 11 +--
 clang/test/Driver/dxc_dxv_path.hlsl |  6 ++--
 5 files changed, 62 insertions(+), 17 deletions(-)

diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 08ae8173db6df..9457a19255f21 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -4669,7 +4669,7 @@ void Driver::BuildActions(Compilation &C, DerivedArgList 
&Args,
   Actions.push_back(C.MakeAction(
   LastAction, types::TY_DX_CONTAINER));
 }
-if (Args.getLastArg(options::OPT_metal)) {
+if (TC.requiresBinaryTranslation(Args)) {
   Action *LastAction = Actions.back();
   // Metal shader converter runs on DXIL containers, which can either be
   // validated (in which case they are TY_DX_CONTAINER), or unvalidated
@@ -5219,8 +5219,14 @@ void Driver::BuildJobs(Compilation &C) const {
 unsigned NumOutputs = 0;
 unsigned NumIfsOutputs = 0;
 for (const Action *A : C.getActions()) {
+  // The actions below do not increase the number of outputs, when 
operating
+  // on DX containers.
+  if (A->getType() == types::TY_DX_CONTAINER &&
+  (A->getKind() == clang::driver::Action::BinaryAnalyzeJobClass ||
+   A->getKind() == clang::driver::Action::BinaryTranslatorJobClass))
+continue;
+
   if (A->getType() != types::TY_Nothing &&
-  A->getType() != types::TY_DX_CONTAINER &&
   !(A->getKind() == Action::IfsMergeJobClass ||
 (A->getType() == clang::driver::types::TY_IFS_CPP &&
  A->getKind() == clang::driver::Action::CompileJobClass &&
@@ -6221,11 +6227,27 @@ const char *Driver::GetNamedOutputPath(Compilation &C, 
const JobAction &JA,
 return C.addResultFile(C.getArgs().MakeArgString(FcValue.str()), &JA);
   }
 
-  if (JA.getType() == types::TY_Object &&
-  C.getArgs().hasArg(options::OPT_dxc_Fo)) {
+  if ((JA.getType() == types::TY_Object &&
+   C.getArgs().hasArg(options::OPT_dxc_Fo)) ||
+  JA.getType() == types::TY_DX_CONTAINER) {
 StringRef FoValue = C.getArgs().getLastArgValue(options::OPT_dxc_Fo);
-// TODO: Should we use `MakeCLOutputFilename` here? If so, we can probably
-// handle this as part of the SLASH_Fo handling below.
+// If we are targeting DXIL and not validating or translating, we should 
set
+// the final result file. Otherwise we should emit to a temporary.
+if (C.getDefaultToolChain().getTriple().isDXIL()) {
+  const auto &TC = static_cast(
+  C.getDefaultToolChain());
+  // Fo can be empty here if the validator is running for a compiler flow
+  // that is using Fc or just printing disassembly.
+  if (TC.isLastJob(C.getArgs(), JA.getKind()) && !FoValue.empty())
+return C.addResultFile(C.getArgs().MakeArgString(FoValue.str()), &JA);
+  StringRef Name = llvm::sys::path::filename(BaseInput);
+  std::pair Split = Name.split('.');
+  const char *Suffix = types::getTypeTempSuffix(JA.getType(), true);
+  return CreateTempFile(C, Split.first, Suffix, false);
+}
+// We don't have SPIRV-val integrated (yet), so for now we can assume this
+// is the final output.
+assert(C.getDefaultToolChain().getTriple().isSPIRV());
 return C.addResultFile(C.getArgs().MakeArgString(FoValue.str()), &JA);
   }
 
diff --git a/clang/lib/Driver/ToolChains/HLSL.cpp 
b/clang/lib/Driver/ToolChains/HLSL.cpp
index 62e4d14390b90..22498bff1f251 100644
--- a/clang/lib/Driver/ToolChains/HLSL.cpp
+++ b/clang/lib/Driver/ToolChains/HLSL.cpp
@@ -186,12 +186,9 @@ void tools::hlsl::Validator::ConstructJob(Compilation &C, 
const JobAction &JA,
   ArgStringList CmdArgs;
   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
   const InputInfo &Input = Inputs[0];
-  assert(Input.isFilename() && "Unexpected verify input");
-  // Grabbing the output of the earlier cc1 run.
   CmdArgs.push_back(Input.getFilename());
-  // Use th

  1   2   >