Skip to content

Analyzer Proposal: Seal internal/private types #49944

Closed
dotnet/roslyn-analyzers
#5594

Description

@stephentoub

There are numerous performance benefits to sealing types:

  1. Calls to overrides can be done directly rather than with virtual dispatch, which then also means they can be inlined.
public class C {
    internal void Call(SealedType o) => o.M();
    internal void Call(NonSealedType o) => o.M();
}

internal class BaseType
{
    public virtual void M() {}
}
internal class NonSealedType : BaseType
{
    public override void M() {}
}
internal sealed class SealedType : BaseType
{
    public override void M() {}
}

results in:

C.Call(SealedType)
    L0000: cmp [rdx], edx
    L0002: ret

C.Call(NonSealedType)
    L0000: mov rcx, rdx
    L0003: mov rax, [rdx]
    L0006: mov rax, [rax+0x40]
    L000a: mov rax, [rax+0x20]
    L000e: jmp rax
  1. is/as type checks for the type can be done more efficiently, as it only needs to compare the type itself rather than account for a potential hierarchy.
public class C {
    public bool IsSealed(Object o) => o is SealedType;
    public bool IsNotSealed(Object o) => o is NonSealedType;
}

internal class NonSealedType { }
internal sealed class SealedType { }

results in:

C.IsSealed(System.Object)
    L0000: test rdx, rdx
    L0003: je short L0016
    L0005: mov rax, 0x7ff7ab9ad180
    L000f: cmp [rdx], rax
    L0012: je short L0016
    L0014: xor edx, edx
    L0016: test rdx, rdx
    L0019: setne al
    L001c: movzx eax, al
    L001f: ret

C.IsNotSealed(System.Object)
    L0000: sub rsp, 0x28
    L0004: mov rcx, 0x7ff7ab9ad048
    L000e: call System.Runtime.CompilerServices.CastHelpers.IsInstanceOfClass(Void*, System.Object)
    L0013: test rax, rax
    L0016: setne al
    L0019: movzx eax, al
    L001c: add rsp, 0x28
    L0020: ret
  1. Arrays of that type don’t need covariance checks every time an element is stored into it.
public class C {
    internal void StoreSealed(SealedType[] arr, SealedType item) => arr[0] = item;
    internal void StoreNonSealed(NonSealedType[] arr, NonSealedType item) => arr[0] = item;
}

internal class NonSealedType { }
internal sealed class SealedType { }

results in:

C.StoreSealed(SealedType[], SealedType)
    L0000: sub rsp, 0x28
    L0004: cmp dword ptr [rdx+8], 0
    L0008: jbe short L001c
    L000a: lea rcx, [rdx+0x10]
    L000e: mov rdx, r8
    L0011: call 0x00007ff801db9f80
    L0016: nop
    L0017: add rsp, 0x28
    L001b: ret
    L001c: call 0x00007ff801f0bc70
    L0021: int3

C.StoreNonSealed(NonSealedType[], NonSealedType)
    L0000: sub rsp, 0x28
    L0004: mov rcx, rdx
    L0007: xor edx, edx
    L0009: call System.Runtime.CompilerServices.CastHelpers.StelemRef(System.Array, Int32, System.Object)
    L000e: nop
    L000f: add rsp, 0x28
    L0013: ret
  1. Creating spans of that type don’t need to validate the actual type of the array matches the specified generic type.
using System;
public class C {
    internal Span<SealedType> CreateSealed(SealedType[] arr) => arr;
    internal Span<NonSealedType> CreateNonSealedType(NonSealedType[] arr) => arr;
}

internal class NonSealedType { }
internal sealed class SealedType { }

results in:

C.CreateSealed(SealedType[])
    L0000: test r8, r8
    L0003: jne short L000b
    L0005: xor eax, eax
    L0007: xor ecx, ecx
    L0009: jmp short L0013
    L000b: lea rax, [r8+0x10]
    L000f: mov ecx, [r8+8]
    L0013: mov [rdx], rax
    L0016: mov [rdx+8], ecx
    L0019: mov rax, rdx
    L001c: ret

C.CreateNonSealedType(NonSealedType[])
    L0000: sub rsp, 0x28
    L0004: test r8, r8
    L0007: jne short L000f
    L0009: xor eax, eax
    L000b: xor ecx, ecx
    L000d: jmp short L0026
    L000f: mov rax, 0x7ff7aba4d870
    L0019: cmp [r8], rax
    L001c: jne short L0034
    L001e: lea rax, [r8+0x10]
    L0022: mov ecx, [r8+8]
    L0026: mov [rdx], rax
    L0029: mov [rdx+8], ecx
    L002c: mov rax, rdx
    L002f: add rsp, 0x28
    L0033: ret
    L0034: call System.ThrowHelper.ThrowArrayTypeMismatchException()
    L0039: int3
  1. Probably more both I’ve missed and that will emerge in the future.

We should add an analyzer, at either hidden or info level but that we’d look to turn on as a warning in dotnet/runtime, that flags:

  • Internal and private non-static, non-abstract, non-sealed classes that
  • Don’t have any derived types in its containing assembly
  • Which also doesn't have InternalsVisibleTo on it

and flag that they should be sealed. A fixer would seal the type. We could also make it configurable on the visibility, in case someone wanted to e.g. also opt-in public types (we wouldn't/couldn't in dotnet/runtime). We could also optionally factor in whether the type declares any new virtual methods, a protected ctor, or anything else that suggests the type is intended for derivation... upon detecting such things, we could either choose not to warn, or we could warn with a different diagnostic id.

If a developer working in the library ever wants to derive from such a type, they can remove the sealed when they add the derivation.

Activity

  1. added
    code-analyzer
    code-fixer
    api-ready-for-review
    on Mar 20, 2021
  2. added this to the 6.0.0 milestone on Mar 20, 2021
  3. ghost added
    area-CodeGen-coreclr
    on Mar 20, 2021
  4. ghost added
    untriaged
    on Mar 20, 2021
  5. added and removed
    area-CodeGen-coreclr
    on Mar 20, 2021
  6. danmoseley commented on Mar 20, 2021

    @danmoseley
    Contributor

    Can the JIT not perform a similar thought process?

  7. stephentoub commented on Mar 20, 2021

    @stephentoub
    MemberAuthor

    Can the JIT not perform a similar thought process?

    It's the JIT that's doing these aforementioned optimizations based on the type being sealed, but the JIT today can't assume that non-sealed types won't ever have derived types, e.g. if a derived type were to be reflection emitted.

  8. jkotas commented on Mar 21, 2021

    @jkotas
    Member

    Can the JIT not perform a similar thought process?

    Full AOT that can do global analysis of all code that will ever run in the process can do this optimization.

    JIT can do this optimization speculatively by assuming that the type is sealed, and undoing/rejiting all code that depends on this assumption when it is proven false. We have stayed away from speculative optimizitions like this so far. We have actually tried to build a similar speculative optimization for dictionaries of shared generic types, but we ended up rolling it back because it was hard to stabilize and because it had questionable performance characteristics.

  9. KalleOlaviNiemitalo commented on Mar 21, 2021

    @KalleOlaviNiemitalo

    Sealing a type might cause warning CS0628 or CA1047 if the type has protected members.

    If the type is being sealed to help the JIT compiler, not for design reasons, then the developer might want to keep protected members protected so that the type can be easily unsealed again if a derived class is added.

    If there is going to be a code fix that seals types, then perhaps it could also suppress those warnings.

  10. huoyaoyuan commented on Mar 21, 2021

    @huoyaoyuan
    Member

    Which also doesn't have InternalsVisibleTo on it

    It's quite common for a lib project to have InternalsVisibleTo for its corresponding test project.

  11. stephentoub commented on Mar 21, 2021

    @stephentoub
    MemberAuthor

    It's quite common for a lib project to have InternalsVisibleTo for its corresponding test project.

    Various optimizations are disabled by InternalsVisibleTo, e.g. the linker can't remove unused internals when building in a library marked InternalsVisibleTo. I'm fine with that being a limitation for this analyzer, as it is for other analyzers, like CA1812 (avoid uninstantiated internal classes).

  12. stephentoub commented on Mar 21, 2021

    @stephentoub
    MemberAuthor

    Sealing a type might cause warning CS0628 or CA1047 if the type has protected members.

    Yes, that's why I wrote "We could also optionally factor in whether the type declares any new virtual methods, a protected ctor, or anything else that suggests the type is intended for derivation... upon detecting such things, we could either choose not to warn, or we could warn with a different diagnostic id."

  13. 21 remaining items

  14. removed
    blocking
    on Apr 15, 2021
  15. geeknoid commented on Apr 26, 2021

    @geeknoid
    Member

    I have an implementation of the basic analyzer with tests here: https://github.com/geeknoid/UnsealedAnalyzer which I developed for our project. It could give a head-start to someone working on this issue. It doesn't support all the features requested here, but it does cover the essentials.

  16. NewellClark commented on May 22, 2021

    @NewellClark
    Contributor

    I would like to be assigned to this.

  17. modified the milestones: 6.0.0, 7.0.0 on Aug 11, 2021
  18. Youssef1313 commented on Oct 15, 2021

    @Youssef1313
    Member

    @stephentoub Does it make sense to extend this to public types where the base type doesn't have any public constructors?

  19. stephentoub commented on Oct 25, 2021

    @stephentoub
    MemberAuthor

    Does it make sense to extend this to public types where the base type doesn't have any public constructors?

    If it doesn't have any public, protected, or protected internal constructors, then we could also factor it in.

  20. added
    in-pr
    on Nov 23, 2021
  21. askazakov commented on Jan 25, 2022

    @askazakov

    @stephentoub I'm sorry I've not catch is it https://rules.sonarsource.com/csharp/RSPEC-3260 about the same issue? Did I miss something important?

  22. stephentoub commented on Jan 25, 2022

    @stephentoub
    MemberAuthor

    @askazakov, that's in an unrelated static analysis library rather than the analyzers that ship as part of the .NET SDK, and at least from the description it's only about private rather than non-public, e.g. it doesn't seem to cover internal types (at least not from the short description you linked to).

  23. meziantou commented on Mar 21, 2022

    @meziantou
    Contributor

    I think the analyzer should exclude classes declared as [ComImport]/[CoClass] from the analysis as the fix may break the compilation:

    using System.Runtime.InteropServices;
    
    _ = (IFileSaveDialog)new FileSaveDialogRCW(); // If FileSaveDialogRCW is sealed: error CS0030: Cannot convert type 'FileSaveDialogRCW' to 'IFileSaveDialog'
    
    [ComImport]
    [Guid("C0B4E2F3-BA21-4773-8DBA-335EC946EB8B")]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [CoClass(typeof(FileSaveDialogRCW))]
    internal interface IFileSaveDialog
    {
    }
    
    [ComImport]
    [ClassInterface(ClassInterfaceType.None)]
    [Guid("C0B4E2F3-BA21-4773-8DBA-335EC946EB8B")]
    class FileSaveDialogRCW // 👈 sealed is not valid here because of `(IFileSaveDialog)new NativeFileSaveDialog()`
    {
    }
  24. ericstj commented on Mar 22, 2022

    @ericstj
    Member

    @meziantou -- it looks like this is currently under PR here dotnet/roslyn-analyzers#5594 Would you mind adding your feedback there?

  25. ghost locked as resolved and limited conversation to collaborators on May 17, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

api-approvedarea-Metacode-analyzercode-fixerin-pr

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions