llvmorg-github-actions[bot] wrote:
<!--LLVM PR SUMMARY COMMENT--> @llvm/pr-subscribers-clang Author: Alex Mason (bearbones) <details> <summary>Changes</summary> ### Summary Adds `-Wlogical-conditional-parentheses` (grouped under `-Wparentheses` / `-Wall`, close to `-Wlogical-op-parentheses` but kept separate so users can disable it surgically) in `SemaExpr::DiagnoseConditionalPrecedence` to warn when an unparenthesized `&&` or `||` expression is used directly as the condition of a ternary operator (`?:`). The tests should make it plain what scenarios are excluded to keep the check from making too much noise. ### Motivation See [CVE coverage campaign thread](https://discourse.llvm.org/t/rfc-cve-coverage-campaign/92983?u=bearbones) for the real-life bug that this warning would have caught. In this simplified example, the author of a boolean expression might intend to return whether some value matches an expected value, or barring that, whether the value passes a threshold depending on some boolean flag. ``` return (a == target_val) || require_higher_val ? (a > 3) : (a > 1); ``` However because `||` has higher precedence than `?:`, this actually causes `(a == target_val) || require_higher_val` to decide which threshold to use on `a`. That is, if `a` and `target_val` are both 2, it returns `false`. Assisted-by: Gemini 4 Neon --- Full diff: https://github.com/llvm/llvm-project/pull/246430.diff 7 Files Affected: - (modified) clang/docs/ReleaseNotes.md (+6) - (modified) clang/include/clang/Basic/DiagnosticGroups.td (+2) - (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+3) - (modified) clang/lib/Sema/SemaExpr.cpp (+83-19) - (modified) clang/test/Misc/warning-wall.c (+1) - (added) clang/test/Sema/logical-conditional-parentheses.c (+75) - (added) clang/test/SemaCXX/logical-conditional-parentheses.cpp (+124) ``````````diff diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md index 6bbc910d86b5aa..4134e1dea95391 100644 --- a/clang/docs/ReleaseNotes.md +++ b/clang/docs/ReleaseNotes.md @@ -557,6 +557,12 @@ documentation](CIR/index.md) for more information regarding ClangIR's status and ### Improvements to Clang's diagnostics +- Added `-Wlogical-conditional-parentheses` (off by default; enabled by + `-Wparentheses` and `-Wall`) to warn when an unparenthesized logical `&&` or + `||` expression is used as the condition of a ternary `?:` operator whose + branches evaluate to boolean values and the two groupings have different + semantics (e.g., `a || b ? (x > y) : (x != y)`). + - Errors for invalid element types during instantiation of an `ext_vector_type` now include a source location, including in alias templates. (#GH229300) diff --git a/clang/include/clang/Basic/DiagnosticGroups.td b/clang/include/clang/Basic/DiagnosticGroups.td index 9f43b8570ea035..e0dc9649288001 100644 --- a/clang/include/clang/Basic/DiagnosticGroups.td +++ b/clang/include/clang/Basic/DiagnosticGroups.td @@ -542,6 +542,7 @@ Emit a warning for each variable declaration that generates code run at startup. } def BitwiseConditionalParentheses: DiagGroup<"bitwise-conditional-parentheses">; def BitwiseOpParentheses: DiagGroup<"bitwise-op-parentheses">; +def LogicalConditionalParentheses: DiagGroup<"logical-conditional-parentheses">; def LogicalOpParentheses: DiagGroup<"logical-op-parentheses">; def LogicalNotParentheses: DiagGroup<"logical-not-parentheses">; def ShiftOpParentheses: DiagGroup<"shift-op-parentheses">; @@ -1401,6 +1402,7 @@ def ParenthesesOnEquality : DiagGroup<"parentheses-equality">; def Parentheses : DiagGroup<"parentheses", [LogicalOpParentheses, LogicalNotParentheses, + LogicalConditionalParentheses, BitwiseConditionalParentheses, BitwiseOpParentheses, ShiftOpParentheses, diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index 2ae80dc3223501..b4fdc6abe15a89 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -7669,6 +7669,9 @@ def warn_precedence_conditional : Warning< def warn_precedence_bitwise_conditional : Warning< "operator '?:' has lower precedence than '%0'; '%0' will be evaluated first">, InGroup<BitwiseConditionalParentheses>; +def warn_precedence_logical_conditional : Warning< + "operator '?:' has lower precedence than '%0'; '%0' will be evaluated first">, + InGroup<LogicalConditionalParentheses>, DefaultIgnore; def note_precedence_conditional_first : Note< "place parentheses around the '?:' expression to evaluate it first">; diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index bc3f6444b88bae..635bf9b9082726 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -9385,15 +9385,12 @@ static bool IsArithmeticOp(BinaryOperatorKind Opc) { // not any of the logical operators. Bitwise-xor is commonly used as a // logical-xor because there is no logical-xor operator. The logical // operators, including uses of xor, have a high false positive rate for - // precedence warnings. + // general conditional expressions (e.g., `a || b ? 1 : 2`); logical + // operators with boolean conditional branches are diagnosed separately in + // DiagnoseConditionalPrecedence. } -/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary -/// expression, either using a built-in or overloaded operator, -/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side -/// expression. -static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode, - const Expr **RHSExprs) { +static const Expr *StripImplicitNodesWithoutParens(const Expr *E) { // Don't strip parenthesis: we should not warn if E is in parenthesis. E = E->IgnoreImpCasts(); E = E->IgnoreConversionOperatorSingleStep(); @@ -9402,6 +9399,16 @@ static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode, E = MTE->getSubExpr(); E = E->IgnoreImpCasts(); } + return E; +} + +/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary +/// expression, either using a built-in or overloaded operator, +/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side +/// expression. +static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode, + const Expr **RHSExprs) { + E = StripImplicitNodesWithoutParens(E); // Built-in binary operator. if (const auto *OP = dyn_cast<BinaryOperator>(E); @@ -9434,6 +9441,22 @@ static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode, return false; } +/// IsLogicalBinaryExpr - Returns true if E is a built-in logical binary +/// expression ('&&' or '||'), setting *Opcode, *OpLoc, and *RHSExpr. +static bool IsLogicalBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode, + SourceLocation *OpLoc, const Expr **RHSExpr) { + E = StripImplicitNodesWithoutParens(E); + + if (const auto *OP = dyn_cast<BinaryOperator>(E); OP && OP->isLogicalOp()) { + *Opcode = OP->getOpcode(); + *OpLoc = OP->getOperatorLoc(); + *RHSExpr = OP->getRHS(); + return true; + } + + return false; +} + /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type /// or is a logical expression such as (x==y) which has int type, but is /// commonly interpreted as boolean. @@ -9454,27 +9477,68 @@ static bool ExprLooksBoolean(const Expr *E) { return false; } +/// ExprLooksBooleanValue - Returns true if E evaluates to a boolean value, +/// excluding pointers: selecting between pointer arms (e.g. +/// `const char *s = a && b ? "yes" : "no"` or `T *x = a && b ? p : q`) is +/// idiomatic and has a different result type from `a && (b ? p : q)`. +static bool ExprLooksBooleanValue(const Expr *E) { + E = E->IgnoreParenImpCasts(); + + if (E->isTypeDependent()) + return false; + if (E->getType()->isBooleanType()) + return true; + if (const auto *OP = dyn_cast<BinaryOperator>(E)) + return OP->isComparisonOp() || OP->isLogicalOp(); + if (const auto *OP = dyn_cast<UnaryOperator>(E)) + return OP->getOpcode() == UO_LNot; + + return false; +} + +static bool IsBoolLiteralValue(const Expr *E, bool Expected) { + if (const auto *BL = dyn_cast<CXXBoolLiteralExpr>(E->IgnoreParenImpCasts())) + return BL->getValue() == Expected; + return false; +} + /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator /// and binary operator are mixed in a way that suggests the programmer assumed /// the conditional operator has higher precedence, for example: -/// "int x = a + someBinaryCondition ? 1 : 2". +/// "int x = a + someBinaryCondition ? 1 : 2" or +/// "bool r = a || b ? (x > y) : (x != y)". static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc, Expr *Condition, const Expr *LHSExpr, const Expr *RHSExpr) { BinaryOperatorKind CondOpcode; const Expr *CondRHS; + unsigned DiagID; - if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) - return; - if (!ExprLooksBoolean(CondRHS)) - return; - - // The condition is an arithmetic binary expression, with a right- - // hand side that looks boolean, so warn. - - unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode) - ? diag::warn_precedence_bitwise_conditional - : diag::warn_precedence_conditional; + if (IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) { + if (!ExprLooksBoolean(CondRHS)) + return; + // The condition is an arithmetic binary expression, with a right- + // hand side that looks boolean, so warn. + DiagID = BinaryOperator::isBitwiseOp(CondOpcode) + ? diag::warn_precedence_bitwise_conditional + : diag::warn_precedence_conditional; + } else { + SourceLocation CondOpLoc; + if (!IsLogicalBinaryExpr(Condition, &CondOpcode, &CondOpLoc, &CondRHS)) + return; + if (OpLoc.isMacroID() || CondOpLoc.isMacroID()) + return; + if (Self.inTemplateInstantiation()) + return; + if (!ExprLooksBooleanValue(LHSExpr) || !ExprLooksBooleanValue(RHSExpr)) + return; + // (A || B) ? true : Y is equivalent to A || (B ? true : Y), and + // (A && B) ? X : false is equivalent to A && (B ? X : false). + if ((CondOpcode == BO_LOr && IsBoolLiteralValue(LHSExpr, true)) || + (CondOpcode == BO_LAnd && IsBoolLiteralValue(RHSExpr, false))) + return; + DiagID = diag::warn_precedence_logical_conditional; + } Self.Diag(OpLoc, DiagID) << Condition->getSourceRange() diff --git a/clang/test/Misc/warning-wall.c b/clang/test/Misc/warning-wall.c index 6d6c4e562400fa..3108cbaf4e892a 100644 --- a/clang/test/Misc/warning-wall.c +++ b/clang/test/Misc/warning-wall.c @@ -98,6 +98,7 @@ CHECK-NEXT: -Wuser-defined-warnings CHECK-NEXT: -Wparentheses CHECK-NEXT: -Wlogical-op-parentheses CHECK-NEXT: -Wlogical-not-parentheses +CHECK-NEXT: -Wlogical-conditional-parentheses CHECK-NEXT: -Wbitwise-conditional-parentheses CHECK-NEXT: -Wbitwise-op-parentheses CHECK-NEXT: -Wshift-op-parentheses diff --git a/clang/test/Sema/logical-conditional-parentheses.c b/clang/test/Sema/logical-conditional-parentheses.c new file mode 100644 index 00000000000000..5df603a6498212 --- /dev/null +++ b/clang/test/Sema/logical-conditional-parentheses.c @@ -0,0 +1,75 @@ +// RUN: %clang_cc1 -std=c11 -fsyntax-only -verify -DSILENCE %s +// RUN: %clang_cc1 -std=c11 -fsyntax-only -verify -Wparentheses %s +// RUN: %clang_cc1 -std=c11 -fsyntax-only -verify -Wlogical-conditional-parentheses %s +// RUN: %clang_cc1 -std=c11 -fsyntax-only -verify -Wparentheses -Wno-logical-conditional-parentheses -DSILENCE %s +// RUN: %clang_cc1 -std=c11 -fsyntax-only -fdiagnostics-parseable-fixits -Wlogical-conditional-parentheses %s 2>&1 | FileCheck %s + +#ifdef SILENCE +// expected-no-diagnostics +#endif + +// Regression modeled on CVE-2026-130875 (C11 comparisons have type int). +int packet_looks_bogus(int i, int arg_cnt, unsigned flags, int len, int datalength) { + return (i != arg_cnt) || (flags & 1u) ? (len > datalength) : (len != datalength); +#ifndef SILENCE + // expected-warning@-2 {{operator '?:' has lower precedence than '||'; '||' will be evaluated first}} + // expected-note@-3 {{place parentheses around the '||' expression to silence this warning}} + // expected-note@-4 {{place parentheses around the '?:' expression to evaluate it first}} +#endif + // CHECK: fix-it:"{{.*}}":{[[@LINE-6]]:10-[[@LINE-6]]:10}:"(" + // CHECK: fix-it:"{{.*}}":{[[@LINE-7]]:40-[[@LINE-7]]:40}:")" + // CHECK: fix-it:"{{.*}}":{[[@LINE-8]]:28-[[@LINE-8]]:28}:"(" + // CHECK: fix-it:"{{.*}}":{[[@LINE-9]]:83-[[@LINE-9]]:83}:")" +} + +int logical_and_with_bool_arms(_Bool a, _Bool b, _Bool x, _Bool y) { + return a && b ? x : y; +#ifndef SILENCE + // expected-warning@-2 {{operator '?:' has lower precedence than '&&'; '&&' will be evaluated first}} + // expected-note@-3 {{place parentheses around the '&&' expression to silence this warning}} + // expected-note@-4 {{place parentheses around the '?:' expression to evaluate it first}} +#endif + // CHECK: fix-it:"{{.*}}":{[[@LINE-6]]:10-[[@LINE-6]]:10}:"(" + // CHECK: fix-it:"{{.*}}":{[[@LINE-7]]:16-[[@LINE-7]]:16}:")" + // CHECK: fix-it:"{{.*}}":{[[@LINE-8]]:15-[[@LINE-8]]:15}:"(" + // CHECK: fix-it:"{{.*}}":{[[@LINE-9]]:24-[[@LINE-9]]:24}:")" +} + +int logical_not_arms(int a, int b, int x, int y) { + return a || b ? !x : !y; +#ifndef SILENCE + // expected-warning@-2 {{operator '?:' has lower precedence than '||'; '||' will be evaluated first}} + // expected-note@-3 {{place parentheses around the '||' expression to silence this warning}} + // expected-note@-4 {{place parentheses around the '?:' expression to evaluate it first}} +#endif +} + +// Negative controls: explicitly parenthesized groupings. +int explicit_parens_controls(int i, int arg_cnt, unsigned flags, int len, int datalength) { + int r1 = ((i != arg_cnt) || (flags & 1u)) ? (len > datalength) : (len != datalength); + int r2 = (i != arg_cnt) || ((flags & 1u) ? (len > datalength) : (len != datalength)); + return r1 && r2; +} + +// Negative controls: non-boolean conditional arms (idiomatic C ternaries). +int non_boolean_arms(int a, int b, int x, int y, const char *p, const char *q) { + int r1 = a || b ? x : y; + int r2 = a && b ? 1 : 0; + int r3 = a || b ? (x > y) : 0; + const char *s = a && b ? p : q; + return r1 + r2 + r3 + (s != 0); +} + +// Negative control: GNU binary conditional extension (?:). +int gnu_binary_conditional(_Bool a, _Bool b, _Bool y) { + return a || b ?: y; +} + +// Negative controls: macros containing '?' or the logical operator. +#define UNPAREN_COND(A, B) A || B +#define MACRO_TERNARY(A, B, X, Y) A || B ? X : Y +int macro_controls(int a, int b, int x, int y) { + int r1 = UNPAREN_COND(a, b) ? (x > y) : (x != y); + int r2 = MACRO_TERNARY(a, b, x > y, x != y); + return r1 && r2; +} diff --git a/clang/test/SemaCXX/logical-conditional-parentheses.cpp b/clang/test/SemaCXX/logical-conditional-parentheses.cpp new file mode 100644 index 00000000000000..165c676e176a53 --- /dev/null +++ b/clang/test/SemaCXX/logical-conditional-parentheses.cpp @@ -0,0 +1,124 @@ +// RUN: %clang_cc1 -fsyntax-only -verify -DSILENCE %s +// RUN: %clang_cc1 -fsyntax-only -verify -Wparentheses %s +// RUN: %clang_cc1 -fsyntax-only -verify -Wlogical-conditional-parentheses %s +// RUN: %clang_cc1 -fsyntax-only -verify -Wparentheses -Wno-logical-conditional-parentheses -DSILENCE %s +// RUN: %clang_cc1 -fsyntax-only -fdiagnostics-parseable-fixits -Wlogical-conditional-parentheses %s 2>&1 | FileCheck %s + +#ifdef SILENCE +// expected-no-diagnostics +#endif + +bool predA(int x); +bool predB(int x); + +bool or_with_comparisons(int i, int cnt, int flags, int len, int max_len) { + return (i != cnt) || (flags & 1) ? (len > max_len) : (len != max_len); +#ifndef SILENCE + // expected-warning@-2 {{operator '?:' has lower precedence than '||'; '||' will be evaluated first}} + // expected-note@-3 {{place parentheses around the '||' expression to silence this warning}} + // expected-note@-4 {{place parentheses around the '?:' expression to evaluate it first}} +#endif + // CHECK: fix-it:"{{.*}}":{[[@LINE-6]]:10-[[@LINE-6]]:10}:"(" + // CHECK: fix-it:"{{.*}}":{[[@LINE-7]]:35-[[@LINE-7]]:35}:")" + // CHECK: fix-it:"{{.*}}":{[[@LINE-8]]:24-[[@LINE-8]]:24}:"(" + // CHECK: fix-it:"{{.*}}":{[[@LINE-9]]:72-[[@LINE-9]]:72}:")" +} + +bool and_with_bool_calls(bool a, bool b, int x) { + return a && b ? predA(x) : predB(x); +#ifndef SILENCE + // expected-warning@-2 {{operator '?:' has lower precedence than '&&'; '&&' will be evaluated first}} + // expected-note@-3 {{place parentheses around the '&&' expression to silence this warning}} + // expected-note@-4 {{place parentheses around the '?:' expression to evaluate it first}} +#endif + // CHECK: fix-it:"{{.*}}":{[[@LINE-6]]:10-[[@LINE-6]]:10}:"(" + // CHECK: fix-it:"{{.*}}":{[[@LINE-7]]:16-[[@LINE-7]]:16}:")" + // CHECK: fix-it:"{{.*}}":{[[@LINE-8]]:15-[[@LINE-8]]:15}:"(" + // CHECK: fix-it:"{{.*}}":{[[@LINE-9]]:38-[[@LINE-9]]:38}:")" +} + +bool chained_or_with_bools(bool a, bool b, bool c, bool x, bool y) { + return a || b || c ? x : y; +#ifndef SILENCE + // expected-warning@-2 {{operator '?:' has lower precedence than '||'; '||' will be evaluated first}} + // expected-note@-3 {{place parentheses around the '||' expression to silence this warning}} + // expected-note@-4 {{place parentheses around the '?:' expression to evaluate it first}} +#endif + // CHECK: fix-it:"{{.*}}":{[[@LINE-6]]:10-[[@LINE-6]]:10}:"(" + // CHECK: fix-it:"{{.*}}":{[[@LINE-7]]:21-[[@LINE-7]]:21}:")" + // CHECK: fix-it:"{{.*}}":{[[@LINE-8]]:20-[[@LINE-8]]:20}:"(" + // CHECK: fix-it:"{{.*}}":{[[@LINE-9]]:29-[[@LINE-9]]:29}:")" +} + +bool inverted_bool_literals(bool a, bool b) { + // (a || b) ? false : true != a || (b ? false : true) + bool r1 = a || b ? false : true; +#ifndef SILENCE + // expected-warning@-2 {{operator '?:' has lower precedence than '||'; '||' will be evaluated first}} + // expected-note@-3 {{place parentheses around the '||' expression to silence this warning}} + // expected-note@-4 {{place parentheses around the '?:' expression to evaluate it first}} +#endif + // (a && b) ? false : true != a && (b ? false : true) + bool r2 = a && b ? false : true; +#ifndef SILENCE + // expected-warning@-2 {{operator '?:' has lower precedence than '&&'; '&&' will be evaluated first}} + // expected-note@-3 {{place parentheses around the '&&' expression to silence this warning}} + // expected-note@-4 {{place parentheses around the '?:' expression to evaluate it first}} +#endif + return r1 && r2; +} + +template <typename T> +bool templated_nondependent(bool a, bool b, int x, int y, T) { + return a || b ? (x > y) : (x != y); +#ifndef SILENCE + // expected-warning@-2 {{operator '?:' has lower precedence than '||'; '||' will be evaluated first}} + // expected-note@-3 {{place parentheses around the '||' expression to silence this warning}} + // expected-note@-4 {{place parentheses around the '?:' expression to evaluate it first}} +#endif +} + +template <typename T> +T generic_select(bool a, bool b, T x, T y) { + // Do not warn merely because a generic template is instantiated with T=bool. + return a || b ? x : y; +} + +bool instantiate_templates(bool a, bool b, int x, int y) { + return templated_nondependent(a, b, x, y, 0) && + generic_select<bool>(a, b, x > y, x != y) && + generic_select<int>(a, b, x, y) != 0; +} + +// Negative controls: explicitly parenthesized groupings. +bool explicit_parens_controls(int i, int cnt, int flags, int len, int max_len) { + bool r1 = ((i != cnt) || (flags & 1)) ? (len > max_len) : (len != max_len); + bool r2 = (i != cnt) || ((flags & 1) ? (len > max_len) : (len != max_len)); + return r1 && r2; +} + +// Negative controls: non-boolean branches (including pointers). +int non_boolean_arms(bool a, bool b, int x, int y, const char *p, const char *q) { + int v1 = a || b ? x : y; + int v2 = a && b ? x : y; + const char *s = a && b ? p : q; + return v1 + v2 + (s != nullptr ? 1 : 0); +} + +// Negative controls: semantically equivalent groupings. +bool equivalent_groupings(bool a, bool b, bool x, bool y) { + bool r1 = a || b ? true : y; + bool r2 = a && b ? x : false; + bool r3 = a || b ? true : false; + bool r4 = a && b ? true : false; + return r1 && r2 && r3 && r4; +} + +// Negative control: overloaded logical operator (expression templates, etc.). +struct ExprVal { + explicit operator bool() const; +}; +ExprVal operator||(ExprVal, ExprVal); +bool overloaded_logical(ExprVal a, ExprVal b, bool x, bool y) { + return a || b ? x : y; +} `````````` </details> https://github.com/llvm/llvm-project/pull/246430 _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
