Clang fails to warn on dodgy logical expression code that VC++ does warn on
| Bugzilla Link | 37155 |
| Version | trunk |
| OS | Windows NT |
| CC | @devincoughlin,@DougGregor,@zmodem,@haoNoQ,@zygoloid,@ZequanWu |
Extended Description
The code below, if compiled with VC++ 2017 with /W4:
bool Test(int i) { return i == 2 | i == 3; }
gives this warning:
warning.cpp(2): warning C4554: '|': check operator precedence for possible error; use parentheses to clarify precedence
It would be nice if clang gave a similar warning. There isn't actually a bug, but using | instead of || can certainly be confusing.
We warn on return i == 2 | i; but not return i == 2 | i == 3;
This seems to be by design: the former case seems very likely to be intended to be return i == (2 | i); whereas the latter case can only reasonably be intended to mean return (i == 2) | (i == 3); which is indeed what it does mean.
Generally, when considering whether the frontend should warn, it seems reasonable to ask whether we have evidence that the actual meaning of the program diverges from what the programmer or an incautious reader of the code might expect. This case seems borderline, because the precedence of & and | compared to other operators is not well known.
I believe this shouldn't be on the static analyzer component. Like, static analyzer can be updated to emit such warnings, but i believe that shouldn't be. It doesn't exercise any mechanisms unique to the analyzer (such as path-sensitive analysis) and it doesn't have anything to do with third party libraries; instead, it's entirely about how the language works and the problem is entirely isolated on a single line of code, so there's no reason not to keep it as a compiler warning. Moved to the frontend component (do i understand our bugzilla components correctly?).
There is a Sema test case for clang's -Wparentheses diagnostics. It seems like that it intentionally ignores this case: https://github.com/llvm/llvm-project/blob/master/clang/test/Sema/parentheses.c#L46-L47
gcc has a warning for this:
error: suggest parentheses around comparison in operand of '|' [Werror=parentheses]
Extra information: the code in question was added to Chromium in https://chromium-review.googlesource.com/990721. It's on line 1010 of style_property_serializer.cc.