Fold fwrite of a single byte to fputc for performance.
Optimizes single-byte `fwrite` calls to `fputc`, improving performance in applications like `jq`.
This commit introduces a new GIMPLE pass to fold fwrite(p, 1, 1, f) calls into fputc(*p, f). This optimization is beneficial because fputc writes directly to the stream, bypassing fwrite’s buffered-write path. Benchmarks with jq show significant reductions in instructions and cycles, particularly when processing large datasets.
In Details
The gimple-fold pass optimizes GIMPLE (GCC's intermediate representation) by replacing certain built-in functions with more efficient equivalents. This change adds a folder for BUILT_IN_FWRITE and BUILT_IN_FWRITE_UNLOCKED when they transfer exactly one byte. This mirrors existing logic that folds one-character fputs into fputc and assumes unlocked entry points can be folded similarly. The performance gains are seen in applications like jq that emit output character by character.
- GIMPLE
- GCC's internal three-address intermediate representation, used for many optimization passes.
- fputc
- A C standard library function that writes a single character to an output stream.
- fwrite
- A C standard library function that writes a block of data to an output stream.
- gimple-fold
- A GCC optimization pass that simplifies or replaces GIMPLE expressions with equivalent but more efficient ones.
- jq
- A lightweight and flexible command-line JSON processor.