Skip to content

[API Proposal]: MakeWeakTypeReference as trimming indicator #74307

Open

Description

@hez2010

Background and motivation

While we were working with trimming, we found that we often want to express "code only needed if a type is preserved", but currently we do not have such thing in C#.

For example, in XAML frameworks, we use URLs to locate resources. With source generator, the code of the resource locator which is generated by a source generator may consist with a method with plenty of if statements, for example:

// auto-generated by a source generator
object? LoadResource(string path)
{
    if (path == "ms-appx://MyAssembly/My/Fancy/XamlControl1Style") return XamlLoader.Load<XamlControl1Style>();
    if (path == "ms-appx://MyAssembly/Another/XamlControl2Style") return XamlLoader.Load<XamlControl2Style>();
    return null;
}

With this source generator approach, we can achieve trimming compatibility. However, this would result in all types referenced in LoadResource being preserved even they are not being actually used. In this case, we only want XamlControl1Style to be preserved if XamlControl1 is referenced in other pieces of code.

API Proposal

namespace System.Diagnostics.CodeAnalysis;

public class ControlFlow
{
    public static bool MakeWeakTypeReference<T>() => true;
}

API Usage

object? LoadResource(string path)
{
    if (ControlFlow.MakeWeakTypeReference<XamlControl1>())
        if (path == "ms-appx://MyAssembly/My/Fancy/XamlControl1Style")
            return XamlLoader.Load<XamlControl1Style>();
    if (ControlFlow.MakeWeakTypeReference<XamlControl2>())
        if (path == "ms-appx://MyAssembly/Another/XamlControl2Style")
            return XamlLoader.Load<XamlControl2Style>();
    return null;
}

It behaves as a no-op which always returns true, but if there are no other type references to XamlControl1, the whole block of the if statement can be safely trimmed, which produces code after trimming like below:

object? LoadResource(string path)
{
    if (path == "ms-appx://MyAssembly/Another/XamlControl2Style")
        return XamlLoader.Load<XamlControl2Style>();
    return null;
}

Therefore, all types related to XamlControl1 and XamlControl1Type can also be trimmed away.

This should also support and and or so that we can express multiple types as a single prerequisite:

if (ControlFlow.MakeWeakTypeReference<Foo>() && ControlFlow.MakeWeakTypeReference<Bar>())
{
    // only preserved if both Foo and Bar are referenced
}

if (ControlFlow.MakeWeakTypeReference<Foo>() || ControlFlow.MakeWeakTypeReference<Bar>())
{
    // only preserved if either Foo or Bar is referenced
}

// Bogus
if (!ControlFlow.MakeWeakTypeReference<Foo>())
{
    // no-op, can never reach because `!ControlFlow.MakeWeakTypeReference<Foo>()` is always false, maybe a warning should be emitted by the compiler or illink?
}

Alternative Designs

No response

Risks

No response

Activity

  1. added
    api-suggestion
    on Aug 21, 2022
  2. ghost added
    untriaged
    on Aug 21, 2022
  3. added
    linkable-framework
    on Aug 21, 2022
  4. teo-tsirpanis commented on Aug 21, 2022

    @teo-tsirpanis
    Contributor

    Interesting idea; the name does not sound right to me though.

  5. hez2010 commented on Aug 21, 2022

    @hez2010
    ContributorAuthor

    Interesting idea; the name does not sound right to me though.

    Yes. I did think about the name for a while but didn't conclude a fancy name :)

  6. MichalPetryka commented on Aug 21, 2022

    @MichalPetryka
    Contributor

    Maybe IsTypePresent<T>?

  7. teo-tsirpanis commented on Aug 21, 2022

    @teo-tsirpanis
    Contributor

    That's better, and with that name it fits more on Type.

  8. eerhardt commented on Aug 22, 2022

    @eerhardt
    Member

    See the following code, which we use in System.Text.Json to do this exact scenario:

    // This method takes an unannotated string which makes linker reflection analysis lose track of the type we are
    // looking for. This indirection allows the removal of the type if it is not used in the calling application.
    [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2057:TypeGetType",
    Justification = "This method exists to allow for 'weak references' to the Stack and Queue types. If those types are used in the app, " +
    "they will be preserved by the app and Type.GetType will return them. If those types are not used in the app, we don't want to preserve them here.")]
    private static Type? GetTypeIfExists(string name) => Type.GetType(name, false);

  9. jkoritzinsky commented on Aug 22, 2022

    @jkoritzinsky
    Member

    @eerhardt that's really clever and I think a good example for where an API like this could be useful. I think being able to have a well-known API that would enable this to work while using generics or strongly-typed System.Type objects instead of having to round-trip through type name parsing would be quite useful and likely more maintainable than the existing mechanism you shared.

  10. MichalPetryka commented on Aug 22, 2022

    @MichalPetryka
    Contributor

    @eerhardt that's really clever and I think a good example for where an API like this could be useful. I think being able to have a well-known API that would enable this to work while using generics or strongly-typed System.Type objects instead of having to round-trip through type name parsing would be quite useful and likely more maintainable than the existing mechanism you shared.

    Additionally, it'd be more AOT safe.

  11. teo-tsirpanis commented on Aug 22, 2022

    @teo-tsirpanis
    Contributor
    namespace System;
    
    public abstract partial class Type
    {
        public static Type? GetTypeIfExists<T>() => typeof(T); // would be replaced with null by the trimmer if the type does not exist.
    }
  12. 5 remaining items

  13. kekekeks commented on Aug 24, 2022

    @kekekeks

    The problem with XAML styles is that they are completely separate from the control itself. Control does not and should not know anything about its styles, they are essentially user-defined and can be switched to a separate set of styles at runtime during the theme switch.
    Just like in WPF, in Avalonia styles are defined in a separate assembly (in case of Avalonia they come in separate nuget packages) and can be replaced for the entire app or a particular control subtree with another set of styles that come from a 3rd party package.

  14. kekekeks commented on Aug 26, 2022

    @kekekeks

    Another use case:

    My COM interop bindings generate COM interfaces as normal .NET interfaces.

    e. g.

    [uuid(ED7F3339-8EB4-4912-9D6F-EC4CDD094164})]
    interface IFoo : IUnknown
    {
    	void Bar();
    }
    

    becomes

    // IUnknown is defined as a marker interface on top of IDisposable
    interface IFoo : IUnknown
    {
        void Bar();
    }

    Interop is handled by separate generated classes __MicroComIFooProxy (implements the managed interface and forwards calls to native function pointers) and __MicroComIFooVTable (builds a CCW vtable).

    Both are registered by the module initializer. I'd like to be able to trim unneeded interop types when the interface isn't used.

  15. jkotas commented on Aug 26, 2022

    @jkotas
    Member

    Interop is handled by separate generated classes __MicroComIFooProxy (implements the managed interface and forwards calls to native function pointers) and __MicroComIFooVTable (builds a CCW vtable).

    CsWinRT solved this problem by linking the interop helper types via custom attributes: microsoft/CsWinRT#1224

  16. kekekeks commented on Aug 26, 2022

    @kekekeks

    I believe such custom attributes require reflection access. MicroCom aims to work with IlcDisableReflection=True

  17. teo-tsirpanis commented on Aug 26, 2022

    @teo-tsirpanis
    Contributor

    No, the attributes would be accessed at the time of the source generation, not at runtime.

  18. kekekeks commented on Aug 26, 2022

    @kekekeks

    type.GetCustomAttribute looks like run-time reflection to me: https://github.com/microsoft/CsWinRT/pull/1224/files#diff-2c2d5b5c93b2d4df6db3e983e3ba3126c9de5efa3648d9987c499904a3ea99b2R26-R54
    This code doesn't seem like it would run with IlcDisableReflection too

                    var helper = $"ABI.{fullTypeName}";
                    return type.Assembly.GetType(helper) ?? Type.GetType(helper);
  19. jkotas commented on Aug 27, 2022

    @jkotas
    Member

    type.GetCustomAttribute looks like run-time reflection

    Yes, custom attributes are accessed via reflection. The key advantage is that the helper type associations via custom attribute can be statically analyzed for correctness and the solution does not have concerns shared by @vitek-karas and @MichalStrehovsky above.

    var helper = $"ABI.{fullTypeName}";
    return type.Assembly.GetType(helper) ?? Type.GetType(helper);

    This is temporary fallback path that should go away eventually.

  20. MichalStrehovsky commented on Aug 29, 2022

    @MichalStrehovsky
    Member

    I believe such custom attributes require reflection access. MicroCom aims to work with IlcDisableReflection=True

    Working with IlcDisableReflection is a noble goal but I don't think the base class libraries will ever be in a position where they work with IlcDisableReflection=true. They likely won't even work in the more usable future version of it: #67193 (comment). Trimmable reflection is not a problem and would be a good solution for this.

    IlcDisableReflection is a tech demo that was introduced before we had things like IlcTrimMetadata=true (which is now the default). With metadata trimming, I don't believe you'll see meaningful size differences with/without reflection for apps that are bigger than a console hello world. IlcDisableReflection produces meaningful savings for hello-world-sized apps because it allows removing the whole reflection stack, but that's a fixed ~1MB cost that is not worth it for most. We'll likely do work that will indirectly make this cost smaller over time. The reflection stack in NativeAOT is a bit overengineered.

    If you still see a meaningful difference for Avalonia-sized apps, please add <ItemGroup><IlcArg Include="--make-repro-path:c:\some\path\where\a\zip\can\be\created" /></ItemGroup> to the project and share the resulting ZIP with me (in a new issue) - it's likely a bug - IlcDisableReflection has been useful in finding those in the past.

  21. vitek-karas commented on Aug 31, 2022

    @vitek-karas
    Member

    We didn't document branch removal rules on purpose. We only test them on the runtime repo. We had to #40539 in the runtime repo to fit the envelope of the optimization in the past. This would make relying on the shape of the optimization part of a public API surface (the API by itself has no legitimate use outside of this pattern). There would be no feedback if constprop is not able to kick in and doesn't eliminate a branch that the user expects. This is hard to debug for end users.

    I view this as two separate things:

    • Correctness/consistency - the app behaves the same with/without trimming. The idea of branch removal doesn't violate this in any way. (unlike the proposed API which does)
    • Size optimization (trimming) - currently we don't describe nor make any promises with regard to trimming specific pieces of the app. The tools (trimmer, NativeAOT, ...) may decide to keep code/metadata around without any specific documented reason. This leads to us not making any size guarantees. The branch removal proposed above doesn't work today, but if it enabled it, it would simple improve size for some apps, but should have no other impact.

    That said, it would be nice to have some agreed upon way especially for libraries to verify that they can be successfully trimmed to a certain degree - and to enable detection or regressions and such. But that's sort of outside the scope of this issue.

  22. removed
    untriaged
    on Sep 6, 2022
  23. added this to the Future milestone on Sep 6, 2022
  24. dotnet-policy-service commented on Apr 15, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @agocke, @elinor-fung
    See info in area-owners.md if you want to be subscribed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionarea-AssemblyLoaderlinkable-framework

    Type

    No type

    Projects

    • Status
      No status

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions