Add a warning to catch a bug recently caught by code review, like this:
t2.c:2:12: warning: use of logical && with constant operand; switch to bitwise &
or remove constant [-Wlogical-bitwise-confusion]
return x && 4;
^ ~
wording improvement suggestions are welcome.
git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@108260 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/lib/Sema/Sema.h b/lib/Sema/Sema.h
index c4153b6..d902dfe 100644
--- a/lib/Sema/Sema.h
+++ b/lib/Sema/Sema.h
@@ -4353,7 +4353,7 @@
QualType CheckBitwiseOperands( // C99 6.5.[10...12]
Expr *&lex, Expr *&rex, SourceLocation OpLoc, bool isCompAssign = false);
QualType CheckLogicalOperands( // C99 6.5.[13,14]
- Expr *&lex, Expr *&rex, SourceLocation OpLoc);
+ Expr *&lex, Expr *&rex, SourceLocation OpLoc, unsigned Opc);
// CheckAssignmentOperands is used for both simple and compound assignment.
// For simple assignment, pass both expressions and a null converted type.
// For compound assignment, pass both expressions and the converted type.
diff --git a/lib/Sema/SemaExpr.cpp b/lib/Sema/SemaExpr.cpp
index 5d53dde..cb3518a 100644
--- a/lib/Sema/SemaExpr.cpp
+++ b/lib/Sema/SemaExpr.cpp
@@ -5735,7 +5735,21 @@
}
inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
- Expr *&lex, Expr *&rex, SourceLocation Loc) {
+ Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
+
+ // Diagnose cases where the user write a logical and/or but probably meant a
+ // bitwise one. We do this when the LHS is a non-bool integer and the RHS
+ // is a constant.
+ if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
+ rex->getType()->isIntegerType() && rex->isEvaluatable(Context) &&
+ !Loc.isMacroID())
+ Diag(Loc, diag::warn_logical_instead_of_bitwise)
+ << rex->getSourceRange()
+ << (Opc == BinaryOperator::LAnd ? "&&" : "||")
+ << (Opc == BinaryOperator::LAnd ? "&" : "|");
+
+
+
if (!Context.getLangOptions().CPlusPlus) {
UsualUnaryConversions(lex);
UsualUnaryConversions(rex);
@@ -6363,7 +6377,7 @@
break;
case BinaryOperator::LAnd:
case BinaryOperator::LOr:
- ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
+ ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
break;
case BinaryOperator::MulAssign:
case BinaryOperator::DivAssign: