Skip to content

ILLink does not retain external TypeMap entries for castclass targets #136568

Description

@simonrozsival

Description

ILLink does not retain an external TypeMapAttribute entry when its trim target is used only by a reachable reference-type castclass instruction. The same program works correctly with NativeAOT/ILC.

This was discovered while investigating dotnet/android#13286, but it reproduces in a standalone net11.0 console application without Android.

Minimal reproduction

TypeMapCastRepro.csproj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net11.0</TargetFramework>
    <PublishTrimmed>true</PublishTrimmed>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
</Project>

Program.cs:

using System.Runtime.InteropServices;

[assembly: TypeMap<Repro.TypeMapGroup> (
    "cast-target",
    typeof (Repro.MappedType),
    typeof (Repro.CastTarget))]

namespace Repro;

static class Program
{
    static int Main (string [] args)
    {
        _ = (CastTarget?) (args.Length == 0 ? null : new object ());

        var typeMap = TypeMapping.GetOrCreateExternalTypeMapping<TypeMapGroup> ();
        if (!typeMap.TryGetValue ("cast-target", out Type? mappedType)) {
            Console.WriteLine ("MISSING: castclass did not retain the external type-map entry.");
            return 1;
        }

        Console.WriteLine ($"PRESENT: castclass retained {mappedType.FullName}.");
        return mappedType.FullName == "Repro.MappedType" ? 0 : 2;
    }
}

sealed class TypeMapGroup;
sealed class CastTarget;
sealed class MappedType;

The command-line argument check prevents the cast operand from being statically known as null. With no arguments, the cast safely receives null; passing any argument intentionally supplies an incompatible object and proves that the castclass remains.

CoreCLR/ILLink result

Using .NET SDK 11.0.100-rc.2.26504.105 on osx-arm64:

dotnet publish -c Release -r osx-arm64 --self-contained true \
  -p:PublishAot=false -o out/coreclr
./out/coreclr/TypeMapCastRepro

Output and exit code:

MISSING: castclass did not retain the external type-map entry.
exit code: 1

Inspection of the linked application confirms:

  • Main still contains castclass Repro.CastTarget.
  • Repro.CastTarget remains.
  • Repro.MappedType is removed.
  • The assembly-level TypeMapAttribute entry is removed.

NativeAOT/ILC result

dotnet publish -c Release -r osx-arm64 --self-contained true \
  -p:PublishAot=true -o out/nativeaot
./out/nativeaot/TypeMapCastRepro

Output and exit code:

PRESENT: castclass retained Repro.MappedType.
exit code: 0

Expected behavior

The External Type Map specification explicitly includes both isinst and castclass as operations that retain an entry whose trim target is the instruction operand:

https://github.com/dotnet/runtime/blob/523349107aca82ae8fa2feaaca5a1767619f1111/docs/design/features/typemap.md#external-type-map

The CoreCLR/ILLink result should match NativeAOT/ILC and retain the cast-target entry and MappedType.

Suspected root cause

TypeMapHandler initially stores the entry in _unmarkedExternalTypeMapEntries, keyed by CastTarget. It must later receive ProcessType(CastTarget) to mark the attribute and its target.

MarkStep.MarkInstruction has explicit TypeMap notification only for Code.Isinst:

case OperandType.InlineType:
var operand = (TypeReference)instruction.Operand;
requiresReflectionMethodBodyScanner |= InstructionRequiresReflectionMethodBodyScannerForTypeAccess(instruction);
switch (instruction.OpCode.Code)
{
case Code.Newarr:
if (Context.TryResolve(operand) is TypeDefinition typeDefinition)
{
MarkRelevantToVariantCasting(typeDefinition);
}
break;
case Code.Isinst:
if (operand is TypeSpecification || operand is GenericParameter)
break;
if (!Context.CanApplyOptimization(CodeOptimizations.UnusedTypeChecks, method.DeclaringType.Module.Assembly))
break;
TypeDefinition? type = Context.Resolve(operand);
if (type == null)
return;
if (type.IsInterface)
break;
_typeMapHandler.ProcessType(type);
if (!Annotations.IsInstantiated(type))
{
_pending_isinst_instr.Add((type, method.Body, instruction));
return;
}
break;
}
origin = new MessageOrigin(origin, instruction.Offset);
MarkType(operand, new DependencyInfo(DependencyKind.InstructionTypeRef, method), origin);
break;

case Code.Isinst:
    ...
    _typeMapHandler.ProcessType(type);

There is no Code.Castclass case. castclass falls through to ordinary MarkType(operand, ...), which preserves CastTarget but does not notify TypeMapHandler. The deferred external map entry therefore remains unmarked.

NativeAOT handles both instructions through the same ImportCasting path and creates the necessary type-symbol dependency:

private void ImportCasting(ILOpcode opcode, int token)
{
TypeDesc type = (TypeDesc)_methodIL.GetObject(token);
if (type.IsRuntimeDeterminedSubtype)
{
_dependencies.Add(GetGenericLookupHelper(ReadyToRunHelperId.TypeHandleForCasting, type), "IsInst/CastClass");
}
else
{
_dependencies.Add(_compilation.ComputeConstantLookup(ReadyToRunHelperId.TypeHandleForCasting, type), "IsInst/CastClass");
}

The ILLink hook was introduced in #116555. The implementation and test suite cover isinst and value-type unboxing, but there does not appear to be a reference-type castclass retention test.

A likely fix is to process direct castclass and isinst targets before entering the isinst-specific unused-type-check optimization. Simply sharing the existing body unchanged would be incorrect because it could add castclass instructions to _pending_isinst_instr, whose cleanup rewrites type checks to pop; ldnull.

The existing isinst notification is also currently conditional on the UnusedTypeChecks optimization being enabled and skips interfaces before notifying TypeMapHandler; both conditions appear narrower than the External Type Map specification.

Related issues

Activity

  1. added
    untriaged
    area-Tools-ILLink
    on Oct 28, 2026
  2. dotnet-policy-service commented on Oct 28, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @agocke, @dotnet/illink
    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

    area-Tools-ILLinkbuguntriaged

    Type

    No type

    Projects

    • Status
      No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions