roslyn icon indicating copy to clipboard operation
roslyn copied to clipboard

Avoid reusing temps whose refs might be captured

Open jjonescz opened this issue 1 year ago • 6 comments

Fixes https://github.com/dotnet/roslyn/issues/67435.

The idea is to have a "heuristic" to detect whether a method might capture the references passed to it. If such method call is detected, and a temporary reference is being emitted, we avoid freeing the temp so it lives during the whole method instead of just the expression.

The heuristic is implemented by CodeGenerator.MightEscapeTemporaryRefs. It runs on the lowered nodes (because it's the emit layer which decides to emit a temporary). It might have false positives (some calls like M(rvalue, out _) might be marked by the heuristic as dangerous but they are not), but it shouldn't have false negatives.

Without a heuristic, we would need to avoid reusing many more temps, which would be a regression (at least in IL size). But perhaps that's negligible and it would be better to avoid this complexity? I'm not sure.

jjonescz avatar Nov 21 '24 15:11 jjonescz

Done with review pass (commit 1), tests are not looked at.

AlekseyTs avatar Nov 22 '24 18:11 AlekseyTs

Done with review pass (commit 6)

AlekseyTs avatar Dec 05 '24 02:12 AlekseyTs

@dotnet/roslyn-compiler for a second review, thanks

jjonescz avatar Jan 13 '25 09:01 jjonescz

@dotnet/roslyn-compiler for a second review, thanks

jjonescz avatar Jan 30 '25 17:01 jjonescz

A more general thought I had when I was reviewing is that it seems there are several places which are doing the equivalent of a "best common type", except for safe-contexts. This, as well as "method arguments must match" checks, and likely other places. Possibly a shared implementation should be used for these.

I'll try to get into more details on what I mean when I do another full review pass. Thanks

RikkiGibson avatar Feb 05 '25 16:02 RikkiGibson

@RikkiGibson when you have time again, can you take another look? Thanks.

jjonescz avatar Mar 12 '25 14:03 jjonescz

I will try to get to this this week

RikkiGibson avatar Jul 10 '25 18:07 RikkiGibson