runtime icon indicating copy to clipboard operation
runtime copied to clipboard

Avoid zeroing memory on stackalloc?

Open RossNordby opened this issue 11 years ago • 57 comments

The current stackalloc implementation uses a tight loop of push instructions to allocate and fill in the memory. For example, stackalloc int[16384] yields:

000007FE8D8A05C4  mov         eax,10000h
000007FE8D8A05C9  push        0
000007FE8D8A05CB  push        0
000007FE8D8A05CD  sub         rax,10h
000007FE8D8A05D1  jne         000007FE8D8A05C9

Given that the use of stackalloc is often performance related, it would be nice if the stack pointer just jumped directly to the end and left the memory as-is. This appears to be permitted by the C# spec, section 18.8: "The content of the newly allocated memory is undefined."

Changing this behavior would nastily break applications that relied on the zeroing (despite spec). I'm not sure how much of a problem this would be. It's a niche feature that tends to be used for very specific reasons, and older JIT versions seemed to leave the memory as-is (according to some postings circa 2003).

RossNordby avatar Jul 23 '15 04:07 RossNordby

In your example, the JIT has been told to force a zero initialization. There is code in the JIT to simply do large frame stack page probing without zero init, but that didn't kick in here.

BruceForstall avatar Jul 23 '15 06:07 BruceForstall

Changing this behavior would nastily break applications that relied on the zeroing (despite spec).

Note that zeroing is not always done even today. The following code prints 42, that value remains on the stack from Foo:

static unsafe void Main() {
    Foo();
    int* p = stackalloc int[16384];
    Console.WriteLine(p[0]);
}
static unsafe void Foo() {
    int* p = stackalloc int[16384];
    for (int i = 0; i < 16384; i++)
        p[i] = 42;
}

mikedn avatar Jul 23 '15 07:07 mikedn

Interesting! I should have looked deeper.

If my new understanding is right, the JIT just obeys the method IL header CorILMethod_InitLocals flag when choosing how to allocate, and III.3.47 of the CLI spec suggests that the JIT has no choice but to obey. Darn.

I guess any remaining degrees of freedom would be over on the roslyn side of things.

RossNordby avatar Jul 24 '15 00:07 RossNordby

It's even more interesting if you check the C# specification and you find this text in 19.8:

The content of the newly allocated memory is undefined.

Go figure. I think that the IL spec is a bit messed up for requiring localalloc to follow the localsinit flag. That's why in my above example no zeroing is done, Main doesn't contain any locals and there's no localsinit flag. Perhaps Roslyn should just refrain from using localsinit in unsafe methods, it's of no use anyway.

mikedn avatar Jul 24 '15 05:07 mikedn

Not setting localsinit for unsafe methods sounds like a good option. I haven't found anything that would restrict that in the specs yet, given that verifiability is already out the window. I think I might go write up an issue on that.

Another option might be to introduce a separate IL instruction that does not have the same baggage as localloc, allowing stackalloc to be implemented according to its looser C# spec. I think this might run afoul of the blanket implications of localsinit, though:

A “localsinit flag” that indicates whether the local variables and memory pool (§I.12.3.2.4) should be initialized by the CLI.

At best, it would be a weird corner case. Also, while I'm not familiar with the process behind doing such a thing, I would guess a change to Roslyn's localsinit behavior would be easier if acceptable.

RossNordby avatar Jul 24 '15 22:07 RossNordby

@mikedn I'm not seeing this (re localsinit); even declaring the stackalloc'd variable results in a localsinit being emitted?

char* output = stackalloc char[length];
.method private hidebysig static string MultiBlockAsciiString(
    class MemoryBlock block,
    int32 offset,
    int32 length) cil managed
{
  // Code size       17 (0x11)
  .maxstack  4
  .locals init ([0] char* output)
  IL_0000:  ldarg.2
  IL_0001:  conv.u
  IL_0002:  ldc.i4.2
  IL_0003:  mul.ovf.un
  IL_0004:  localloc
  IL_0006:  stloc.0
  IL_0007:  ldarg.0
  IL_0008:  ldarg.1
  IL_0009:  ldarg.2
  IL_000a:  ldloc.0
  IL_000b:  call       string ::MultiBlockAsciiIter(
                                                class MemoryBlock,
                                                int32,
                                                int32,
                                                char*)
  IL_0010:  ret
}

benaadams avatar Nov 01 '15 06:11 benaadams

Correction: localsinit being dropped does happen but there are some extra caveats; trying to narrow down

benaadams avatar Nov 01 '15 06:11 benaadams

Haven't quite narrowed it down; but if you call a method it needs to be first param; and some sorts of work triggers it; possibly for loop even with the index being not local.

Pattern that seems to work:

1..function that declares via statckalloc and does no other work other than 2. returning result of another function that takes the stackalloc as first param

Can pass though needed vars from first function to second. Bit of a contort...

See as example: https://github.com/aspnet/KestrelHttpServer/pull/312/files#diff-7042cc5345ca45a84e36433636d7f10fR15

benaadams avatar Nov 01 '15 07:11 benaadams

There is code in the JIT to simply do large frame stack page probing without zero init, but that didn't kick in here.

@BruceForstall Could you share where this might be? I saw that CoreCLR generates 0 initialization of stack locals very late in the prolog in one of the Kestrel hotspots.

choikwa avatar Nov 01 '16 22:11 choikwa

@choikwa you can do it with stackalloc, but you have to do a weird pattern of stackallocing in one function and nothing else except passing that variable into another function - then the function doing the stackalloc won't zero.

benaadams avatar Nov 01 '16 22:11 benaadams

For stackalloc, the code is in CodeGen::genLclHeap(). Zero init of stack locals in the normal prolog is in CodeGen::genZeroInitFrame()

BruceForstall avatar Nov 01 '16 23:11 BruceForstall

Is there any particular reason why zero init of stack locals must be done at the prologue *generation? Why not expose this to the optimizer which can dead-store-eliminate or push down init. where it's only necessary?

choikwa avatar Nov 01 '16 23:11 choikwa

(I believe) we only zero init local vars with GC types that are untracked (thus don't get individual operation GC state change information). There may be other cases, such as potentially uninitialized locals in verifiable code.

BruceForstall avatar Nov 02 '16 06:11 BruceForstall

Cursory search for zero init of locals:

  • Above method, in the prolog generation by tracking lvMustInit field of LclVarDsc
    • tracking seems to be done at Compiler::fgInterBlockLocalVarLiveness().

      I am confused by this comment; I would be thrilled if someone could explain to me the need for volatility and must-init.

    /* Mark all pointer variables live on exit from a 'finally'
       block as either volatile for non-GC ref types or as
       'explicitly initialized' (volatile and must-init) for GC-ref types */
  • Compiler::fgInlinePrependStatements() for zero init of inlinee's locals by inserting assignment trees

The BOTR doesn't seem to describe why the former is needed or GC's relation to the stack locals. It would be nice if there are no hard restrictions to moving zero-init from prolog to earlier pass.

choikwa avatar Nov 02 '16 18:11 choikwa

We don't enregister anything live in/out of handlers. That's because an exception in a "try" can happen at any time, and the handler needs to be able to find the current value of the variable in that case. The OS/VM doesn't preserve registers from the "try" to the handler, so the only place we can find the variable is on the stack. Thus, all writes to the variable must be to the stack. We could do better here in some cases, but that's the current status.

We only need to explicitly zero non-arg, GC-ref types because we're going to report them to the GC, and they must always have a valid value (zero is valid). If we knew the value was always defined before entering every EH region that had a handler using that value, we might be able to avoid force zero initializing it in the prolog. This could be improved with some better analysis.

It looks like Compiler::fgInlinePrependStatements() only zero inits locals for cases where the IL for a function requires it for the inlinee.

BruceForstall avatar Nov 02 '16 22:11 BruceForstall

@BruceForstall @choikwa This issue is about unnecessary zero-initialization for stackalloc in C# / localloc in IL.

jkotas avatar Nov 02 '16 23:11 jkotas

We need to do something about this for Span<T> to work end-to-end.

jkotas avatar Jun 12 '17 20:06 jkotas

I have look into this some more:

  • Run CoreCLR tests with a hack that suppressed the init-locals bit for everything. No issues in the JIT found. (~30 tests written in IL that were exercising the init-locals bit failed - by design.)
  • Found one place in corelib that depends on the stackalloc memory to be zero-initialized: https://github.com/dotnet/coreclr/blob/97c58ac4fce27b7796206a59eea0ca27cb49fe1a/src/mscorlib/src/System/RtType.cs#L621
  • Observed that clearing the init-locals bit helps code quality with “out” arguments. The storage for “out” arguments is always zero-initialized today because of the init-locals bits, but the zero-initialization is not necessary (if the out arguments do not contain GC pointers).

The current options that I am thinking about are - from the most preferred to least preferred:

  1. Change C# compiler to not set the init-locals bit for unsafe methods; or even for everything in assemblies compiled with /unsafe or with a new compiler switch. Works for existing runtimes. Potentially breaks code like the corelib example above.
  2. Introduce option for ILLinker to clear the zero init locals bit on all methods in assembly. It would be the start of turning ILLinker into a full IL-to-IL optimizer. There are number of optimization ideas that we do not have a good place to put today – they are hard/expensive/breaking/complex to implement in either Roslyn or JIT. https://github.com/dotnet/roslyn/issues/15929
  3. Introduce a new CompilationRelaxations.NoZeroInitLocals flag and make folks to explicitly add it if they need fast stackalloc or other benefits of no init-locals bit. It is a bit odd design because of one piece data invalidates other piece of data. Does not work for existing runtimes.

Having a new intrinsic method that does not zero init, or having flexibility to control this at method granularity, seems to be unnecessary. Assembly level granularity should be sufficient for this.

jkotas avatar Jun 15 '17 01:06 jkotas

Change C# compiler to not set the init-locals bit for unsafe methods

Probably works; and unsafe blocks.

for everything in assemblies compiled with /unsafe or with a new compiler switch

Probably a bit heavy?

MethodImpl flag?

[MethodImpl(MethodImplOptions.NoZeroInitLocals)]

benaadams avatar Jun 15 '17 02:06 benaadams

[MethodImpl(MethodImplOptions.NoZeroInitLocals)]

This is variant of 3. I think that folks who care about this would want it for all their code, without need to annotate every method.

jkotas avatar Jun 15 '17 02:06 jkotas