https://github.com/MScarta updated 
https://github.com/llvm/llvm-project/pull/241354

>From fe9780f42d8f1ef4ec1c28e15f73269bf103a066 Mon Sep 17 00:00:00 2001
From: Michael Scartaccini <[email protected]>
Date: Wed, 11 Nov 2026 23:26:57 +0800
Subject: [PATCH 1/5] [clang] Fix strlen constant evaluation for wide string
 literals with an offset

The string literal fast path in EvaluateBuiltinStrLen passed a byte
offset to StringLiteral::findZeroCodeUnit(), which expects an index in
code units. For a wide string literal with a non-zero offset this gave
the wrong length. For example, with a 4-byte wchar_t,
__builtin_wcslen(L"abc" + 1) evaluated to 12 instead of 2.

This was introduced by #218601 (a2ac4f6af958) and has not been in a
release.

The fix converts the offset to code units before calling the helper,
only takes the fast path when the offset is on a code unit boundary,
and no longer falls back to the literal's byte size.

It also fixes two other faults from the same change:

* The fast path was taken when the literal was read through a pointer
  to a different character type, so
  __builtin_strlen((const char *)L"abc") could be folded to 3. The
  check that the character types match is restored.
* When the string contents were requested, a wide literal was sliced
  using a code unit count as a byte count. Wide literals now take the
  slow path in that case, so both paths produce the same string.

The new constant interpreter is not affected by the offset bug, but it
still folds the cast case above. That is an older fault that is also in
LLVM 21, so it is left for a separate change and marked in the test.

AI use: an AI tool found the bug. The fix and the tests were drafted
with AI assistance. I reviewed every line, understand the change, and
ran the tests.

Assisted-by: Claude
---
 clang/lib/AST/ExprConstant.cpp          | 25 +++++++++++++++----------
 clang/test/SemaCXX/constexpr-string.cpp | 16 ++++++++++++++--
 2 files changed, 29 insertions(+), 12 deletions(-)

diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 57d5bb475d0f9b..d7d2b1dba0e8bb 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -23785,25 +23785,30 @@ EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info,
   if (!EvaluatePointer(E, String, Info))
     return std::nullopt;
 
+  QualType CharTy = E->getType()->getPointeeType();
+
   // Fast path: if it's a string literal, search the string value.
   if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
           String.getLValueBase().dyn_cast<const Expr *>())) {
     StringRef Str = S->getBytes();
     int64_t Off = String.Offset.getQuantity();
-    if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size()) {
-      UnsignedOrNone ZeroIndex = S->findZeroCodeUnit(Off);
-      if (StringResult) {
-        if (ZeroIndex)
-          Str = Str.substr(Off, *ZeroIndex);
-        *StringResult = Str;
+    unsigned Width = S->getCharByteWidth();
+    QualType LitCharTy =
+        S->getType()->castAsArrayTypeUnsafe()->getElementType();
+    if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && Off % Width == 0 
&&
+        Info.Ctx.hasSameUnqualifiedType(CharTy, LitCharTy) &&
+        // When the text is wanted, wide strings go to the slow path, which
+        // builds it one char per character. Raw bytes here would not match.
+        (Width == 1 || !StringResult)) {
+      if (UnsignedOrNone Len = S->findZeroCodeUnit(Off / Width)) {
+        if (StringResult)
+          *StringResult = Str.substr(Off, *Len);
+        return *Len;
       }
-
-      return ZeroIndex.value_or(Str.size());
     }
-    // For an invalid index, fall through to the offset handling below.
+    // Anything else falls through to the slow path.
   }
 
-  QualType CharTy = E->getType()->getPointeeType();
   // Slow path: scan the bytes of the string looking for the terminating 0.
   for (uint64_t Strlen = 0; /**/; ++Strlen) {
     APValue Char;
diff --git a/clang/test/SemaCXX/constexpr-string.cpp 
b/clang/test/SemaCXX/constexpr-string.cpp
index 96303ba1ef8015..ee008fd596949e 100644
--- a/clang/test/SemaCXX/constexpr-string.cpp
+++ b/clang/test/SemaCXX/constexpr-string.cpp
@@ -7,8 +7,8 @@
 // RUN: %clang_cc1 %s -triple armebv7-unknown-linux -std=c++2a -fsyntax-only 
-verify -pedantic -Wno-vla-extension -fno-signed-char
 // RUN: %clang_cc1 %s -triple armebv7-unknown-linux -std=c++2a -fsyntax-only 
-verify -pedantic -Wno-vla-extension -fno-wchar -DNO_PREDEFINED_WCHAR_T
 
-// RUN: %clang_cc1 %s -triple armebv7-unknown-linux -std=c++2a -fsyntax-only 
-verify -pedantic -Wno-vla-extension -fno-signed-char 
-fexperimental-new-constant-interpreter
-// RUN: %clang_cc1 %s -triple armebv7-unknown-linux -std=c++2a -fsyntax-only 
-verify -pedantic -Wno-vla-extension -fno-wchar -DNO_PREDEFINED_WCHAR_T 
-fexperimental-new-constant-interpreter
+// RUN: %clang_cc1 %s -triple armebv7-unknown-linux -std=c++2a -fsyntax-only 
-verify=expected,new-interp -pedantic -Wno-vla-extension -fno-signed-char 
-fexperimental-new-constant-interpreter
+// RUN: %clang_cc1 %s -triple armebv7-unknown-linux -std=c++2a -fsyntax-only 
-verify=expected,new-interp -pedantic -Wno-vla-extension -fno-wchar 
-DNO_PREDEFINED_WCHAR_T -fexperimental-new-constant-interpreter
 
 # 9 "/usr/include/string.h" 1 3 4  // expected-warning {{this style of line 
directive is a GNU extension}}
 extern "C" {
@@ -63,6 +63,18 @@ namespace Strlen {
   int arr[3]; // expected-note 2{{here}}
   int k = arr[strlen("hello")]; // expected-warning {{array index 5}}
   int wk = arr[wcslen(L"hello")]; // expected-warning {{array index 5}}
+
+  // __builtin_wcslen on a wide string literal with a non-zero offset.
+  static_assert(__builtin_wcslen(&L"abc"[1]) == 2, "");
+  static_assert(__builtin_wcslen(&L"abcdef"[1]) == 5, "");
+  static_assert(__builtin_wcslen(&L"ab\0cd"[1]) == 1, "");
+  static_assert(__builtin_wcslen(&L"ab\0cd"[3]) == 2, "");
+  static_assert(__builtin_wcslen(&L"abc"[3]) == 0, "");
+  static_assert(__builtin_strlen(&"abc"[1]) == 2, "");
+
+  // A wide literal read as char must not be folded.
+  // FIXME: The new constant interpreter still folds it.
+  static_assert(!__builtin_constant_p(__builtin_strlen((const char *)L"abc")), 
""); // new-interp-error {{static assertion failed}}
 }
 
 namespace StrcmpEtc {

>From b8a7606319d95baeeb5dcb03d0a860ea09e08646 Mon Sep 17 00:00:00 2001
From: Michael Scartaccini <[email protected]>
Date: Thu, 12 Nov 2026 10:00:00 +0800
Subject: [PATCH 2/5] Compare character sizes instead of types in the string
 literal fast path

---
 clang/lib/AST/ExprConstant.cpp          | 5 ++---
 clang/test/SemaCXX/constexpr-string.cpp | 6 +++++-
 2 files changed, 7 insertions(+), 4 deletions(-)

diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index d7d2b1dba0e8bb..064fd9bf43a356 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -23793,10 +23793,9 @@ EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info,
     StringRef Str = S->getBytes();
     int64_t Off = String.Offset.getQuantity();
     unsigned Width = S->getCharByteWidth();
-    QualType LitCharTy =
-        S->getType()->castAsArrayTypeUnsafe()->getElementType();
     if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && Off % Width == 0 
&&
-        Info.Ctx.hasSameUnqualifiedType(CharTy, LitCharTy) &&
+        !CharTy->isIncompleteType() &&
+        Info.Ctx.getTypeSize(CharTy) == Width * 8 &&
         // When the text is wanted, wide strings go to the slow path, which
         // builds it one char per character. Raw bytes here would not match.
         (Width == 1 || !StringResult)) {
diff --git a/clang/test/SemaCXX/constexpr-string.cpp 
b/clang/test/SemaCXX/constexpr-string.cpp
index ee008fd596949e..e3dd96e71f90c9 100644
--- a/clang/test/SemaCXX/constexpr-string.cpp
+++ b/clang/test/SemaCXX/constexpr-string.cpp
@@ -67,7 +67,7 @@ namespace Strlen {
   // __builtin_wcslen on a wide string literal with a non-zero offset.
   static_assert(__builtin_wcslen(&L"abc"[1]) == 2, "");
   static_assert(__builtin_wcslen(&L"abcdef"[1]) == 5, "");
-  static_assert(__builtin_wcslen(&L"ab\0cd"[1]) == 1, "");
+  static_assert(__builtin_wcslen(&L"abc\0defgh"[1]) == 2, "");
   static_assert(__builtin_wcslen(&L"ab\0cd"[3]) == 2, "");
   static_assert(__builtin_wcslen(&L"abc"[3]) == 0, "");
   static_assert(__builtin_strlen(&"abc"[1]) == 2, "");
@@ -75,6 +75,10 @@ namespace Strlen {
   // A wide literal read as char must not be folded.
   // FIXME: The new constant interpreter still folds it.
   static_assert(!__builtin_constant_p(__builtin_strlen((const char *)L"abc")), 
""); // new-interp-error {{static assertion failed}}
+
+  // A literal read as a different character type of the same size is folded.
+  static_assert(__builtin_constant_p(__builtin_strlen((const char *)u8"abc")), 
"");
+  static_assert(__builtin_constant_p(__builtin_wcslen((const wchar_t 
*)U"abc")), "");
 }
 
 namespace StrcmpEtc {

>From 909dae53e45a7432662e3db8d20841a082ee0b7a Mon Sep 17 00:00:00 2001
From: Michael Scartaccini <[email protected]>
Date: Fri, 13 Nov 2026 11:34:36 +0800
Subject: [PATCH 3/5] Add a unit test for tryEvaluateStrLen on a pointer to an
 incomplete type

tryEvaluateStrLen() and tryEvaluateString() take any pointer. For
(const struct S *)"abc" with an incomplete struct S, the string literal
fast path would call getTypeSize() on the incomplete type and assert.
The test checks that both return std::nullopt.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
---
 clang/unittests/AST/ASTExprTest.cpp | 12 ++++++++++++
 1 file changed, 12 insertions(+)

diff --git a/clang/unittests/AST/ASTExprTest.cpp 
b/clang/unittests/AST/ASTExprTest.cpp
index 5c9e7928bb804f..2a3cd4f4293ea6 100644
--- a/clang/unittests/AST/ASTExprTest.cpp
+++ b/clang/unittests/AST/ASTExprTest.cpp
@@ -446,3 +446,15 @@ TEST(ASTExpr, CXXDefaultInitExprHasRewrittenInit) {
   EXPECT_FALSE(CtorDIE->hasRewrittenInit());
   EXPECT_EQ(CtorDIE->getExpr(), CtorDIE->getField()->getInClassInitializer());
 }
+
+TEST(ASTExpr, TryEvaluateStringIncompletePointee) {
+  auto AST = buildASTFromCodeWithArgs(
+      "struct S; const struct S *p = (const struct S *)\"abc\";", {"-xc"});
+  ASTContext &Ctx = AST->getASTContext();
+  const auto *VD =
+      selectFirst<VarDecl>("p", match(varDecl(hasName("p")).bind("p"), Ctx));
+  ASSERT_TRUE(VD);
+  const Expr *E = VD->getInit();
+  EXPECT_FALSE(E->tryEvaluateStrLen(Ctx));
+  EXPECT_FALSE(E->tryEvaluateString(Ctx));
+}

>From c5161b039c5ee3a9b001de768a432d73c05da9f3 Mon Sep 17 00:00:00 2001
From: Michael Scartaccini <[email protected]>
Date: Sat, 14 Nov 2026 10:58:05 +0800
Subject: [PATCH 4/5] Replace the unit test with a C test and move a comment

A builtin redeclared without a prototype, where the earlier declaration
is hidden, gets its arguments unconverted. The new test uses that to
reach the fast path from C source with a pointer to void and with a
pointer to an incomplete struct. This replaces the unit test.

Also move the comment out of the middle of the if condition.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
---
 clang/lib/AST/ExprConstant.cpp          |  4 ++--
 clang/test/Sema/builtins-no-prototype.c | 29 +++++++++++++++++++++++++
 clang/unittests/AST/ASTExprTest.cpp     | 12 ----------
 3 files changed, 31 insertions(+), 14 deletions(-)
 create mode 100644 clang/test/Sema/builtins-no-prototype.c

diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 064fd9bf43a356..cce4236f9f3642 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -23793,11 +23793,11 @@ EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info,
     StringRef Str = S->getBytes();
     int64_t Off = String.Offset.getQuantity();
     unsigned Width = S->getCharByteWidth();
+    // When the text is wanted, wide strings go to the slow path, which
+    // builds it one char per character. Raw bytes here would not match.
     if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && Off % Width == 0 
&&
         !CharTy->isIncompleteType() &&
         Info.Ctx.getTypeSize(CharTy) == Width * 8 &&
-        // When the text is wanted, wide strings go to the slow path, which
-        // builds it one char per character. Raw bytes here would not match.
         (Width == 1 || !StringResult)) {
       if (UnsignedOrNone Len = S->findZeroCodeUnit(Off / Width)) {
         if (StringResult)
diff --git a/clang/test/Sema/builtins-no-prototype.c 
b/clang/test/Sema/builtins-no-prototype.c
new file mode 100644
index 00000000000000..469f6f56e84c59
--- /dev/null
+++ b/clang/test/Sema/builtins-no-prototype.c
@@ -0,0 +1,29 @@
+// RUN: %clang_cc1 -std=c99 -fsyntax-only -verify 
-Wno-deprecated-non-prototype %s
+// expected-no-diagnostics
+
+// A builtin redeclared without a prototype, where the earlier declaration is
+// hidden, gets its arguments unconverted.
+
+typedef __SIZE_TYPE__ size_t;
+struct S;
+size_t strlen(const char *);
+char *strcpy(char *, const char *);
+
+// A void pointer still gives the length.
+void test_void(void) {
+  int strlen = 0;
+  {
+    extern size_t strlen();
+    _Static_assert(strlen((const void *)"abc") == 3, "");
+  }
+}
+
+// A pointer to an incomplete struct must not crash.
+void test_incomplete(void) {
+  int strcpy = 0;
+  {
+    extern char *strcpy();
+    char buf[2];
+    strcpy(buf, (const struct S *)"abcdef");
+  }
+}
diff --git a/clang/unittests/AST/ASTExprTest.cpp 
b/clang/unittests/AST/ASTExprTest.cpp
index 2a3cd4f4293ea6..5c9e7928bb804f 100644
--- a/clang/unittests/AST/ASTExprTest.cpp
+++ b/clang/unittests/AST/ASTExprTest.cpp
@@ -446,15 +446,3 @@ TEST(ASTExpr, CXXDefaultInitExprHasRewrittenInit) {
   EXPECT_FALSE(CtorDIE->hasRewrittenInit());
   EXPECT_EQ(CtorDIE->getExpr(), CtorDIE->getField()->getInClassInitializer());
 }
-
-TEST(ASTExpr, TryEvaluateStringIncompletePointee) {
-  auto AST = buildASTFromCodeWithArgs(
-      "struct S; const struct S *p = (const struct S *)\"abc\";", {"-xc"});
-  ASTContext &Ctx = AST->getASTContext();
-  const auto *VD =
-      selectFirst<VarDecl>("p", match(varDecl(hasName("p")).bind("p"), Ctx));
-  ASSERT_TRUE(VD);
-  const Expr *E = VD->getInit();
-  EXPECT_FALSE(E->tryEvaluateStrLen(Ctx));
-  EXPECT_FALSE(E->tryEvaluateString(Ctx));
-}

>From 9aa0b333c0cfd2a66bfa6d325c5ada15b10237b7 Mon Sep 17 00:00:00 2001
From: Michael Scartaccini <[email protected]>
Date: Sat, 14 Nov 2026 13:32:53 +0800
Subject: [PATCH 5/5] Compare sizes in CharUnits, rename Width and tidy a cast
 and comment

Compare the pointee size with the literal's character byte width in
CharUnits so the bare 8 is gone. Rename Width to CharByteWidth. Drop the
redundant cast of Str.size() and cast Off with static_cast<size_t>.
Reword the comment above the condition.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
---
 clang/lib/AST/ExprConstant.cpp | 17 +++++++++--------
 1 file changed, 9 insertions(+), 8 deletions(-)

diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index cce4236f9f3642..ce347e9dafdb55 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -23792,14 +23792,15 @@ EvaluateBuiltinStrLen(const Expr *E, EvalInfo &Info,
           String.getLValueBase().dyn_cast<const Expr *>())) {
     StringRef Str = S->getBytes();
     int64_t Off = String.Offset.getQuantity();
-    unsigned Width = S->getCharByteWidth();
-    // When the text is wanted, wide strings go to the slow path, which
-    // builds it one char per character. Raw bytes here would not match.
-    if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() && Off % Width == 0 
&&
-        !CharTy->isIncompleteType() &&
-        Info.Ctx.getTypeSize(CharTy) == Width * 8 &&
-        (Width == 1 || !StringResult)) {
-      if (UnsignedOrNone Len = S->findZeroCodeUnit(Off / Width)) {
+    unsigned CharByteWidth = S->getCharByteWidth();
+    // StringResult holds one char per character, so the literal's bytes can
+    // only be copied into it when each character is one byte.
+    if (Off >= 0 && static_cast<size_t>(Off) <= Str.size() &&
+        Off % CharByteWidth == 0 && !CharTy->isIncompleteType() &&
+        Info.Ctx.getTypeSizeInChars(CharTy) ==
+            CharUnits::fromQuantity(CharByteWidth) &&
+        (CharByteWidth == 1 || !StringResult)) {
+      if (UnsignedOrNone Len = S->findZeroCodeUnit(Off / CharByteWidth)) {
         if (StringResult)
           *StringResult = Str.substr(Off, *Len);
         return *Len;

_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to