[clang] [clang][bytecode] Diagnose delete of non-heap-allocated blocks (PR #137475)
Timm Baeder via cfe-commits
cfe-commits at lists.llvm.org
Sat Apr 26 13:59:50 PDT 2025
https://github.com/tbaederr created https://github.com/llvm/llvm-project/pull/137475
With std::allocator::deallocate() calls
>From bdada63879bdd12603273167a291eaa4c0971dc4 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= <tbaeder at redhat.com>
Date: Sat, 26 Apr 2025 22:57:55 +0200
Subject: [PATCH] [clang][bytecode] Diagnose delete of non-heap-allocated
blocks
With std::allocator::deallocate() calls
---
clang/lib/AST/ByteCode/InterpBuiltin.cpp | 7 +++++++
clang/test/AST/ByteCode/new-delete.cpp | 7 ++++++-
2 files changed, 13 insertions(+), 1 deletion(-)
diff --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index 770511ff76bb0..045e79c3c561d 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -1641,6 +1641,13 @@ static bool interp__builtin_operator_delete(InterpState &S, CodePtr OpPC,
Source = Ptr.getDeclDesc()->asExpr();
BlockToDelete = Ptr.block();
+
+ if (!BlockToDelete->isDynamic()) {
+ S.FFDiag(Call, diag::note_constexpr_delete_not_heap_alloc)
+ << Ptr.toDiagnosticString(S.getASTContext());
+ if (const auto *D = Ptr.getFieldDesc()->asDecl())
+ S.Note(D->getLocation(), diag::note_declared_at);
+ }
}
assert(BlockToDelete);
diff --git a/clang/test/AST/ByteCode/new-delete.cpp b/clang/test/AST/ByteCode/new-delete.cpp
index e1b81e9a7963e..21d65461c79c7 100644
--- a/clang/test/AST/ByteCode/new-delete.cpp
+++ b/clang/test/AST/ByteCode/new-delete.cpp
@@ -610,7 +610,8 @@ namespace std {
}
constexpr void deallocate(void *p) {
__builtin_operator_delete(p); // both-note 2{{std::allocator<...>::deallocate' used to delete pointer to object allocated with 'new'}} \
- // both-note {{used to delete a null pointer}}
+ // both-note {{used to delete a null pointer}} \
+ // both-note {{delete of pointer '&no_deallocate_nonalloc' that does not point to a heap-allocated object}}
}
};
template<typename T, typename ...Args>
@@ -1004,6 +1005,10 @@ namespace WrongFrame {
}
+constexpr int no_deallocate_nonalloc = (std::allocator<int>().deallocate((int*)&no_deallocate_nonalloc), 1); // both-error {{constant expression}} \
+ // both-note {{in call}} \
+ // both-note {{declared here}}
+
#else
/// Make sure we reject this prior to C++20
constexpr int a() { // both-error {{never produces a constant expression}}
More information about the cfe-commits
mailing list