Skip to content

Unexpected reordering of memory allocation when using GC.GetAllocatedBytesForCurrentThread() when running optimized #96836

Open

Description

@madelson

Description

I'm using GC.GetAllocatedBytesForCurrentThread() in a unit test to verify zero-allocation behavior. My test is like this:

var before = GC.GetAllocatedBytesForCurrentThread();
// do zero-allocation thing
var delta = GC.GetAllocatedBytesForCurrentThread() - before;
Assert.That(delta, Is.EqualTo(0));

I found that this was failing in release mode, where delta as 24 rather than zero. This happened even when I commented out all lines between the 2 GC checks.

Reproduction Steps

Here is a simple program which repros the issue for me in release mode but not in debug mode:

	var before = GC.GetAllocatedBytesForCurrentThread();
	var delta = GC.GetAllocatedBytesForCurrentThread() - before;
	//Thread.MemoryBarrier(); // uncommenting this fixes the problem
	Console.WriteLine((object)delta); // 0 in debug mode, 24 in release mode

Expected behavior

I would expect to always get 0

Actual behavior

I get 24 in release mode

Regression?

Not sure

Known Workarounds

Thread.MemoryBarrier seems to work.

Configuration

.NET 8, Windows 11, x64

Other information

No response

Activity

  1. ghost added
    untriaged
    on Jan 11, 2024
  2. added
    area-CodeGen-coreclr
    on Jan 11, 2024
  3. added
    question
    and removed on Jan 11, 2024
  4. jkotas commented on Jan 11, 2024

    @jkotas
    Member

    The JIT is reordering the allocation of the Int32 box to be in front of GetAllocatedBytesForCurrentThread call as a side-effect of various optimizations. @dotnet/jit-contrib This reordering does not seem to be profitable. Do we want to avoid it?

    However, small allocations are considered to be side-effect free and the JIT can reorder or remove them as it sees a fit in general. Issues like this are expected if you try to use GetAllocatedBytesForCurrentThread. Also, allocations can happen as side-effects of JITing.

           call     System.GC:GetAllocatedBytesForCurrentThread():long
           mov      rbx, rax
           mov      rcx, 0x7FFF6F6894F0
           call     CORINFO_HELP_NEWSFAST
           mov      rsi, rax
           call     System.GC:GetAllocatedBytesForCurrentThread():long
           sub      rax, rbx
           mov      qword ptr [rsi+0x08], rax
           mov      rcx, rsi
           call     [System.Console:WriteLine(System.Object)]
    
  5. EgorBo commented on Jan 11, 2024

    @EgorBo
    Member

    Minimal repro:

        static void Foo()
        {
            long before = GC.GetAllocatedBytesForCurrentThread();
            long delta = GC.GetAllocatedBytesForCurrentThread() - before;
            Console.WriteLine((object)delta);
        }
    Trees after Importation
    
    -----------------------------------------------------------------------------------------------------------------------------------------
    BBnum BBid ref try hnd preds           weight    lp [IL range]     [jump]      [EH region]         [flags]
    -----------------------------------------------------------------------------------------------------------------------------------------
    BB01 [0000]  1                             1       [000..018)        (return)                     i newobj 
    -----------------------------------------------------------------------------------------------------------------------------------------
    
    ------------ BB01 [0000] [000..018) (return), preds={} succs={}
    
    ***** BB01 [0000]
    STMT00000 ( 0x000[E-] ... 0x005 )
                   [000001] DAC-G------                         *  STORE_LCL_VAR long   V00 loc0         
                   [000000] --C-G------                         \--*  CALL      long   System.GC:GetAllocatedBytesForCurrentThread():long
    
    ***** BB01 [0000]
    STMT00001 ( 0x006[E-] ... 0x017 )
                   [000007] DA---------                         *  STORE_LCL_VAR ref    V02 tmp1         
                   [000006] -----------                         \--*  ALLOCOBJ  ref   
                   [000005] H----------                            \--*  CNS_INT(h) long   0x7ff807d94468 class
    
    ***** BB01 [0000]
    STMT00002 ( ??? ... ??? )
                   [000011] nAC-G------                         *  STOREIND  long  
                   [000010] -----------                         +--*  ADD       byref 
                   [000008] -----------                         |  +--*  LCL_VAR   ref    V02 tmp1         
                   [000009] -----------                         |  \--*  CNS_INT   long   8
                   [000004] --C-G------                         \--*  SUB       long  
                   [000002] --C-G------                            +--*  CALL      long   System.GC:GetAllocatedBytesForCurrentThread():long
                   [000003] -----------                            \--*  LCL_VAR   long   V00 loc0         
    
    ***** BB01 [0000]
    STMT00003 ( ??? ... ??? )
                   [000014] --C-G------                         *  CALL      void   System.Console:WriteLine(System.Object)
                   [000013] ----------- arg0                    \--*  BOX       ref   
                   [000012] -----------                            \--*  LCL_VAR   ref    V02 tmp1         
    
    ***** BB01 [0000]
    STMT00004 ( 0x017[E-] ... ??? )
                   [000015] -----------                         *  RETURN    void  
    

    looks like it's an intentional behaviour of impImportAndPushBox - we try to write boxed tree directly to a box instead of saving it to a local first (e.g. for structs that will be a redundant copy I guess)

  6. EgorBo commented on Jan 11, 2024

    @EgorBo
    Member

    So my initial conclusion that this behavior helps us to optimize boxings in certain cases (e.g. from GDVs?)
    it can be "fixed" like this: EgorBo@9a4772d (fixes the issue) but brings a lot of size regressions. Since, as Jan noted, allocation is side-effect free (we ignore OOM as a side-effect) it's legal to keep it as is... we can intrinsify the GC call if needed.

    cc @dotnet/jit-contrib

  7. jkotas commented on Jan 11, 2024

    @jkotas
    Member

    we can intrinsify the GC call if needed.

    What do you mean?

  8. EgorBo commented on Jan 11, 2024

    @EgorBo
    Member

    we can intrinsify the GC call if needed.

    What do you mean?

    To basically always spill GC.GetAllocatedBytesForCurrentThread() if we see it. That will fix this specific issue but other phases might still do something similar. We can also mark all allocations as "have side-effects" in the presense of GetAllocatedBytesForCurrentThread but that probably a bad idea (observing impacts results).

  9. jkotas commented on Jan 11, 2024

    @jkotas
    Member

    To basically always spill GC.GetAllocatedBytesForCurrentThread() if we see it. That will fix this specific issue but other phases might still do something similar.

    Right. I do not think special casing GetAllocatedBytesForCurrentThread in the JIT makes sense.

  10. AndyAyersMS commented on Jan 12, 2024

    @AndyAyersMS
    Member

    The JIT is reordering the allocation of the Int32 box to be in front of GetAllocatedBytesForCurrentThread call as a side-effect of various optimizations. @dotnet/jit-contrib This reordering does not seem to be profitable. Do we want to avoid it?

    As Egor mentioned, the benefit (more apparent with larger value types that are returned by ref) is that the code does not need to copy the value from the call's return buffer into the box payload; instead the call writes the value into the box directly.

  11. madelson commented on Jan 12, 2024

    @madelson
    ContributorAuthor

    Would adding something like a memory barrier inside the implementation of GetAllocatedBytesForCurrentThread be sufficient to prevent this reordering without any JIT changes?

    My (possibly mistaken) assumption is that this methods only real purpose is measurements like what I’ve shown; it would be nice if those behaved as expected.

  12. jkotas commented on Jan 12, 2024

    @jkotas
    Member

    Would adding something like a memory barrier inside the implementation of GetAllocatedBytesForCurrentThread be sufficient to prevent this reordering without any JIT changes?

    It would not help.

    To avoid unexpected interferences between the measured code and the surrounding code, you can wrap the measured code in no-inline method. Wrappers like this are common for perf microbenchmark. For example, Benchmark.NET does something similar.

    [MethodImplAttribute(MethodImplOptions.NoInlining)]
    static int Measure()
    {
    	var before = GC.GetAllocatedBytesForCurrentThread();
    	var delta = GC.GetAllocatedBytesForCurrentThread() - before;
    }
    
    Console.WriteLine((object)Measure());
  13. added this to the 9.0.0 milestone on Jan 13, 2024
  14. ghost removed
    untriaged
    on Jan 13, 2024
  15. modified the milestones: 9.0.0, Future on May 2, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-CodeGen-coreclrquestion

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions