Skip to content

Commit 1977a18

Browse files
committed
simplifyNumericCalculations: Don't fold negative constants in shift/bitmask calculation. Behaviour is not well defined.
1 parent 3b41606 commit 1977a18

2 files changed

Lines changed: 7 additions & 0 deletions

File tree

lib/templatesimplifier.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -964,6 +964,12 @@ bool TemplateSimplifier::simplifyNumericCalculations(Token *tok)
964964

965965
// Integer operations
966966
if (Token::Match(op, ">>|<<|&|^|%or%")) {
967+
// Don't simplify if operand is negative, shifting with negative
968+
// operand is UB. Bitmasking with negative operand is implementation
969+
// defined behaviour.
970+
if (MathLib::isNegative(tok->str()) || MathLib::isNegative(tok->strAt(2)))
971+
continue;
972+
967973
const char cop = op->str()[0];
968974
std::string result;
969975
if (tok->str().find_first_of("uU") != std::string::npos)

test/testsimplifytokens.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2096,6 +2096,7 @@ class TestSimplifyTokens : public TestFixture {
20962096
ASSERT_EQUALS("x ( 1 )", tok("x(2 && 4<<4<<5 && 4)")); // #4933
20972097
ASSERT_EQUALS("x ( 1 )", tok("x(9&&8%5%4/3)")); // #4931
20982098
ASSERT_EQUALS("x ( 1 )", tok("x(2 && 2|5<<2%4)")); // #4931
2099+
ASSERT_EQUALS("x ( -2 << 6 | 1 )", tok("x(1-3<<6|5/3)")); // #4931
20992100

21002101
// don't remove these spaces..
21012102
ASSERT_EQUALS("new ( auto ) ( 4 ) ;", tok("new (auto)(4);"));

0 commit comments

Comments
 (0)