Skip to content

[mypyc] Fix C types of constant operands in native int shifts and arithmetic - #22557

Open
Jahongir-Qurbonov wants to merge 2 commits into
python:masterfrom
Jahongir-Qurbonov:mypyc-native-int-literal-operands
Open

Jahongir-Qurbonov wants to merge 2 commits into
python:masterfrom
Jahongir-Qurbonov:mypyc-native-int-literal-operands

Conversation

@Jahongir-Qurbonov

Copy link
Copy Markdown
Contributor

A C integer literal has type int, long long or unsigned long long, depending on its value. Constant operands of native int ops were emitted as plain literals, so in a few cases the operation was performed using the wrong C type:

  • A shift with a constant left operand used int. For example, 3 << n as u64 emitted 3 << cpy_r_n, so 3 << 40 gave 0 (or 6 with -O0) instead of 3298534883328, and 3 << 31 as u32 overflowed int. A right shift such as 1000000 >> n as i64 or u64 shifted an int by a count of up to 63, which is undefined behavior (with -O0, 1000000 >> 33 gave 500000 instead of 0).
  • A u32 addition, subtraction or multiplication by a constant that is at least 2**31 used long long, since the constant is emitted as e.g. 4000000000LL. x * 4000000000 could then overflow long long, which is undefined behavior. With the default CFLAGS (-fno-strict-overflow) the result was correct.

Convert a constant operand to the C type of the result in these cases. Other ops already cast their operands (signed arithmetic and signed left shifts use an unsigned type since #22547 and #22556), or the C type of a constant doesn't matter.

I checked the generated C expressions for the examples above with UBSan (-fsanitize=undefined), which reports the shifts and the multiplication before this change. The new run tests fail without the fix (the u64 and i64 shift tests, with the default -O0 used by the tests).

…thmetic

A C integer literal has type int, long long or unsigned long long,
depending on its value. Constant operands of native int ops were emitted
as plain literals, so in a few cases the operation used the wrong C type:

* A shift with a constant left operand used int. For example, 3 << n as
  u64 gave 0 for n = 40, and 1000000 >> n as i64 or u64 shifted an int by
  a count of up to 63, which is undefined behavior.
* A u32 addition, subtraction or multiplication by a constant that is at
  least 2**31 used long long (e.g. 4000000000LL), so a multiplication could
  overflow long long, which is undefined behavior.

Convert a constant operand to the C type of the result in these cases.
@JukkaL

JukkaL commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator

Thanks! This looks good, but there's a merge conflict.

…literal-operands

# Conflicts:
#	mypyc/test-data/run-i64.test
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