dotnet / Silk.NET

The high-speed OpenGL, OpenCL, OpenAL, OpenXR, GLFW, SDL, Vulkan, Assimp, WebGPU, and DirectX bindings library your mother warned you about.
https://dotnet.github.io/Silk.NET
MIT License
4.13k stars 397 forks source link

Make use of SkipLocalsInit Attribute #390

Open thargy opened 3 years ago

thargy commented 3 years ago

Summary of feature

C#9.0 introduces the SkipLocalsInitAttribute which can be added at the module, class or method level. Once added it prevents the compiler from emitting the .locals init directive, instead using just the .locals directive. At that point any locals are not immediately zeroed on declaration at the start of a method. This can lead to performance gains.

There is an excellent article here, which goes into details.

Comments

Further to the above article, 3 areas where care needs to be taken are:

Put simply, the compiler normally prevents you from using a local variable until it has been initialised, which is why the new SkipLocalsInitAttribute has been added, as the zeroing is frequently unnecessary. However, when passing pointers to variables around you are now exposing uninitialised memory which can easily result in security issues or break existing code that is expecting zeroed memory. Similarly, care should be taken when using stackalloc to zero out the allocation or initialise it, prior to passing it to an external function, for example when using it as a temporary buffer to be filled by a driver.

The attribute can be added at the module level, which would immediately turn it off initialisation everywhere, and then individual exceptions can be manually addressed by zeroing the data. Alternatively, it can be added on a per-class or per-method basis. The latter approach will improve visibility, reminding maintainers to review their code for appropriateness, and also makes it easier to turn off for a particular method, rather than adding the initialisation manually.

Compatibility

Although this is a compiler feature, the attribute itself is introduced in .NET 5, so a fallback shim would need to be added to https://github.com/Ultz/Bcl/.

There should be no breaking changes introduced by making this change, so long as care is taken to review the above scenarios on implementation. As such, this can be done as part of a future minor release. However, it is likely to have a very positive impact on the performance of the library for very little investment.

Perksey commented 10 months ago

3.0 triage, @tannergooding does ClangSharp have any particular strategy here?