Repository navigation
Closed
Labels
JitThroughputCLR JIT issues regarding speed of JIT itselfarea-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI
Milestone
Description
This issue proposes a series of changes to reduce the overhead and increase the fidelity of local variable reference counts in the jit. The main idea is to get rid of the current costly and buggy incremental count maintenance in favor of batch updates that are done just before accurate ref counts are needed.
See discussion in #8715 for background.
Expected impact is:
- 4-5% improvement in tier0 / minopts / debug throughput
- minimal impact to optimized jit throughput
- smaller frame sizes in some cases where reference counts are currently inflated
- removal of workarounds to artificially inflate reference counts to avoid asserts
The more accurate reference counts and weighted counts are likely to cause widespread codegen diffs. Hopefully these will mostly be improvements, but some regressions are certainly possible.
Proposed steps are:
- encapsulate accesses to
lvRefCntandlvRefCntWtdin an API, make backing fields private (Investigate preallocating space for ICollections/IIListProvider in SelectEnumerableIterator methods #18979) - characterize when ref count access and update is invalid, and update API to flag invalid access (System.Linq.Expressions factories throw NullReferenceException with global fields and global methods #19068)
- classify invalid accesses and figure out strategies for removing them (Add XmlSchema and Xslt test coverage for Non-Windows platforms #19012)
- once all invalid accesses are removed, add appropriate asserts to catch invalid accesses (System.Linq.Expressions factories throw NullReferenceException with global fields and global methods #19068)
- figure out what actions under
lvaMarkRefsare required for all compilations vs only needed when optimizing (WebUtility.HtmlDecode does not decode all HTML5 character entities #19103, JIT: refactor ref count computation into a reusable utility method coreclr#19240) - figure out minopts / debug codegen approach (WebUtility.HtmlDecode does not decode all HTML5 character entities #19103)
- ensure we have an algorithm that can properly recompute counts from scratch (NullReferenceException when calling Vector<float>.CopyTo in Release mode #19240)
- recompute counts after lower (Failed to cross build for ARM32 #19325)
- change from incremental updates to batched updates (System.Data.SqlClient.sln contains stresstest project that does not exist #19345)
- decide how often counts need to be made current (or track if they've possibly gone stale) (System.Data.SqlClient.sln contains stresstest project that does not exist #19345)
- sort through codegen diffs resulting from more accurate ref counts and fix what can be fixed (System.Data.SqlClient.sln contains stresstest project that does not exist #19345)
- try and clean up the logic in
lvaMarkRefsto split out ref counting from other activities
cc @dotnet/jit-contrib
category:implementation
theme:ir
skill-level:expert
cost:large
Reacted by Bruce Forstall, mikedn, Haytham ElFadeel and ikopylov
Metadata
Metadata
Assignees
Labels
JitThroughputCLR JIT issues regarding speed of JIT itselfarea-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI
Activity
JIT: force all local var ref counts to be accessed via API
AndyAyersMS commentedon Jul 18, 2018
Currently local ref counts become valid after
lvaMarkLocalVarsand are supposed to stay valid for the remainder of compilation (will update as I discover more)....Here are some of the references / updates to ref counts that happen before that point:
lvaPromoteStructVar-- ref count bump for promoted reg arg fields for "prolog" init countfgMarkImplicitByRefArgs-- zero ref counts for implicit by-ref parametersfgMarkAddressExposedLocals-- track ref counts for implicit by-ref parametersfgRetypeImplicitByRefArgs-- use ref counts to decide whether to promote implict by-ref parametersfgMakeOutgoingStructArgCopy-- use implicit by-ref parameter ref count to try and detect if the last use of the parameter is a call arg; if so try and avoid a copyfgGrabTempWithImplicitUse-- eg for the inline pinvoke frame var, hidden stub parameterlvaMarkLocalVarsdoes some ref count manipulation before turning on "ref counts valid" modemikedn commentedon Jul 18, 2018
I'm curious how did you come up with that estimate :). Also, do we even need ref counts in minopts?
AndyAyersMS commentedon Jul 18, 2018
Perf estimates are from #8715.
I have a reasonably up to date version of this so can re-validate ... probably a good idea.
AndyAyersMS commentedon Jul 18, 2018
Yeah, performance estimates still seem to hold up, eg PMI of Microsoft.CodeAnalysis.CSharp with minopts goes from 1334ms to 1275ms, around 4.5%, based on the just-updated prototype.
Actual benefit may be higher because the prototype still leaves a lot of ref counting cruft behind.
AndyAyersMS commentedon Jul 18, 2018
Roughly speaking, the "invalid" ref count accesses in the current scheme (ref count reads, incs, decs, or sets before the jit officially starts ref counting) fall into categories:
The implicit cases can perhaps better be handled by new local var property bits, eg
lvHasImplicitReferenceorlvHasTemporaryImplicitReference. If these bits are set then thelvRefCnt()should always return nonzero counts (likely just adding 1 to the explicit ref count result is sufficient) and likewise for the weighted version. The distinction between always implicit and transiently implicit may not matter as it might be OK to lump them together into one category. But if not, then at some point when the appropriate lowering happens the transient implicit bit can be turned off and ref counts established for the variable.The conveying cases can perhaps be tolerated by using a different set of APIs or a special parameter to permit temporary (short-lifetime) use of ref counts for some subset of locals.
Struct last use copy avoidance is arguably something better handled by the work on first class structs as that should be more general, more capable, and less fragile.
JIT: force all local var ref counts to be accessed via API (#18979)
JIT: handle implicit local var references via local var attribute bit
AndyAyersMS commentedon Jul 19, 2018
dotnet/coreclr#19012 should clear up the implicit reference cases and the avoidable cases.
For the other cases, one thought is to essentially make ref counts into something like a phased var, where the count fields are valid only for a certain time and certain purpose. The various APIs would then be extended with an enum describing the accessing phase, and this would be error-checked against the current phase. This could extend later to describe intervals when the counts are valid or potentially stale.
The error checking is a bit clunky with the current API shape as we either also need to pass in the compiler instance or fetch it from TLS. But perhaps the latter is acceptable....?
briansull commentedon Jul 19, 2018
It is fine for use in Debug only code, but we should avoid using it for retail code
AndyAyersMS commentedon Jul 19, 2018
It would be something like this:
CarolEidt commentedon Jul 19, 2018
This rings a bell, but I don't recall exactly what's being done. Can you point me to this?
Re: the error checking, I think it's fine to fetch the compiler instance from TLS for an assert.
AndyAyersMS commentedon Jul 19, 2018
Look at
fgMakeOutgoingStructArgCopyCarolEidt commentedon Jul 19, 2018
Thanks @AndyAyersMS - I now recall that some time ago when I was making the first round of 1st class struct changes, I deleted this line: https://github.com/dotnet/coreclr/blob/master/src/jit/morph.cpp#L5297 but it caused diffs, which I was trying to avoid and I wanted to analyze it further - so I created that "to do" and it's still there :-(
21 remaining items
AndyAyersMS commentedon Aug 16, 2018
Playing around with removing the local table sort. Think removing it may also have minimal codegen impact. Should have data shortly.
Because of the way
lvaSortByRefCountis currently written, we may end up tracking less thanlclMAX_TRACKEDlocals and still leave some trackable locals untracked (because some low-numbered locals are untrackable).CarolEidt commentedon Aug 16, 2018
If we are eliminating the sort, we may want to still consider https://github.com/dotnet/coreclr/issues/11339. I think it could improve throughput to make the set of lclVars that are live across blocks more dense, and would also enable slightly different heuristics for the two types. Also, many, if not all, of the locals introduced in
RationalizerandLoweringare live only within a block (and usually single-def) - knowing those properties would be beneficial to register allocation.CarolEidt commentedon Aug 16, 2018
.. and if it is indeed the case that
RationalizerandLoweringonly ever introduce lclVars that are live only within a block, then perhaps we could avoid running liveness after those phases, and just set thelvTrackedfield and theGTF_VAR_DEATHflag appropriately as new lcls are introduced by the backend.AndyAyersMS commentedon Aug 16, 2018
Interesting.
Since we walk the IR to recompute the ref counts, we should be able to fairly cheaply determine if a trackable local's lifetime is block-local, and split the tracking index assignment into two passes so the globally live locals all have low tracking indexes.
AndyAyersMS commentedon Aug 17, 2018
Back to sorting for the moment -- very few methods (~10) in the pmi -f set have more than 512 trackable locals, and the issue I noted above doesn't seem to crop up for any of them, as we evidently do a good enough job sorting that in the first 512 sorted candidates all are trackable.
So one might expect a small number of diffs.
However, the numbers say otherwise:
For the most not sorting this would be a size wash or win except for the trace event methods -- they have huge numbers of temps. We can "fix" the problem there by less aggressively tracking structs but that's not good in general. (The wins seem to come perhaps from changes in CSE behavior; haven't looked at this to closely yet).
So we might consider some kind of two-pass tracking selection where the first pass picks out higher priority cases and the second pass then fills in anything else trackable until we run out of space. Or several passes if we want to get globally live things densely clustered in the ID space.
The second issue is that the jit is evidently sensitive to the ordering relationship induced by the ID -- these have been effectively "permuted" by not sorting the table, and this is likely what causes the larger number of diffs. If we're sorting the IDs reflect an underlying ordering metric based on weighted ref counts (and other things) it seems likely we can track down where the ordering comparison happens with IDs and perhaps replace it with the predicate used to sort -- if it's not needed too often.
AndyAyersMS commentedon Aug 17, 2018
Worth pointing out that the methods with big regressions all have large numbers of trackable but untracked locals. Some rough accounting...
mikedn commentedon Aug 17, 2018
Considering that such large methods tend to be rare would it make sense to increase the max number of tracked variables?
AndyAyersMS commentedon Aug 17, 2018
Maybe? The liveness time and space cost is proportional to BV size * number of BBs. So if a method has a lot of locals but few BBs then sure, we could up the limit. If it has a lot of locals and a lot of BBs then perhaps we shouldn't be optimizing it at all.
Divergence (at least in cases I've explored so far) for fully trackable methods seems to come about in
LinearScan::buildIntervals()where we create intervals for reg params inlvVarIndexorder.We can rewrite this bit to just sort the tracked reg params (usually just a handful) using the old predicate.
mikedn commentedon Aug 18, 2018
Yep, it needs to be done with care, we probably don't need another JIT64. I was considering making the max number of tracked variables configurable after I got rid of fixed size arrays in 18504, just to see what impact increasing the limit has. But I've yet to get to it...
Hmm, I suppose that would allow making the global BB BVs smaller than the BVs used for local liveness. But such a change is probably rather tricky and would not help if it turns out that there number of globally live lclvars is high.
AndyAyersMS commentedon Jan 16, 2019
lvaMarkLclRefsstill does a bunch of unrelated computation but I'm not planning on disentangling it any time soon. Moving to future.AndyAyersMS commentedon Feb 19, 2020
This is basically done, so will close.