Skip to content

ir: Fix shift overflow in AND(SHR, C) constant folding#148

Merged
dstogov merged 1 commit into
dstogov:masterfrom
weltling:fix-fold-and-shr-overflow
Jun 15, 2026
Merged

ir: Fix shift overflow in AND(SHR, C) constant folding#148
dstogov merged 1 commit into
dstogov:masterfrom
weltling:fix-fold-and-shr-overflow

Conversation

@weltling

Copy link
Copy Markdown
Contributor

The redundancy rules for AND of a shifted value against a mask computed the shifted all ones value without masking the shift count, which is undefined behavior when the count reaches the type width.

Mask the shift count per type width to match the existing SHR constant folding.

@dstogov

dstogov commented Jun 15, 2026

Copy link
Copy Markdown
Owner

This seems right!

How did you find the problem.
Nor AddressSanitizer neither valgrind report problems to me on your test.

@dstogov

dstogov commented Jun 15, 2026

Copy link
Copy Markdown
Owner

I understood. C doesn't perform shifts on 8-bit data. It first extends operands to int and as result we don't have the undefined behavior. To demonstrate the issue, the test should use uint32_t instead of uint8_t (with modified constants).

Could you please modify the test.

The redundancy rules for AND of a shifted value against a mask
computed the shifted all ones value without masking the shift count,
which is undefined behavior when the count reaches the type width.

Mask the shift count per type width to match the existing SHR
constant folding.

Signed-off-by: Anatol Belski <anbelski@linux.microsoft.com>
@weltling

Copy link
Copy Markdown
Contributor Author

Thanks for checking. I've been experimenting with a fuzzer that goes beyond the text parser and mutates the IR data structures directly. This was found by an early prototype run under a UBSan build.

On the test, I initially chose uint8_t on purpose, since it gets promoted to int before the shift, so it was actually failing on a plain release build. I'll adjust the test case as requested and file a draft PR with the fuzzer prototype later today for review.

Thanks!

@weltling weltling force-pushed the fix-fold-and-shr-overflow branch from 368198e to 3b6492d Compare June 15, 2026 16:43
@weltling

Copy link
Copy Markdown
Contributor Author

@dstogov the test is rewritten with uint32_t now and adapted values.

Thanks

@dstogov dstogov left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@dstogov dstogov merged commit 37cc5a5 into dstogov:master Jun 15, 2026
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants