From 577cd070845fb8facf0a451aafe1e444b9374b08 Mon Sep 17 00:00:00 2001 From: Marek Polacek Date: Thu, 30 Apr 2015 13:20:03 +0000 Subject: [PATCH] c-common.c (maybe_warn_bool_compare): When comparing with 0/1, require that the non-constant be of a boolean type. * c-common.c (maybe_warn_bool_compare): When comparing with 0/1, require that the non-constant be of a boolean type. * c-c++-common/Wbool-compare-3.c: New test. From-SVN: r222622 --- gcc/c-family/ChangeLog | 5 ++++ gcc/c-family/c-common.c | 11 +++++++ gcc/testsuite/ChangeLog | 4 +++ gcc/testsuite/c-c++-common/Wbool-compare-3.c | 30 ++++++++++++++++++++ 4 files changed, 50 insertions(+) create mode 100644 gcc/testsuite/c-c++-common/Wbool-compare-3.c diff --git a/gcc/c-family/ChangeLog b/gcc/c-family/ChangeLog index c17ea5f6138..8c2e93345ac 100644 --- a/gcc/c-family/ChangeLog +++ b/gcc/c-family/ChangeLog @@ -1,3 +1,8 @@ +2015-04-30 Marek Polacek + + * c-common.c (maybe_warn_bool_compare): When comparing with 0/1, + require that the non-constant be of a boolean type. + 2015-04-29 Josh Triplett * c-common.c (handle_section_attribute): Refactor to reduce diff --git a/gcc/c-family/c-common.c b/gcc/c-family/c-common.c index 7d314f854fe..ada8e8aa901 100644 --- a/gcc/c-family/c-common.c +++ b/gcc/c-family/c-common.c @@ -11924,6 +11924,17 @@ maybe_warn_bool_compare (location_t loc, enum tree_code code, tree op0, } else if (integer_zerop (cst) || integer_onep (cst)) { + /* If the non-constant operand isn't of a boolean type, we + don't want to warn here. */ + tree noncst = TREE_CODE (op0) == INTEGER_CST ? op1 : op0; + /* Handle booleans promoted to integers. */ + if (CONVERT_EXPR_P (noncst) + && TREE_TYPE (noncst) == integer_type_node + && TREE_CODE (TREE_TYPE (TREE_OPERAND (noncst, 0))) == BOOLEAN_TYPE) + /* Warn. */; + else if (TREE_CODE (TREE_TYPE (noncst)) != BOOLEAN_TYPE + && !truth_value_p (TREE_CODE (noncst))) + return; /* Do some magic to get the right diagnostics. */ bool flag = TREE_CODE (op0) == INTEGER_CST; flag = integer_zerop (cst) ? flag : !flag; diff --git a/gcc/testsuite/ChangeLog b/gcc/testsuite/ChangeLog index e0df670404c..455776844e3 100644 --- a/gcc/testsuite/ChangeLog +++ b/gcc/testsuite/ChangeLog @@ -1,3 +1,7 @@ +2015-04-30 Marek Polacek + + * c-c++-common/Wbool-compare-3.c: New test. + 2015-04-30 Paolo Carlini PR c++/57610 diff --git a/gcc/testsuite/c-c++-common/Wbool-compare-3.c b/gcc/testsuite/c-c++-common/Wbool-compare-3.c new file mode 100644 index 00000000000..bac4f47c2a0 --- /dev/null +++ b/gcc/testsuite/c-c++-common/Wbool-compare-3.c @@ -0,0 +1,30 @@ +/* { dg-do compile } */ +/* { dg-options "-Wbool-compare" } */ + +#ifndef __cplusplus +# define bool _Bool +#endif + +#define A 0 +#define B 1 + +int +foo (int i, bool b) +{ + int r = 0; + + r += i <= (A || B); + r += i <= b; + r += i <= A; + r += i < (A || B); + r += i < b; + r += i < A; + r += i > (A || B); + r += i > b; + r += i > A; + r += i >= (A || B); + r += i >= b; + r += i >= A; + + return r; +} -- 2.30.2