Skip to content

[mypyc] Fix range() loops with a step that overflows the index - #22501

Open
JukkaL wants to merge 7 commits into
masterfrom
mypyc-for-range-overflow
Open

JukkaL wants to merge 7 commits into
masterfrom
mypyc-for-range-overflow

Conversation

@JukkaL

@JukkaL JukkaL commented Nov 16, 2026

Copy link
Copy Markdown
Collaborator

A for loop over range(a, b, step) with a literal step other than 1 or -1
could overflow the index near the limits of its type, and keep looping with
a wrapped-around index. For example, with u8 bounds, range(250, 255, 2)
produced 250, 252, 254, 0, 2, ...

For a native int index, exit the loop before the increment if index + step
wouldn't fit in the type. Such a value would be past the end anyway. This is
a single compare against a constant. It's skipped if the step is 1 or -1, or
if the end is a constant that rules out overflow.

For a short int index, fall back to an int index if the step could overflow
a short int. This happens only for literal bounds near +-2**62 or huge
steps. Also load a step that doesn't fit in a short int as an int literal.
Previously this generated an out-of-range C literal, which either broke the
build or silently wrapped the step (so the loop could hang).

Alternative to #22470, since this generates a bit simpler IR and appears
to be faster on my mac laptop (perf is similar on x86-64 Linux).

A for loop over range(a, b, step) with a literal step other than 1 or -1
could overflow the index near the limits of its type, and keep looping with
a wrapped-around index. For example, with u8 bounds, range(250, 255, 2)
produced 250, 252, 254, 0, 2, ...

For a native int index, exit the loop before the increment if index + step
wouldn't fit in the type. Such a value would be past the end anyway. This is
a single compare against a constant. It's skipped if the step is 1 or -1, or
if the end is a constant that rules out overflow.

For a short int index, fall back to an int index if the step could overflow
a short int. This happens only for literal bounds near +-2**62 or huge
steps. Also load a step that doesn't fit in a short int as an int literal.
Previously this generated an out-of-range C literal, which either broke the
build or silently wrapped the step (so the loop could hang).

Alternative to #22470, since this generates a bit simpler IR and appears
to be faster on my mac laptop (perf is similar on x86-64 Linux).
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.

1 participant