GCC Newspaper
NOVEMBER 30, 2026
Date
/
Architectures
Components
Topics
News & Policy
Other
middle-end

GCC avoids incorrect block comparisons using cmpstr/cmpstrn

GCC's middle-end now only uses `cmpmem` for BLKmode block comparisons, preventing incorrect results with null bytes.

GCC’s prepare_cmp_insn function has been corrected to exclusively use the cmpmem pattern for comparing BLKmode operands (blocks of memory). Previously, it would attempt cmpstr and cmpstrn if cmpmem failed, but these patterns stop at null bytes and can produce incorrect results for blocks containing nulls. The change ensures that block comparisons are performed correctly by retrying with the next mode only if cmpmem’s expander fails.

In Details

This change in optabs.cc addresses a correctness issue in how GCC handles comparisons of BLKmode operands. The prepare_cmp_insn function, used for comparing blocks of memory, incorrectly tried cmpstr and cmpstrn after cmpmem. These string comparison patterns are unsuitable for arbitrary memory blocks as they terminate on null bytes. The fix restricts prepare_cmp_insn to use only cmpmem, which is designed for byte-wise memory comparison, and falls back to other modes only if cmpmem's expander fails. This prevents incorrect comparisons when a block contains null bytes.

For Context
BLKmode
GCC's internal data mode representing a block of memory of an arbitrary, but fixed, size.
cmpmem
A GCC pattern in machine descriptions that defines memory-to-memory comparison instructions.
optabs.cc
A GCC source file containing 'optimizer table lookups' that map abstract operations to concrete machine instructions.
expander
A piece of code within GCC that translates a high-level pattern into a sequence of simpler machine instructions if a direct instruction is not available.
Filed Under: correctnessmiddle-end