dotnet / corert

This repo contains CoreRT, an experimental .NET Core runtime optimized for AOT (ahead of time compilation) scenarios, with the accompanying compiler toolchain.
http://dot.net
MIT License
2.91k stars 510 forks source link

[Interpreter] Static constructors and field access #8351

Closed tonerdo closed 4 years ago

tonerdo commented 4 years ago

This PR adds support for instance and static fields on a reference type. It interprets the following opcodes:

As a consequence of adding static field support, I also added support for interpreting static constructors on dynamically loaded types. The following scenario is now supported:

class Class1
{
    public string Field1;
    public int Field2;
    public float Field3;

    public static string StaticField1;
    public static int StaticField2;
    public static float StaticField3;

    [ThreadStatic]
    public static int ThreadStaticField1;

    static Class1()
    {
        StaticField1 = "statically nice!";
        StaticField2 = 10;
        StaticField3 = 3.56f;
        ThreadStaticField1 = 56;
    }
}

.....

public static void DoFields()
{
    Class1 class1 = new Class1();
    class1.Field1 = "nice";
    class1.Field2 = 23;
    class1.Field3 = 2.5f;

    Console.WriteLine(class1.Field1);
    Console.WriteLine(class1.Field2);
    Console.WriteLine(class1.Field3);
}

public static void DoStaticFields()
{
    Console.WriteLine(Class1.StaticField1);
    Console.WriteLine(String.Empty);
    Console.WriteLine(Class1.StaticField2);
    Console.WriteLine(Class1.StaticField3);
    Console.WriteLine(Class1.ThreadStaticField1);
}

The interpreter will happily load instance and static fields on both dynamically loaded types and types compiled into the native executable, while ensuring that static constructors have been run in both cases.