Repository navigation
Description
This is a follow-up from #1007.
For this example
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public class C {
[StructLayout(LayoutKind.Sequential, Size = 20)]
public struct Buffer
{
public ulong Field1;
public ulong Field2;
public uint Field3;
}
public void M() {
var buf = new Buffer();
buf.Field1 = 2;
DoSomethingWithMyType(buf);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public void DoSomethingWithMyType(Buffer buf)
{
// Do Something.. to prevent the JIT from optimizing it all awayyyy
}
}the jit generates the folllowing code:
G_M25775_IG01:
4883EC38 sub rsp, 56
G_M25775_IG02:
33C9 xor rcx, rcx
33C0 xor eax, eax
BA02000000 mov edx, 2
4C8D442420 lea r8, bword ptr [rsp+20H]
498910 mov qword ptr [r8], rdx
49894808 mov qword ptr [r8+8], rcx
41894010 mov dword ptr [r8+16], eax
488D4C2420 lea rcx, bword ptr [rsp+20H]
E881A9FFFF call C:DoSomethingWithMyType(Buffer)
90 nop
G_M25775_IG03:
4883C438 add rsp, 56
C3 ret
; Total bytes of code 45, prolog size 4, PerfScore 12.00, (MethodHash=0c929b50) for method C:M()Both rcx and rax are used to hold 0.
@CarolEidt's comment from #1007:
I believe there's a separate issue that occurs when the register allocator enregisters a promoted field that's being set to zero. If that field is then only used to copy to another field on the stack (or if it is spilled) we can wind up creating multiple zeros in registers.
There are a number of instances of these kinds of issues in the frameworks.
A couple to look at to see if they can be addressed by the same fix(es):
Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts:BeginOfBlockStatementIfAny(Microsoft.CodeAnalysis.SyntaxNode):Microsoft.CodeAnalysis.SyntaxNode In Microsoft.CodeAnalysis.VisualBasic.dll. This has the "multiple copies of zero" problem (on x64, both Windows and Linux).
category:cq
theme:register-allocator
skill-level:expert
cost:medium
Activity
erozenfeld commentedon May 27, 2020
@dotnet/jit-contrib
AndyAyersMS commentedon May 27, 2020
@erozenfeld milestone? Future?
erozenfeld commentedon May 27, 2020
I think it can be Future unless @CarolEidt thinks we should try to fix this in .NET 5. I'm not sure how much register allocator work will be involved in fixing this.
tannergooding commentedon May 27, 2020
This also comes up for
HWIntrinsicsandSIMDIntrinsicswhere multiple SIMD registers may hold "zero" at the same time.AndyAyersMS commentedon Jun 1, 2020
Let's mark it as future. Does not preclude us from looking at it in .Net 5.
CarolEidt commentedon Jun 1, 2020
Agreed - I'm pretty sure that I wouldn't be able to get to this in the immediate future, and I suspect that the best near-term way to address this would be to see if we can get these addressed by extending the existing constant register support in the JIT to enable reuse of dead lclVar values.
Of course, I'd be happy to support/consult with someone who wanted to dive in to the register allocator and work on this (or figure out another good way to address it)!
CarolEidt commentedon Nov 10, 2020
This and #37216 should be analyzed to see whether they remain after work that was done for .NET 5 to eliminate redundant zeroing.
2 remaining items
AndyAyersMS commentedon Apr 9, 2021
Where do we first create the zeroing pattern? Morph?
kunalspathak commentedon Apr 9, 2021
Yes
AndyAyersMS commentedon Apr 9, 2021
Seems like
fgMorphPromoteLocalInitBlockcould perhaps check and see if all assignments are integer types with a zero init pattern, and for intel 64 bit targets, just initialize a single zero temp of the longest size and use it for all cases.For arm64 suspect we're already using the build-in zero reg?
Not as sure about 32 bit targets. What does the codegen look like on x86? Wondering if we end up zeroing 3 registers there...
kunalspathak commentedon Apr 9, 2021
I will try to come up with a fix as you suggested.
Thanks for asking me to check for other targets:
Bufferafter the call.kunalspathak commentedon May 11, 2021
I tried this approach, but constant propagation undo the work we do in morph and we end up with similar code.
kunalspathak commentedon May 13, 2021
So I was trying to think of other mechanism through which we can capture such scenarios as well as the ones in #52286. The common pattern of these scenarios is constant propagation happens and we have multiple tree with structure like this:
Although it sounds great to propagate constant, but it is not always profitable (specially if the constant being propagated for assignment). It puts register pressure and generate inferior code as explained below:
During lowering, the above nodes are transformed into:
In register allocation, when we build intervals, we end up creating 3 ref positions for
x = 0operation.RefDef(t2 = CNS_INT long 0)RefUseRefDef.Last 2 ref positions are created inside:
runtime/src/coreclr/jit/lsrabuild.cpp
Line 3327 in ce396bb
When we allocate, we give a register say
rdxto ref position#1and#2above. They are marked as holding a constant value. Since 2nd refposition was the last use of the constant, registerrdxis technically available when we start the allocation of ref position#3. If that is the popular one, it gets assigned to ref position#3. When we do that, we unmark thatrdxis holding a constant (although it still is). Thusrdxwas a constant holding register whose constant got wiped off because it got allocated immediately to ref position#3.Next, we try to allocate registers for second group of 3 refpositions:
rax.In a nutshell, here is allocating table looks like.
#2,#3and#4forms the first group where we can see thatrdxis assigned.#5,#6and#7forms the second group whereraxis assigned.Here are few options that I explored and prototyped in past couple of days, but was not helpful (ignoring the facts that there were lot of asserts that I had to comment out)
Option1
What if, when assigning to ref position
#4, we add an indicator saying "it holds constant value"? We can do that inruntime/src/coreclr/jit/lsrabuild.cpp
Line 3446 in ce396bb
op1->IsCnsIntOrI(). Next, if the registerrdxis getting assigned to such refpositions (like#4), do not clear the "constant value" flag. ("Constant value" flag tells that the register holds a constant value). Basically indicate that althoughrdxis being assigned to different non-constant interval, it still holds the constant value.Next, when assigning to
#5, we would getrdxback because it is still marked with "constant value". But when it gets assigned to the new interval of#5, make sure that we do not spill the value of#4(that's what register allocator will do because it thinks thatrdxwas assigned to#4, but now since it is being assigned to#5, I need to store value of#4on stack). And then reload the value. With that approach, I was able to getrdxbeing reused, but there were extra spills that got generated and I didn't debug. Also, there were lot of asserts on the way that I commented so was not sure if that was the right route to take.This is in my private branch: https://github.com/kunalspathak/runtime/tree/const-prop-lsra
Option2
After
rdxis assigned to#2and#3, somehow allocate different registerrbxassigned to#4. That will make sure thatrdxis still marked with having "constant value". However, with that, we will have to add an extra move to move the0value fromrdxtorbxand might be worse.Thinking about these possible solutions in register allocation, I feel this is not a scenario that register allocator should/needs to handle. I believe the right phase to address this is somewhere earlier either in CSE, constant propagation, etc. I tried
COMPlus_JitConstCSE=4, but that doesn't help. I think we need a phase that will reverse the constant propagation (at least for assignments) if there are more than X assignments of a constant C. So it should transform something like this:to
What is the best phase to do this?
AndyAyersMS commentedon May 13, 2021
There is a concept in register allocation known as rematerialization: live ranges whose values can be cheaply recomputed. These live ranges never need spilling or home locations. Constants are the classic example.
So one model would be for us to aggressively CSE constants, and then during RA, mark the live ranges as rematerializable. Because these constants are "cheap to spill/reload" you could freely evict them from registers when you encounter pressure. So this opportunistic re-use gives you the same sort of "undo CSE" ability that you're referring to above, but it is based on RA knowledge so doesn't need to follow some simple heuristic like counting number of appearances or their weights or trying to guess when we have high pressure.
Not sure if this is what you are looking for...
Another approach I've seen used is to write a cheap/fast post-RA cleanup that just checks locally for constants and reuses them even if initially they weren't CSEd. This can often leverage "nearby" constant values to avoid rematerializing full literals, say if you have
it might end up changing this to
But it can't clean up bad spills, so likely you'd want to get the rematerialization in the RA working first.
sandreenko commentedon May 14, 2021
Both options look like big work items, I guess they are out of 6.0 scope?
Maybe a part of option 2 can be done via something like "setOfConstRegs" and when we choose a free reg we first choose from "free & ~setOfConstReg"? We will create a bigger register pressure but only in cases where we still have free regs. Unfortunately, it could be a regression on x64 because reg encoding takes a different number of bytes, but maybe without #7996 it is currently random so the sum diff would be zero.
I agree with Andy that we need rematerialization but I thought we have the necessary instruments to get it with a small tweaking, CSE already can do its part and + "cheap to spill/reload" sound like
regOptionalflag.kunalspathak commentedon May 15, 2021
Thanks @AndyAyersMS and @sandreenko for the ideas. I skimmed through the rematerialization paper and sounds like a good idea. It is based on an initial pass where we annotate the information (terminology
tagsused in the paper) before hand so we can have enough information during allocation. As mentioned offline, I am thinking about similar pre-RA pass, not just for constants but also for better allocation in loops. I will try out some prototype to see how far I can go.@sandreenko - We already have the concept of "setOfConstRegs":
runtime/src/coreclr/jit/lsra.h
Lines 1606 to 1619 in 127be4b
and we check it first during allocation before checking for any other heuristics.
runtime/src/coreclr/jit/lsra.cpp
Lines 3078 to 3086 in 7db5438
However, while debugging this issue, I realized that sometimes the register that holds constant is marked as "busy" and we only check if any of the available regs have constant value or not. So, many times, we already filter out the register having constant value before checking if it exist in
m_RegistersWithConstants. That might be something that need to be fixed and I tried fixing in my private branch I shared above.I will mark this as "Future" for now.
kunalspathak commentedon Jul 21, 2021
Rematerialization related tracking issue - #6264