Skip to content

Commit fe80f85

Browse files
committed
ValueFlow: Improved analysis in the valueFlowAfterAssign
1 parent 2c3807f commit fe80f85

2 files changed

Lines changed: 26 additions & 3 deletions

File tree

‎lib/valueflow.cpp‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -527,17 +527,30 @@ static void valueFlowAfterAssign(TokenList *tokenlist, ErrorLogger *errorLogger,
527527
continue;
528528
std::list<ValueFlow::Value> values = tok->astOperand2()->values;
529529

530+
const bool constValue = tok->astOperand2()->isNumber();
531+
int indentlevel = 0;
530532
unsigned int number_of_if = 0;
533+
int varusagelevel = -1;
531534

532535
for (Token *tok2 = tok; tok2 && tok2 != endToken; tok2 = tok2->next()) {
536+
if (indentlevel >= 0 && tok2->str() == "{")
537+
++indentlevel;
538+
else if (indentlevel >= 0 && tok2->str() == "}")
539+
--indentlevel;
540+
533541
if (Token::Match(tok2, "sizeof|typeof|typeid ("))
534542
tok2 = tok2->linkAt(1);
535543

536544
// conditional block of code that assigns variable..
537-
if (Token::Match(tok2, "%var% (") && Token::simpleMatch(tok2->linkAt(1), ") {")) {
545+
else if (Token::Match(tok2, "%var% (") && Token::simpleMatch(tok2->linkAt(1), ") {")) {
538546
Token * const start = tok2->linkAt(1)->next();
539547
Token * const end = start->link();
540-
if (Token::findmatch(start, "%varid%", end, varid)) {
548+
bool varusage = (indentlevel >= 0 && constValue && number_of_if == 0U) ?
549+
isVariableChanged(start,end,varid) :
550+
(nullptr != Token::findmatch(start, "%varid%", end, varid));
551+
if (varusage) {
552+
varusagelevel = indentlevel;
553+
541554
// TODO: don't check noreturn scopes
542555
if (number_of_if > 0U || Token::findmatch(tok2, "%varid%", start, varid)) {
543556
if (settings->debugwarnings)
@@ -586,7 +599,7 @@ static void valueFlowAfterAssign(TokenList *tokenlist, ErrorLogger *errorLogger,
586599
}
587600
}
588601

589-
else if (tok2->str() == "}") {
602+
else if (tok2->str() == "}" && indentlevel == varusagelevel) {
590603
++number_of_if;
591604

592605
// Set "conditional" flag for all values

‎test/testvalueflow.cpp‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -594,6 +594,16 @@ class TestValueFlow : public TestFixture {
594594
"}";
595595
TODO_ASSERT_EQUALS(true, false, testValueOfX(code, 4U, 32));
596596

597+
code = "void f() {\n"
598+
" int x = 32;\n"
599+
" if (a==1) { z=x+12; }\n"
600+
" if (a==2) { z=x+32; }\n"
601+
" z = x;\n"
602+
"}";
603+
ASSERT_EQUALS(true, testValueOfX(code, 3U, 32));
604+
ASSERT_EQUALS(true, testValueOfX(code, 4U, 32));
605+
ASSERT_EQUALS(true, testValueOfX(code, 5U, 32));
606+
597607
code = "void f() {\n" // #5656 - FP
598608
" int x = 0;\n"
599609
" if (!x) {\n"

0 commit comments

Comments
 (0)