Skip to content

Commit

Permalink
Dead code elimination for if (typeof(T).IsValueType) (#97080)
Browse files Browse the repository at this point in the history
@stephentoub found out that for following code:

```csharp
using System.Buffers;

Foo<Bar>();

static T[] Foo<T>()
{
    if (typeof(T).IsValueType)
    {
        return ArrayPool<T>.Shared.Rent(42);
    }
    return null!;
}

class Bar {}
```

We end up generating `ArrayPool`s of `Bar` even though it's obviously never reachable. The problem is architectural:

* We run a whole program analysis phase that tries to figure out things like generic dictionary layouts so that later, in code generation phase, we can inline offsets into generic dictionaries into codegen.
* For the above code, whole program analysis decides that the dictionary layout of `Foo<__Canon>` needs a slot for `ArrayPool<!0>`.
* Codegen then optimizes out the `IsValueType` branch because `__Canon` is never a valuetype. But we already allocated the dictionary slot and will fill it out, even though it ends up unused due to the optimization.

We're going to run into issues like this until #83021 is addressed. Whole program analysis cannot currently assume a certain optimization happens because we don't know whether RyuJIT will do it. The only way we can "optimize" during whole program analysis is if we rewrite IL and give RyuJIT no saying in whether to do an optimization or not. Rewriting the IL is not great because it e.g. causes PGO data to not match. I don't like doing it, but there's nothing else we can do.

This change extends dead block elimination to understand `typeof(X).IsValueType`. If we recognize a branch is reachable under this condition, we evaluate whether this is true or false and replace the basic block with nops.
  • Loading branch information
MichalStrehovsky authored Jan 18, 2024
1 parent 957ab2f commit 77d643d
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 22 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -591,6 +591,13 @@ private bool TryGetConstantArgument(MethodIL methodIL, byte[] body, OpcodeFlags[
{
return true;
}
else if (method.IsIntrinsic && method.Name is "get_IsValueType"
&& method.OwningType is MetadataType mdt
&& mdt.Name == "Type" && mdt.Namespace == "System" && mdt.Module == mdt.Context.SystemModule
&& TryExpandTypeIsValueType(methodIL, body, flags, currentOffset, out constant))
{
return true;
}
else
{
constant = 0;
Expand Down Expand Up @@ -745,6 +752,40 @@ private string GetResourceStringForAccessor(EcmaMethod method)
return null;
}

private static bool TryExpandTypeIsValueType(MethodIL methodIL, byte[] body, OpcodeFlags[] flags, int offset, out int constant)
{
// We expect to see a sequence:
// ldtoken Foo
// call GetTypeFromHandle
// -> offset points here
constant = 0;
const int SequenceLength = 10;
if (offset < SequenceLength)
return false;

if ((flags[offset - SequenceLength] & OpcodeFlags.InstructionStart) == 0)
return false;

ILReader reader = new ILReader(body, offset - SequenceLength);

TypeDesc type = ReadLdToken(ref reader, methodIL, flags);
if (type == null)
return false;

if (!ReadGetTypeFromHandle(ref reader, methodIL, flags))
return false;

// Dataflow runs on top of uninstantiated IL and we can't answer some questions there.
// Unfortunately this means dataflow will still see code that the rest of the system
// might have optimized away. It should not be a problem in practice.
if (type.IsSignatureVariable)
return false;

constant = type.IsValueType ? 1 : 0;

return true;
}

private static bool TryExpandTypeEquality(MethodIL methodIL, byte[] body, OpcodeFlags[] flags, int offset, string op, out int constant)
{
// We expect to see a sequence:
Expand Down Expand Up @@ -793,37 +834,37 @@ private static bool TryExpandTypeEquality(MethodIL methodIL, byte[] body, Opcode
constant ^= 1;

return true;
}

static TypeDesc ReadLdToken(ref ILReader reader, MethodIL methodIL, OpcodeFlags[] flags)
{
ILOpcode opcode = reader.ReadILOpcode();
if (opcode != ILOpcode.ldtoken)
return null;
private static TypeDesc ReadLdToken(ref ILReader reader, MethodIL methodIL, OpcodeFlags[] flags)
{
ILOpcode opcode = reader.ReadILOpcode();
if (opcode != ILOpcode.ldtoken)
return null;

TypeDesc t = (TypeDesc)methodIL.GetObject(reader.ReadILToken());
TypeDesc t = (TypeDesc)methodIL.GetObject(reader.ReadILToken());

if ((flags[reader.Offset] & OpcodeFlags.BasicBlockStart) != 0)
return null;
if ((flags[reader.Offset] & OpcodeFlags.BasicBlockStart) != 0)
return null;

return t;
}
return t;
}

static bool ReadGetTypeFromHandle(ref ILReader reader, MethodIL methodIL, OpcodeFlags[] flags)
{
ILOpcode opcode = reader.ReadILOpcode();
if (opcode != ILOpcode.call)
return false;
private static bool ReadGetTypeFromHandle(ref ILReader reader, MethodIL methodIL, OpcodeFlags[] flags)
{
ILOpcode opcode = reader.ReadILOpcode();
if (opcode != ILOpcode.call)
return false;

MethodDesc method = (MethodDesc)methodIL.GetObject(reader.ReadILToken());
MethodDesc method = (MethodDesc)methodIL.GetObject(reader.ReadILToken());

if (!method.IsIntrinsic || method.Name != "GetTypeFromHandle")
return false;
if (!method.IsIntrinsic || method.Name != "GetTypeFromHandle")
return false;

if ((flags[reader.Offset] & OpcodeFlags.BasicBlockStart) != 0)
return false;
if ((flags[reader.Offset] & OpcodeFlags.BasicBlockStart) != 0)
return false;

return true;
}
return true;
}

private sealed class SubstitutedMethodIL : MethodIL
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ public static int Run()
TestArrayElementTypeOperations.Run();
TestStaticVirtualMethodOptimizations.Run();
TestTypeEquals.Run();
TestTypeIsValueType.Run();
TestBranchesInGenericCodeRemoval.Run();
TestUnmodifiableStaticFieldOptimization.Run();
TestUnmodifiableInstanceFieldOptimization.Run();
Expand Down Expand Up @@ -355,6 +356,31 @@ public static void Run()
}
}

class TestTypeIsValueType
{
class Never { }

class Ever { }

static void Generic<T>()
{
if (typeof(T).IsValueType)
{
Activator.CreateInstance(typeof(Never));
}

Activator.CreateInstance(typeof(Ever));
}

public static void Run()
{
Generic<object>();

ThrowIfPresent(typeof(TestTypeIsValueType), nameof(Never));
ThrowIfNotPresent(typeof(TestTypeIsValueType), nameof(Ever));
}
}

class TestBranchesInGenericCodeRemoval
{
class ClassWithUnusedVirtual
Expand Down

0 comments on commit 77d643d

Please sign in to comment.