r/rust • • 5d ago

Compile time improvements for derive(Debug)

https://yoyo-code.com/derive-debug-compile-time-improvements/
178 Upvotes

26 comments sorted by

71

u/MalbaCato 5d ago

Interesting post overall.

small (but somewhat important) nitpick:

We ended up fixing this by using custom split_str_by_space routine which avoids UTF-8 handling (variant names are ascii)

variant names, as all identifiers, aren't restricted to ascii in rust, but a splitting a UTF-8 string by a byte which corresponds to an ascii character (the space) results in valid UTF-8 on both sides.

25

u/panstromek 4d ago

Good point, I'll remove the ascii note.

10

u/dnew 4d ago

splitting a UTF-8 string by a byte which corresponds to an ascii character (the space) results in valid UTF-8 on both sides

I just had a passing thought. The reason for this was the military power of the Roman Empire. :-) English is (inappropriately) using the Latin alphabet that fits conveniently into 7 bits.

9

u/berrita000 4d ago

Greek and many other alphabets could just as easily have fitted into 7 bits if history had taken a different turn.

1

u/dnew 4d ago

For sure.

15

u/Lucretiel Datadog 4d ago

I'm... pretty surprised that this was the approach that was taken, rather than just, like, introducing an optimization to the way that match is compiled that lets it handle the "typical" match (exactly one arm for each variant of a single enum) in linear time.

10

u/panstromek 4d ago edited 4d ago

I'm not 100% sure which part you're referring to - I guess you mean match checking? If so, then yes, I think we should just make this case linear, as I hinted at the end.

The rest of the costs associated with MIR are much more tricky. It's very easy to introduce unsoundness when changing how we lower certain constructs to MIR (2 cases in last few weeks IIRC, for relatively minor changes).

It'd nice if we could avoid the temp local for each arm, or if we could lower match into some special SwitchAssign terminator, instead of SwitchInt that branches to N basic blocks, but changing those could have far reaching conseqences. That's orders of magnitude bigger change than what we did here - and it might be usable only in very narrow circumstances. It's not off the table, but certainly not first thing you'd reach for.

14

u/BobTreehugger 4d ago

Interesting writeup, I'm sure everyone at every step thought, "oh this will be a quick fix" and it just kept being more complicated.

I did notice one small thing though:

We ended up fixing this by using custom split_str_by_space routine which avoids UTF-8 handling (variant names are ascii)

Variant names don't have to be ascii as far as I can tell. Is it just for this optimization?

Doesn't seem needed though -- the nice thing about utf8 is that ascii bytes are encoded the same as ascii and don't depend on any parser state, so you can just look for the spaces without needing full unicode handling for this simple case (splitting by exactly a space).

So my guess is that variant names don't need to be ascii, but that's fine for this case.

13

u/panstromek 4d ago

Yes, that `ascii` note is incorrect, a sibling comment pointed it out as well. I removed it.

5

u/dnew 4d ago

Roughly speaking because every match arm gets compared to every previous match arm (which is quadratic) and the enum is simple, so there's no complicated pattern deconstruction logic.

This seems sub-optimal. Create an array of booleans set to false the size of the enum. On each match, make sure the boolean entry is false, then set it true. At the end, make sure they're all set true. Seems like it ought to be linear in the size of the enum if they're all just enum matches.

12

u/panstromek 4d ago

It is sub-optimal but not necessarily simple to change, I just wrote the problem in simple terms. In reality, this property is hidden in thousands of lines of fairly dense code which handles all possible match flavors together. You can check it out here if you're curious: https://github.com/rust-lang/rust/blob/4c11abbbd2daf20b8351e47091950a4d99e62973/compiler/rustc_pattern_analysis/src/usefulness.rs

2

u/matthieum [he/him] 4d ago

This is certainly a monster of a file.

I still can't help but wonder, though, whether a linear pre-pass for the simple case of:

  1. Matching on a single enum value.
  2. Where every pattern is just a discriminant, without a nested pattern nor guard, or an OR combination of such.

Would help.

Matching on simple enums is fairly routine, so it seems like it would pay-off to handle the simple case quickly, and defer anything more complicated to the more exhaustive algorithm.

1

u/panstromek 4d ago

Yea, there certainly is a way. Feel free to get nerd-sniped to try this 😄, this is only waiting for someone to pick it up. Somebody will get to it eventually.

4

u/dnew 4d ago

Yeah, if you're not going to completely special-case this with a pre-scan, it's not going to be linear. Your write-up made it sound (to me) like that might have been called out already. And of course if you were going to add that scan, you'd need to test to see if on average it actually improved anything.

That's some excellent documentation, I will say. Clearly written by a computer scientist and not just a programmer. :-) I kind of wish my career consisted of more computer scientists and fewer programmers.

3

u/minno 4d ago

A few ideas I had while reading this:

  1. Instead of splitting a space-delimited string, what about generating both the start and end indices for your big discriminant match statement in "Landing the optimization again"? E.g. Sprites::Sprite1 => (0usize, 8usize).
  2. If you replace indexing with unsafe pointer arithmetic and from_raw_parts on the "Using concatenated string for C-like enums" code snippet, does it avoid the compile time slowdown?
  3. How complicated is it to add an unsafe "#[trust_me_it_is_exhaustive]` attribute for match statements to speed up the compiler on generated code?

4

u/panstromek 4d ago
  1. It was one of the ideas as well, but it makes the MIR bigger, so it'd probably erase part of the win. But packing them into a single number could help and something I'll maybe try at some point. Similarly, if we could pack variant name into a number instead of a string where possible, it'd save some of the costs as well.

For 2. and 3., the problem is that you might run into the TOCTOU mentioned in the article. We don't want to use `unsafe` in these derives, becase it's very easy to assume something incorrectly. The initial implementation did use `get_unchecked` and was unsound because of it even though this code is seemingly fully under compiler's control. It might help the compile time issue, but it's unclear, because some of these methods on pointers are generic as well, so some of their costs are similar.

Similarly, the attribute to skip exhaustiveness is an idea that's been floating around in these discussions, but again, if the enum definition is changed during compilation, then suddenly the match is incorrect and the desired behaviour is unclear - but it's either UB or silent ignore, while the preferred one is compile error.

We should really just fix the algorithm I think.

3

u/SkiFire13 4d ago

This algorithm in general is NP-complete, because you can reduce checking of match (boolean, boolean, boolean, ..) to SAT

You got this the opposite way: you can reduce SAT to match exhaustiveness checking, and that proves it's NP-complete.

2

u/panstromek 4d ago

Oh, right, that reduction wouldn't really prove much. Thanks, I fixed the note ;)

3

u/sephg 4d ago

Instead of splitting by space, wouldn’t it be better to just make an offsets array? Eg “RedGreenBlue” + [0,3,8]. Then printing a value would be something like print_str(str[inxs[i]..idxs.get(i+1).unwrap_or(str.len())])

This approach would increase the cost per discriminant by 3 bytes (u32 instead of a space character). But it’s constant time at runtime instead of linear time. And it wouldn’t require any complex string scanning iteration code to be written or pulled in.

5

u/panstromek 4d ago edited 4d ago

This is what the first PR did. I wrote why we moved away from it in the article, it makes the AST, HIR and MIR size bigger.

Note that this is linear only with respect to single variant name, which is usually short. Either way, `Debug` impls are almost always dead, so they are considered cold path and we optimize compile time over runtime for them.

1

u/matthieum [he/him] 4d ago

I do want to note that the generated code could simply pass two indexes (start..end) instead of just start, to avoid the scan.

end is already computed in the compiler for the next variant, anyway.

2

u/panstromek 4d ago

That has the same problem, it's just "transposed" in a way. I'm not sure I made it clear, I'm talking about the compile time/memory impact of pushing this through the compiler, not runtime perf. Whether we have 8k constants in an array or separately in 8k match arms is not as big of a difference, it'll have to be `Box<Expr>` 8k times in AST, `Box<ConstOperand>` 8k times in MIR and so on.

4

u/matthieum [he/him] 4d ago

That TOCTOU issues with macros seems like a fairly serious problem, and yet... I guess it's unavoidable?

I wonder if macros could be classified in two categories:

  • Rewriting: the macro rewrites the item it applies to.
  • Additive: the macro adds new items (trait impls, functions, ...).

I figure that this could be done by simply looking at the macro output, and double-check whether it changed the item or not.

And from there, a warning/error could be emitted if any additive macro is called before a rewriting macro, since anything it added is relying on an old version of the item. Perhaps rerunning the additive macro to check whether it generates the same output first, to avoid false-positives.

Note: a macro can definitely be BOTH rewriting and additive... and the additive parts may definitely be out-of-sync if another rewrite occurs after.

4

u/noop_noob 4d ago

Rewriting macros are known as attribute macros. Additive macros are known as derive macros.

A problem with your idea is that currently, derive macros always expand before attribute macros, and changing this potentially breaks code. Also, macros can produce other macros, and everything becomes a mess with your constraint.

1

u/matthieum [he/him] 3d ago

Rewriting macros are known as attribute macros. Additive macros are known as derive macros.

Is the divide that clean? I wouldn't be surprised if a rewriting macro was also adding trait implementations or impl blocks at the same time.

A problem with your idea is that currently, derive macros always expand before attribute macros, and changing this potentially breaks code.

Really? That's a weird decision, when attribute macros can add/remove attributes, breaking the derives...

Also, macros can produce other macros, and everything becomes a mess with your constraint.

Respectfully, given the TOCTOU problem mentioned here, everything is already a mess.