[clang] [Clang] Force expressions with UO_Not to not be non-negative (PR #126846)
Yutong Zhu via cfe-commits
cfe-commits at lists.llvm.org
Thu Feb 13 19:11:49 PST 2025
https://github.com/YutongZhuu updated https://github.com/llvm/llvm-project/pull/126846
>From 44673ebf7c3fa773ffc7c52141b889c9ea352a93 Mon Sep 17 00:00:00 2001
From: Yutong Zhu <y25zhu at uwaterloo.ca>
Date: Tue, 11 Feb 2025 22:49:40 -0500
Subject: [PATCH] Force expressions with UO_Not to not be non-negative
---
clang/docs/ReleaseNotes.rst | 2 ++
clang/lib/Sema/SemaChecking.cpp | 11 +++++++++++
clang/test/Sema/compare.c | 4 ++++
3 files changed, 17 insertions(+)
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6344c4b36e357..e8aeaa6e514e4 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -135,6 +135,8 @@ Improvements to Clang's diagnostics
- Fixed a bug where Clang's Analysis did not correctly model the destructor behavior of ``union`` members (#GH119415).
- A statement attribute applied to a ``case`` label no longer suppresses
'bypassing variable initialization' diagnostics (#84072).
+- The ``-Wsign-compare`` warning now treats expressions with bitwise NOT(~) as signed integers
+ and throws warning if they are compared with unsigned integers (##18878).
Improvements to Clang's time-trace
----------------------------------
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 66c233de4ef30..47566d3db82d3 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -10069,6 +10069,17 @@ static std::optional<IntRange> TryGetExprRange(ASTContext &C, const Expr *E,
case UO_AddrOf: // should be impossible
return IntRange::forValueOfType(C, GetExprType(E));
+ case UO_Not: {
+ std::optional<IntRange> SubRange = TryGetExprRange(
+ C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
+ if (!SubRange)
+ return std::nullopt;
+
+ // The width increments by 1 if the sub-expression cannot be negative
+ // since it now can be.
+ return IntRange(SubRange->Width + (int)SubRange->NonNegative, false);
+ }
+
default:
return TryGetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
Approximate);
diff --git a/clang/test/Sema/compare.c b/clang/test/Sema/compare.c
index 17cf0351ef4f5..faa17ae7546dd 100644
--- a/clang/test/Sema/compare.c
+++ b/clang/test/Sema/compare.c
@@ -419,3 +419,7 @@ void pr36008(enum PR36008EnumTest lhs) {
if (x == y) x = y; // no warning
if (y == x) y = x; // no warning
}
+
+int test13(unsigned a, int *b) {
+ return a > ~(95 != *b); // expected-warning {{comparison of integers of different signs}}
+}
More information about the cfe-commits
mailing list