Keep a discarded method-group conversion out of the delegate cache

CachedDelegateInitializationWithField only fired when the instruction
after the caching `if` read the cache field exactly once. A discarded
conversion -- `_ = (Action<int>)M;` -- reads it zero times: Roslyn emits
the null check and the store, and nothing else. The transform bailed out,
so the `<>O` cache class and its `<0>__M` field survived into the output
under names no C# compiler will accept.

Zero usages is now handled: the `if` is replaced by the delegate
construction it guarded, which is what the source expressed, and the
caching disappears with the field. The rest of the method is checked for
loads of the same field first, since only then is this `if` the sole
initialization.

Closes #3965
This commit is contained in:
dualfroz committed 2026-09-19 11:14:31 +02:00
1 parent 80cf67e749
commit 167098573c
3 files changed
+50 -4

No files matched your search

@@ -37,7 +37,6 @@ namespace ICSharpCode.Decompiler.IL.Transforms
{
if (CachedDelegateInitializationWithField(inst))
{
block.Instructions.RemoveAt(i);
context.IndexOfFirstAlreadyTransformedInstruction = block.Instructions.Count;
continue;
}
@@ -95,13 +94,25 @@ namespace ICSharpCode.Decompiler.IL.Transforms
if (!DelegateConstruction.MatchDelegateConstruction(value.UnwrapConv(ConversionKind.Invalid) as NewObj, out _, out _, out _, true))
return false;
var nextInstruction = inst.Parent.Children.ElementAtOrDefault(inst.ChildIndex + 1);
if (nextInstruction == null)
return false;
var usages = nextInstruction.Descendants.Where(i => i.MatchLdsFld(field)).ToArray();
var usages = nextInstruction?.Descendants.Where(i => i.MatchLdsFld(field)).ToArray() ?? [];
if (usages.Length == 0)
{
// A discarded method-group conversion ("_ = (Action)M;") caches the
// delegate without ever reading the cache back. Keep the conversion,
// which still allocates, and drop the caching around it -- but only
// once the rest of the method is known not to read the field either.
if (context.Function.Descendants.Any(i => i != left && i.MatchLdsFld(field)))
return false;
context.Step("CachedDelegateInitializationWithField (unused)", inst);
inst.ReplaceWith(value);
context.EndStep(value);
return true;
}
if (usages.Length != 1)
return false;
context.Step("CachedDelegateInitializationWithField", inst);
usages[0].ReplaceWith(value);
((Block)inst.Parent).Instructions.RemoveAt(inst.ChildIndex);
context.EndStep(value);
return true;
}