ValueFlow: Improved handling of bitand against a single-bit integer literal

This commit is contained in:
Daniel Marjamäki 2014-04-14 06:45:39 +02:00
parent 1ef99e2662
commit 5ee85ee88a
2 changed files with 42 additions and 0 deletions

View File

@ -238,6 +238,34 @@ static void valueFlowNumber(TokenList *tokenlist)
}
}
static void valueFlowBitAnd(TokenList *tokenlist)
{
for (Token *tok = tokenlist->front(); tok; tok = tok->next()) {
if (tok->str() != "&")
continue;
if (!tok->astOperand1() || !tok->astOperand2())
continue;
MathLib::bigint number;
if (MathLib::isInt(tok->astOperand1()->str()))
number = MathLib::toLongNumber(tok->astOperand1()->str());
else if (MathLib::isInt(tok->astOperand2()->str()))
number = MathLib::toLongNumber(tok->astOperand2()->str());
else
continue;
int bit = 0;
while (bit <= 60 && ((1LL<<bit) < number))
++bit;
if ((1LL<<bit) == number) {
setTokenValue(tok, ValueFlow::Value(0));
setTokenValue(tok, ValueFlow::Value(number));
}
}
}
static void valueFlowBeforeCondition(TokenList *tokenlist, ErrorLogger *errorLogger, const Settings *settings)
{
for (Token *tok = tokenlist->front(); tok; tok = tok->next()) {
@ -971,6 +999,7 @@ void ValueFlow::setValues(TokenList *tokenlist, ErrorLogger *errorLogger, const
tok->values.clear();
valueFlowNumber(tokenlist);
valueFlowBitAnd(tokenlist);
valueFlowForLoop(tokenlist, errorLogger, settings);
valueFlowBeforeCondition(tokenlist, errorLogger, settings);
valueFlowAfterAssign(tokenlist, errorLogger, settings);

View File

@ -36,6 +36,8 @@ private:
void run() {
TEST_CASE(valueFlowNumber);
TEST_CASE(valueFlowBitAnd);
TEST_CASE(valueFlowCalculations);
TEST_CASE(valueFlowBeforeCondition);
@ -629,6 +631,17 @@ private:
ASSERT_EQUALS(false, testValueOfX(code, 8U, 2)); // x is not 2 at line 8
}
void valueFlowBitAnd() {
const char *code;
code = "int f(int a) {\n"
" int x = a & 0x80;\n"
" return x;\n"
"}";
ASSERT_EQUALS(true, testValueOfX(code,3U,0));
ASSERT_EQUALS(true, testValueOfX(code,3U,0x80));
}
void valueFlowForLoop() {
const char *code;