From 1999bc68bfa014c3ecf9481171ae312a8e24bbc5 Mon Sep 17 00:00:00 2001 From: chrchr-github <78114321+chrchr-github@users.noreply.github.com> Date: Sun, 14 May 2023 17:01:07 +0200 Subject: [PATCH] Set values when assigning init list (#5057) * Assign values to pointers with C++11 init * Handle assigning empty init list * Fix #10596 FN uninitdata with value initialization * Fix test * Set values when assigning init list --- lib/valueflow.cpp | 14 ++++++++++---- test/testvalueflow.cpp | 16 ++++++++++++++++ 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/lib/valueflow.cpp b/lib/valueflow.cpp index 2bb5a6f29..80acc30b2 100644 --- a/lib/valueflow.cpp +++ b/lib/valueflow.cpp @@ -1343,11 +1343,17 @@ static Token * valueFlowSetConstantValue(Token *tok, const Settings *settings, b if (!tok->isTemplateArg()) value.setKnown(); setTokenValue(tok->next(), std::move(value), settings, isInitList); - } else if (Token::Match(tok, "%name% = { }") && tok->variable() && + } else if (Token::Match(tok, "%name% = {") && tok->variable() && (tok->variable()->isPointer() || (tok->variable()->valueType() && tok->variable()->valueType()->isIntegral()))) { - ValueFlow::Value value(0); - value.setKnown(); - setTokenValue(tok->tokAt(2), std::move(value), settings, isInitList); + if (Token::simpleMatch(tok->tokAt(3), "}")) { + ValueFlow::Value value(0); + value.setKnown(); + setTokenValue(tok->tokAt(2), std::move(value), settings, isInitList); + } else if (tok->tokAt(2)->astOperand1() && tok->tokAt(2)->astOperand1()->hasKnownIntValue()) { + ValueFlow::Value value(tok->tokAt(2)->astOperand1()->getKnownIntValue()); + value.setKnown(); + setTokenValue(tok->tokAt(2), std::move(value), settings, isInitList); + } } return tok->next(); } diff --git a/test/testvalueflow.cpp b/test/testvalueflow.cpp index f03d4be37..6c1535558 100644 --- a/test/testvalueflow.cpp +++ b/test/testvalueflow.cpp @@ -5094,6 +5094,22 @@ private: ASSERT_EQUALS(true, value.isKnown()); ASSERT_EQUALS(1, value.intvalue); + code = "bool f() {\n" + " int* p = { 0 };\n" + " return p == nullptr;\n" // <- known value + "}"; + value = valueOfTok(code, "=="); + ASSERT_EQUALS(true, value.isKnown()); + ASSERT_EQUALS(1, value.intvalue); + + code = "bool f() {\n" + " int i = { 1 };\n" + " return i == 1;\n" // <- known value + "}"; + value = valueOfTok(code, "=="); + ASSERT_EQUALS(true, value.isKnown()); + ASSERT_EQUALS(1, value.intvalue); + // calculation with known result code = "int f(int x) { a = x & 0; }"; // <- & is 0 value = valueOfTok(code, "&");