Sub-optimal code when the operation "% 1" on integers is met #10956
Labels
area-CodeGen-coreclr
CLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI
enhancement
Product code improvement that does NOT require public API changes/additions
help wanted
[up-for-grabs] Good issue for external contributors
optimization
Milestone
Currently, the CLR gives result "0" (which seems correct) for "remainder of 1" operation on integers.
For
b = 1
the resulting range is obviously(-1; 1)
==> just plain0
.However, it looks like there is some space for improvements in JIT codegen, since JIT does not seem to fold the result of evaluation to zero constant, which prohibits further optimizations - see the repro code below.
To my understanding, ALL
% 1
operations can be folded to just use constant values, with maybe notable exception when the memory read and/or write is required to observe some side effects (eg. volatile variables). For signed integers obtained directly or indirectly (thru implicit type convertion toInt32
) the code looks quite verbose, given that the result is known ahead. It's better forUInt32
andUInt64
whereAND r/m, 0
is issued, but of theseAND [m], 0
only makes sense when again side effects are to be observed. I don't see any reason forAND r, 0
- this loads CPU scheduler much more thanXOR r, r
.Understanding that
% 1
does not often occur in the code, here's real case when it may appear (happened to me). Say there is ring buffer withN
items, and thatN
is provided externally - either thrustatic readonly
field (resolve during runtime), or thruconst
definition (resolve during compile time). To calculate the slot index for current or next item, the% N
opration is used. Since in degenerate case thatN
can be set to1
, there is desire to reduce all related calculations when there's just one slot for everything. At the moment additional checks placed manually are required and that provides more IL, which reduces inlineability for methods.The repro code:
The disasm:
category:cq
theme:expression-opts
skill-level:beginner
cost:small
The text was updated successfully, but these errors were encountered: