Skip to content

Introduce ByteSymbol #141875

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open

Conversation

nnethercote
Copy link
Contributor

@nnethercote nnethercote commented Jun 2, 2025

It's like Symbol but for byte strings. The interner is now used for both Symbol and ByteSymbol. E.g. if you intern "dog" and b"dog" you'll get a Symbol and a ByteSymbol with the same index and the characters will only be stored once.

The motivation for this is to eliminate the Arcs in ast::LitKind, to make ast::LitKind impl Copy, and to avoid the need to arena-allocate ast::LitKind in HIR. The latter change reduces peak memory by a non-trivial amount on literal-heavy benchmarks such as deep-vector and tuple-stress.

Encoder, Decoder, SpanEncoder, and SpanDecoder all get some changes so that they can handle normal strings and byte strings.

@rustbot rustbot added the T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. label Jun 2, 2025
@rust-log-analyzer

This comment has been minimized.

@rust-log-analyzer

This comment has been minimized.

@nnethercote
Copy link
Contributor Author

@bors try @rust-timer queue

@rust-timer

This comment has been minimized.

@rustbot rustbot added the S-waiting-on-perf Status: Waiting on a perf run to be completed. label Jun 2, 2025
bors added a commit that referenced this pull request Jun 2, 2025
Introduce `ByteSymbol`

r? `@ghost`
@bors
Copy link
Collaborator

bors commented Jun 2, 2025

⌛ Trying commit e83f532 with merge f661a16...

@bors
Copy link
Collaborator

bors commented Jun 2, 2025

☀️ Try build successful - checks-actions
Build commit: f661a16 (f661a16cf599bf46f7b251ef3f5caba62f9ce4ac)

@rust-timer

This comment has been minimized.

@petrochenkov petrochenkov self-assigned this Jun 2, 2025
@rust-timer
Copy link
Collaborator

Finished benchmarking commit (f661a16): comparison URL.

Overall result: ❌✅ regressions and improvements - please read the text below

Benchmarking this pull request likely means that it is perf-sensitive, so we're automatically marking it as not fit for rolling up. While you can manually mark this PR as fit for rollup, we strongly recommend not doing so since this PR may lead to changes in compiler perf.

Next Steps: If you can justify the regressions found in this try perf run, please indicate this with @rustbot label: +perf-regression-triaged along with sufficient written justification. If you cannot justify the regressions please fix the regressions and do another perf run. If the next run shows neutral or positive results, the label will be automatically removed.

@bors rollup=never
@rustbot label: -S-waiting-on-perf +perf-regression

Instruction count

This is the most reliable metric that we have; it was used to determine the overall result at the top of this comment. However, even this metric can sometimes exhibit noise.

mean range count
Regressions ❌
(primary)
0.2% [0.2%, 0.2%] 1
Regressions ❌
(secondary)
0.5% [0.5%, 0.5%] 2
Improvements ✅
(primary)
-3.0% [-3.0%, -3.0%] 1
Improvements ✅
(secondary)
-0.4% [-0.5%, -0.3%] 2
All ❌✅ (primary) -1.4% [-3.0%, 0.2%] 2

Max RSS (memory usage)

Results (primary -1.9%, secondary -1.7%)

This is a less reliable metric that may be of interest but was not used to determine the overall result at the top of this comment.

mean range count
Regressions ❌
(primary)
- - 0
Regressions ❌
(secondary)
2.2% [0.4%, 6.7%] 8
Improvements ✅
(primary)
-1.9% [-2.2%, -1.6%] 2
Improvements ✅
(secondary)
-2.5% [-7.9%, -0.4%] 35
All ❌✅ (primary) -1.9% [-2.2%, -1.6%] 2

Cycles

Results (primary -2.4%, secondary 0.3%)

This is a less reliable metric that may be of interest but was not used to determine the overall result at the top of this comment.

mean range count
Regressions ❌
(primary)
- - 0
Regressions ❌
(secondary)
1.0% [0.5%, 2.9%] 11
Improvements ✅
(primary)
-2.4% [-3.1%, -1.7%] 2
Improvements ✅
(secondary)
-0.8% [-1.3%, -0.4%] 7
All ❌✅ (primary) -2.4% [-3.1%, -1.7%] 2

Binary size

Results (primary -1.1%)

This is a less reliable metric that may be of interest but was not used to determine the overall result at the top of this comment.

mean range count
Regressions ❌
(primary)
- - 0
Regressions ❌
(secondary)
- - 0
Improvements ✅
(primary)
-1.1% [-1.1%, -1.1%] 1
Improvements ✅
(secondary)
- - 0
All ❌✅ (primary) -1.1% [-1.1%, -1.1%] 1

Bootstrap: 775.84s -> 774.376s (-0.19%)
Artifact size: 372.26 MiB -> 372.24 MiB (-0.00%)

@rustbot rustbot added perf-regression Performance regression. and removed S-waiting-on-perf Status: Waiting on a perf run to be completed. labels Jun 3, 2025
@nnethercote
Copy link
Contributor Author

The motivation here: introduce ByteSymbol, to eliminate the Arcs in ast::LitKind, to make ast::LitKind impl Copy, to avoid the need to arena-allocate ast::LitKind in HIR.

It works, and the max-rss results (and page faults) are down for the literal-heavy benchmarks: deep-vector, tuple-stress, coercions, ucd. (And it's difficult to get max-rss down in general.) But it has no real effect on speed. So I'm not sure if it's worth the extra code.

@petrochenkov petrochenkov added the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Jun 3, 2025
@petrochenkov
Copy link
Contributor

petrochenkov commented Jun 3, 2025

cc #65818 (comment)

Upd: but maybe most of the (non-backend) improvements we already done in #103812.

@petrochenkov
Copy link
Contributor

petrochenkov commented Jun 3, 2025

This is a real issue because people want to include relatively large binary blobs into their programs, but I'm not sure we have a relevant benchmark in the perf suite.

It makes sense to benchmark this change on something specifically binary-blob-oriented.

@petrochenkov
Copy link
Contributor

I actually wanted to share the interner between string symbols and byte symbols.
The interner shouldn't care whether the bytes it stores or looks up are UTF-8 or not.
Symbol and ByteSymbol would then both be wrappers around an InternerIndex, but Symbol would give a guarantee that the bytes it points to are UTF-8, and ByteSymbol would give no such guarantee, and Symbol(index = 123) and ByteSymbol(index = 123) would actually share the storage if the bytes are UTF-8.

#65818 (comment) suggested making Symbol and ByteSymbol symbols dynamically discernible from each other (e.g. the former counts from 0, and the latter from u32::MAX), but maybe just having two static types would be enough.

Not sure if the same sharing can be done for metadata encoding/decoding tables.

@petrochenkov
Copy link
Contributor

I think this generally makes sense, the byte array interner is not large and is mostly a copypaste of the string interner, so not much new complexity.
@rustbot author

@rustbot rustbot added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Jun 3, 2025
@rustbot
Copy link
Collaborator

rustbot commented Jun 3, 2025

Reminder, once the PR becomes ready for a review, use @rustbot ready.

@nnethercote
Copy link
Contributor Author

nnethercote commented Jun 4, 2025

I benchmarked this program:

pub const BYTES: &[u8] = include_bytes!("/bin/containerd");

fn main() {
    println!("len = {}", BYTES.len());
}

On my Linux box /bin/containerd is a 48MB file.

hyperfine results, before and after:

Benchmark 1: $RUSTC1 b2.rs
  Time (mean ± σ):     414.3 ms ±  27.7 ms    [User: 183.2 ms, System: 294.1 ms]
  Range (min … max):   366.9 ms … 461.0 ms    10 runs
 
Benchmark 1: $RUSTC3 b2.rs
  Time (mean ± σ):     443.1 ms ±  26.2 ms    [User: 191.3 ms, System: 315.1 ms]
  Range (min … max):   413.7 ms … 500.2 ms    10 runs

I.e. this PR makes things a little slower. Probably because of the cost of hashing the binary blob to convert it into a ByteSymbol.

@petrochenkov
Copy link
Contributor

Seems reasonable, big binary blobs are unlikely to be identical, so not much sense to try deduplicating them.

@nnethercote
Copy link
Contributor Author

nnethercote commented Jun 4, 2025

Surprising it's only a little slower: Cachegrind says my example program takes 39 million instrs to compile normally and 67 million instructions with this PR's changes. The differences being all in hashing and some memcpy.

Edit: if I put the benchmark into rustc-perf and measure it, for a check full build I get a 58% wall-time increase from 0.15s to 0.23s.

@rust-log-analyzer

This comment has been minimized.

@nnethercote nnethercote marked this pull request as ready for review June 26, 2025 12:21
@rustbot rustbot added the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Jun 26, 2025
@rustbot
Copy link
Collaborator

rustbot commented Jun 26, 2025

Some changes occurred in compiler/rustc_codegen_ssa

cc @WaffleLapkin

These commits modify compiler targets.
(See the Target Tier Policy.)

Some changes occurred to the CTFE / Miri interpreter

cc @rust-lang/miri, @RalfJung, @oli-obk, @lcnr

Some changes occurred in match checking

cc @Nadrieril

Some changes occurred in src/tools/clippy

cc @rust-lang/clippy

Some changes occurred in rustc_ty_utils::consts.rs

cc @BoxyUwU

HIR ty lowering was modified

cc @fmease

@nnethercote
Copy link
Contributor Author

I actually wanted to share the interner between string symbols and byte symbols. The interner shouldn't care whether the bytes it stores or looks up are UTF-8 or not. Symbol and ByteSymbol would then both be wrappers around an InternerIndex, but Symbol would give a guarantee that the bytes it points to are UTF-8, and ByteSymbol would give no such guarantee, and Symbol(index = 123) and ByteSymbol(index = 123) would actually share the storage if the bytes are UTF-8.

I have done this.

Not sure if the same sharing can be done for metadata encoding/decoding tables.

I've also updated the encoding/decoding so that strings and byte strings are mostly handled the same way, so there is much less code duplication than the earlier version.

@nnethercote
Copy link
Contributor Author

@bors try @rust-timer queue

@rust-timer

This comment has been minimized.

@rustbot rustbot added the S-waiting-on-perf Status: Waiting on a perf run to be completed. label Jun 26, 2025
@bors
Copy link
Collaborator

bors commented Jun 26, 2025

⌛ Trying commit 900a994 with merge 4314adc...

bors added a commit that referenced this pull request Jun 26, 2025
Introduce `ByteSymbol`

It's like `Symbol` but for byte strings. The interner is now used for both `Symbol` and `ByteSymbol`. E.g. if you intern `"dog"` and `b"dog"` you'll get a `Symbol` and a `ByteSymbol` with the same index and the characters will only be stored once.

The motivation for this is to eliminate the `Arc`s in `ast::LitKind`, to make `ast::LitKind` impl `Copy`, and to avoid the need to arena-allocate `ast::LitKind` in HIR. The latter change reduces peak memory by a non-trivial amount on literal-heavy benchmarks such as `deep-vector` and `tuple-stress`.

`Encoder`, `Decoder`, `SpanEncoder`, and `SpanDecoder` all get some changes so that they can handle normal strings and byte strings.
@petrochenkov petrochenkov removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Jun 26, 2025
@bors
Copy link
Collaborator

bors commented Jun 26, 2025

☀️ Try build successful - checks-actions
Build commit: 4314adc (4314adcc655819f0f3b3e60c9f681717fa3d6de4)

@rust-timer

This comment has been minimized.

@rust-timer
Copy link
Collaborator

Finished benchmarking commit (4314adc): comparison URL.

Overall result: ❌✅ regressions and improvements - please read the text below

Benchmarking this pull request means it may be perf-sensitive – we'll automatically label it not fit for rolling up. You can override this, but we strongly advise not to, due to possible changes in compiler perf.

Next Steps: If you can justify the regressions found in this try perf run, please do so in sufficient writing along with @rustbot label: +perf-regression-triaged. If not, please fix the regressions and do another perf run. If its results are neutral or positive, the label will be automatically removed.

@bors rollup=never
@rustbot label: -S-waiting-on-perf +perf-regression

Instruction count

Our most reliable metric. Used to determine the overall result above. However, even this metric can be noisy.

mean range count
Regressions ❌
(primary)
0.1% [0.1%, 0.1%] 1
Regressions ❌
(secondary)
0.4% [0.4%, 0.4%] 3
Improvements ✅
(primary)
-0.4% [-0.4%, -0.3%] 3
Improvements ✅
(secondary)
-0.4% [-0.8%, -0.1%] 3
All ❌✅ (primary) -0.2% [-0.4%, 0.1%] 4

Max RSS (memory usage)

Results (primary 0.2%, secondary -1.0%)

A less reliable metric. May be of interest, but not used to determine the overall result above.

mean range count
Regressions ❌
(primary)
2.1% [2.1%, 2.1%] 1
Regressions ❌
(secondary)
4.1% [2.1%, 5.1%] 8
Improvements ✅
(primary)
-1.7% [-1.7%, -1.7%] 1
Improvements ✅
(secondary)
-2.6% [-4.9%, -1.4%] 26
All ❌✅ (primary) 0.2% [-1.7%, 2.1%] 2

Cycles

Results (secondary -10.2%)

A less reliable metric. May be of interest, but not used to determine the overall result above.

mean range count
Regressions ❌
(primary)
- - 0
Regressions ❌
(secondary)
- - 0
Improvements ✅
(primary)
- - 0
Improvements ✅
(secondary)
-10.2% [-10.7%, -9.8%] 6
All ❌✅ (primary) - - 0

Binary size

This benchmark run did not return any relevant results for this metric.

Bootstrap: 691.142s -> 690.132s (-0.15%)
Artifact size: 372.05 MiB -> 372.05 MiB (0.00%)

@rustbot rustbot removed the S-waiting-on-perf Status: Waiting on a perf run to be completed. label Jun 26, 2025
@petrochenkov petrochenkov added the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Jun 26, 2025
It's like `Symbol` but for byte strings. The interner is now used for
both `Symbol` and `ByteSymbol`. E.g. if you intern `"dog"` and `b"dog"`
you'll get a `Symbol` and a `ByteSymbol` with the same index and the
characters will only be stored once.

The motivation for this is to eliminate the `Arc`s in `ast::LitKind`, to
make `ast::LitKind` impl `Copy`, and to avoid the need to arena-allocate
`ast::LitKind` in HIR. The latter change reduces peak memory by a
non-trivial amount on literal-heavy benchmarks such as `deep-vector` and
`tuple-stress`.

`Encoder`, `Decoder`, `SpanEncoder`, and `SpanDecoder` all get some
changes so that they can handle normal strings and byte strings.

This change does slow down compilation of programs that use
`include_bytes!` on large files, because the contents of those files are
now interned (hashed). This makes `include_bytes!` more similar to
`include_str!`, though `include_bytes!` contents still aren't escaped,
and hashing is still much cheaper than escaping.

rustc_index::newtype_index! {
#[orderable]
struct ByteSymbolIndex {}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like SymbolIndex and ByteSymbolIndex don't need to be separate types.


// SAFETY: we can extend the arena allocation to `'static` because we
// only access these while the arena is still alive.
let string: &'static str = unsafe { &*(string as *const str) };
let byte_str: &'static [u8] = unsafe { &*(byte_str as *const [u8]) };

// This second hash table lookup can be avoided by using `RawEntryMut`,
// but this code path isn't hot enough for it to be worth it. See
// #91445 for details.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Huge blobs from include_bytes! will now go through this logic, so it makes sense to try this optimization again.

Actually, it would be good to have a benchmark for including a huge binary blob on perf-rlo, it's a special case, but an important one.
I've made an issue for that - rust-lang/rustc-perf#2171.

fn encode_symbol(&mut self, symbol: Symbol) {
// if symbol predefined, emit tag and symbol index
if symbol.is_predefined() {
fn encode_symbol_index_or_byte_str(&mut self, index: u32, byte_str: &[u8]) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
fn encode_symbol_index_or_byte_str(&mut self, index: u32, byte_str: &[u8]) {
fn encode_symbol(&mut self, index: u32) {

byte_str can be obtained here with ByteSymbol::new(index).as_byte_str().
Can also avoid touching the interner in SYMBOL_PREDEFINED cases if doing it here.

@@ -1333,7 +1352,15 @@ impl<D: SpanDecoder> Decodable<D> for Span {

impl<D: SpanDecoder> Decodable<D> for Symbol {
fn decode(s: &mut D) -> Symbol {
s.decode_symbol()
s.decode_symbol_index_or_byte_str(Symbol::new, |b| {
Symbol::intern(unsafe { str::from_utf8_unchecked(b) })
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, is this unsafe justified?
We are reading data from some file (?) and just assume that it's UTF-8.

Seems pre-existing because Decoder::read_str does that as well, but it at least does a STR_SENTINEL check.

self.emit_usize(v.len());
self.emit_raw_bytes(v.as_bytes());
self.emit_raw_bytes(v);
self.emit_u8(STR_SENTINEL);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

STR_SENTINEL is now emitted for non UTF-8 strings, but read_str relies on it being an indication of UTF-8-ness to be somewhat safe.

@petrochenkov petrochenkov added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Jun 27, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
perf-regression Performance regression. S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants