[clang] [clang][bytecode] Fix getting pointer element type in __builtin_memcmp (PR #130485)

via cfe-commits cfe-commits at lists.llvm.org
Sun Mar 9 04:31:42 PDT 2025


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)

<details>
<summary>Changes</summary>

When such a pointer is heap allocated, the type we get is a pointer type. Take the pointee type in that case.

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


2 Files Affected:

- (modified) clang/lib/AST/ByteCode/InterpBuiltin.cpp (+12-2) 
- (modified) clang/test/AST/ByteCode/builtin-functions.cpp (+15) 


``````````diff
diff --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index b8c4ef2f48a79..70c7fe5b714cb 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -1881,11 +1881,21 @@ static bool interp__builtin_memcmp(InterpState &S, CodePtr OpPC,
   bool IsWide =
       (ID == Builtin::BIwmemcmp || ID == Builtin::BI__builtin_wmemcmp);
 
+  auto getElemType = [](const Pointer &P) -> QualType {
+    const Descriptor *Desc = P.getFieldDesc();
+    QualType T = Desc->getType();
+    if (T->isPointerType())
+      return T->getAs<PointerType>()->getPointeeType();
+    if (Desc->isArray())
+      return Desc->getElemQualType();
+    return T;
+  };
+
   const ASTContext &ASTCtx = S.getASTContext();
   // FIXME: This is an arbitrary limitation the current constant interpreter
   // had. We could remove this.
-  if (!IsWide && (!isOneByteCharacterType(PtrA.getType()) ||
-                  !isOneByteCharacterType(PtrB.getType()))) {
+  if (!IsWide && (!isOneByteCharacterType(getElemType(PtrA)) ||
+                  !isOneByteCharacterType(getElemType(PtrB)))) {
     S.FFDiag(S.Current->getSource(OpPC),
              diag::note_constexpr_memcmp_unsupported)
         << ASTCtx.BuiltinInfo.getQuotedName(ID) << PtrA.getType()
diff --git a/clang/test/AST/ByteCode/builtin-functions.cpp b/clang/test/AST/ByteCode/builtin-functions.cpp
index dbff9164a91c1..29812553af9f0 100644
--- a/clang/test/AST/ByteCode/builtin-functions.cpp
+++ b/clang/test/AST/ByteCode/builtin-functions.cpp
@@ -1352,6 +1352,21 @@ namespace Memcmp {
   static_assert(__builtin_wmemcmp(L"abab\0banana", L"abab\0canada", 7) == -1);
   static_assert(__builtin_wmemcmp(L"abab\0banana", L"abab\0canada", 6) == -1);
   static_assert(__builtin_wmemcmp(L"abab\0banana", L"abab\0canada", 5) == 0);
+
+#if __cplusplus >= 202002L
+  constexpr bool f() {
+    char *c = new char[12];
+    c[0] = 'b';
+
+    char n = 'a';
+    bool b = __builtin_memcmp(c, &n, 1) == 0;
+
+    delete[] c;
+    return !b;
+  }
+  static_assert(f());
+#endif
+
 }
 
 namespace Memchr {

``````````

</details>


https://github.com/llvm/llvm-project/pull/130485


More information about the cfe-commits mailing list