runtime icon indicating copy to clipboard operation
runtime copied to clipboard

Add support for memory alignment

Open JeffCyr opened this issue 10 years ago • 19 comments

There are some optimizations not available with managed code in .Net because there are currently no ways to enforce a memory alignment greater than the pointer size:

  • Interlocked 64bit in x86 process when the underlying OS is 64bit (See discussion in issue dotnet/runtime#4811)
  • Interlocked 128bit
  • Cache line alignment optimizations

I have no idea if this is easy or hard in the current coreclr design, but it would be nice to have a MemoryAlignmentAttribute that could specify alignment minimally on class type and possibly on any class/struct/field.

My motivation for this feature would be to implement an UnfairSemaphore (#2383) that isn't randomly inefficient in x86 when its 64bit state crosses a cache line boundary.

I have created a gist to isolate the consequences of unaligned Interlocked: https://gist.github.com/JeffCyr/9e162f440e30b567507cc95b6ba5a4a4

On my machine, unaligned Interlocked operation can be 61x slower.

category:proposal theme:alignment skill-level:expert cost:large impact:medium

JeffCyr avatar May 24 '16 21:05 JeffCyr

@JeffCyr, what about [StructLayout(LayoutKind.Sequential, Pack = 16)] (types are in the System.Runtime.InteropServices namespace)?

tannergooding avatar May 24 '16 21:05 tannergooding

@tannergooding The Pack parameter won't affect the base address of the object.

JeffCyr avatar May 24 '16 21:05 JeffCyr

I created a proposal on the CoreFX side here: https://github.com/dotnet/corefx/issues/22790

tannergooding avatar Jul 31 '17 18:07 tannergooding

It has been mentioned that this feature would require major changes to implement in the GC.

Do you think it would worth it to have a global App.Config setting to force 8 byte alignment of all ref types for x86 process running in a x64 OS?

This should be a lot simpler to implement and it resolves the random perf of Int64 in x86 processes. (e.g. dotnet/runtime#4811)

JeffCyr avatar Oct 11 '17 17:10 JeffCyr

As I understand, @Maoni0 and @swgillespie are the GC people to tag on these issues

tannergooding avatar Oct 11 '17 17:10 tannergooding

if you want all objects to have a different alignment that's trivial to implement - we have an Align function that enforces the alignment and is called by every place that calculates the size of an object but does introduce perf penalty as the alignment is no longer a const; if you want the alignment to be a property of a type (which is what FEATURE_STRUCTALIGN implements) that's certainly much more work (the implementation of FEATURE_STRUCTALIGN is incomplete right now) but also has perf penalty as already pointed out on the other thread.

there needs to be a cost-benefit analysis.

Maoni0 avatar Oct 11 '17 21:10 Maoni0

What about just changing the x86 alignment to 8-bytes instead of 4-bytes? The memory increase should be marginal no? And since x86 processors don't really exist anymore, all x86 app could perform better if the alignment match the processor architecture.

JeffCyr avatar Oct 11 '17 21:10 JeffCyr

What about just changing the x86 alignment to 8-bytes instead of 4-bytes?

This seems to be an overkill for what you are trying to achieve, and I don't think the memory increase would be marginal. Moreover, this would not help with "Cache line alignment optimizations" goal listed above.

And since x86 processors don't really exist anymore, all x86 app could perform better if the alignment match the processor architecture.

I don't follow this statement. For best performance, the recommendation is to align data on natural alignment boundaries.

hanblee avatar Oct 13 '17 00:10 hanblee

@hanblee

This seems to be an overkill for what you are trying to achieve, and I don't think the memory increase would be marginal

I don't see how changing to 8-bytes alignment in x86 could increase the memory usage significantly. The worst case is +4 bytes per object, so 4MB per million objects.

I don't follow this statement. For best performance, the recommendation is to align data on natural alignment boundaries.

I meant that nowadays, all x86 application run on a x64 CPU. So if all objects base address is 8-byte aligned, it guarantees that all 8 byte types are 8-byte aligned matching the underlying x64 CPU natural alignment.

Anyway, you're right that this proposition doesn't address the original issue, this conversation could be continued in another issue.

JeffCyr avatar Oct 13 '17 01:10 JeffCyr

I don't see how changing to 8-bytes alignment in x86 could increase the memory usage significantly. The worst case is +4 bytes per object, so 4MB per million objects.

the average size of objects on x86, according to analysis we did, was about 35 bytes, so a 4-byte increase is >10%. that is significant.

Maoni0 avatar Oct 13 '17 02:10 Maoni0

Worst case, if its 4 byte aligned and the law of large numbers kicks in then its 2 bytes average so ~ 5.7% still possibly significant...

Drawaes avatar Oct 17 '17 03:10 Drawaes

Tagging subscribers to this area: @dotnet/gc See info in area-owners.md if you want to be subscribed.

Issue Details

There are some optimizations not available with managed code in .Net because there are currently no ways to enforce a memory alignment greater than the pointer size:

  • Interlocked 64bit in x86 process when the underlying OS is 64bit (See discussion in issue dotnet/runtime#4811)
  • Interlocked 128bit
  • Cache line alignment optimizations

I have no idea if this is easy or hard in the current coreclr design, but it would be nice to have a MemoryAlignmentAttribute that could specify alignment minimally on class type and possibly on any class/struct/field.

My motivation for this feature would be to implement an UnfairSemaphore (#2383) that isn't randomly inefficient in x86 when its 64bit state crosses a cache line boundary.

I have created a gist to isolate the consequences of unaligned Interlocked: https://gist.github.com/JeffCyr/9e162f440e30b567507cc95b6ba5a4a4

On my machine, unaligned Interlocked operation can be 61x slower.

category:proposal theme:alignment skill-level:expert cost:large

Author: JeffCyr
Assignees: -
Labels:

enhancement, design-discussion, area-GC-coreclr

Milestone: Future

ghost avatar Dec 22 '22 03:12 ghost

Worst case, if its 4 byte aligned and the law of large numbers kicks in then its 2 bytes average so ~ 5.7% still possibly significant...

Is not worst case at all. Worst case - is what alignment is needed to avoid false sharing on same cache line. .NET libraries in such cases simply put enermous paddings, in size (e.g. padding twice bigger than cache line), and this caused only because allocator is 4-byte aligned instead of follow normal alignment rules. Both ways are not ideal, but there is serious issue: code which fight with false sharing - definitely want atomic read, but invalid alignment prevent do it. On result (sorry, i forget which type exactly), instead of 64 x 3 bytes tooks 256 x 3 or so. It is idiotical situation, where workaround saves from false sharing by cost of compactness and allow read value from two cache lines at once, what again incorrect. All of this solves with using correct alignment on heap, which fits type requirements.

dmitry-azaraev avatar Sep 10 '25 19:09 dmitry-azaraev

Oversizing an allocation makes no impact to false sharing.

If you do a regular (temporal) read, no matter how small, the CPU will pull a full cache line. A write will likewise only write what you require (but may combine neighboring writes to the same cache line for efficiency), so as long as you aren't writing those extra "padding" bytes as part of your operation then it isn't an issue.

Sharing issues come from two cores touching the same cache line, which is why such allocations are oversized to prevent said sharing concerns because it ensures each core only gets one cache line. If it's truly perf critical, many options such as NativeMemory.AlignedAlloc exist.

tannergooding avatar Sep 10 '25 19:09 tannergooding

Oversizing an allocation makes no impact to false sharing.

It surely has. Imagine you need 3 non-shared fields. To achieve efficiently this - you need align fields on cache-line size. Current .NET code simply put additional padding between fields effectively oversizing really required type size. This is because current (released versions) have no alignment. Paddings are save from false sharing but don't save from reads in-between cache lines because of object alloc alignment.

dmitry-azaraev avatar Sep 10 '25 20:09 dmitry-azaraev

Sharing issues come from two cores touching the same cache line, which is why such allocations are oversized to prevent said sharing concerns because it ensures each core only gets one cache line. If it's truly perf critical, many options such as NativeMemory.AlignedAlloc exist.

Anyone can alloc native memory without special APIs. But you can't have gc refs here, so please, it is not argument. It is even not workaround, and in fact most of time such solutions doesnt work really better, than using .NET heap, the only thing is topic - some things needs alignment. What you argue? Can it work without? Yes. Effectively - absolutely not.

dmitry-azaraev avatar Sep 10 '25 20:09 dmitry-azaraev

Current .NET code simply put additional padding between fields effectively oversizing really required type size

Yes, and provided you don't write the padding (which you shouldn't be) then there is no false sharing. Each field gets its own cache line, the same as you would have for explicit alignment and you only write the bytes for the fields in question (not the unused padding space), again the same as you would for explicit alignment.

The only difference is "where" the padding bytes are. With explicit alignment you always have _field starting at offset 0 of the cache line and then you have sizeof(CacheLine) - sizeof(_field) padding bytes. With the manual padding definition, you may end up with those padding bytes split around the _field since it could appear "anywhere" in the cache line instead.

But you can't have gc refs here

Which is fine for the majority of scenarios. There are plenty of alternative workarounds for the scenarios that do require GC refs and when done properly they behave with the exact same efficiency as explicit alignment would allow; it just requires a bit more effort to achieve.

tannergooding avatar Sep 10 '25 20:09 tannergooding

Does the GC already handle alignment for Vector512? When C# supports union structs, would it be possible to use a union struct containing a Vector512 to ensure proper alignment?

PavelCibulka avatar Sep 11 '25 05:09 PavelCibulka

The .NET GC doesn't do alignment over 8 bytes today. The stack will end up correctly aligning vector types in most scenarios and they will be padded correctly for both value and reference type scenarios.

C# unions may not end up allowing or guaranteeing overlapping fields and doing such things typically pessimize memory and other accesses more than it benefits, so it likely wouldn't be desirable to do that even if it did happen to work.

tannergooding avatar Sep 11 '25 05:09 tannergooding