Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Read behaviour for signed bitfields is inconsistent with Clang, MSVC and GCC #415

Closed
DaZombieKiller opened this issue Jan 23, 2023 · 1 comment · Fixed by #464
Closed

Comments

@DaZombieKiller
Copy link
Contributor

When generating an interop structure for the following type:

struct PackedVertex
{
    union
    {
        int i;
        struct
        {
            int x : 11;
            int y : 11;
            int z : 10;
        };
    };
};

ClangSharpPInvokeGenerator produces accessors like the following:

[NativeTypeName("int : 11")]
public int x
{
    get
    {
        return _bitfield & 0x7FF;
    }

    set
    {
        _bitfield = (_bitfield & ~0x7FF) | (value & 0x7FF);
    }
}

Which does not appear to handle the sign of each component properly.

Setting i to 0xFB3E7064 should produce 100, -50, -20 for x, y, z, but with the currently generated code, it produces 100, 1998, 1004. If the code for the getters are tweaked to match the assembly generated by Clang and MSVC, then the results are correct.

@tannergooding
Copy link
Member

This should be a simple fix. The general bitfield handling logic is in VisitBitfieldDecl here: https://github.com/dotnet/ClangSharp/blob/main/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.VisitDecl.cs#L2347

There is some upfront type checking and other handling and then the actual "code" emitted is handled a bit further down around here: https://github.com/dotnet/ClangSharp/blob/main/sources/ClangSharp.PInvokeGenerator/PInvokeGenerator.VisitDecl.cs#L2693

It's worth noting that the behavior of int x : 11 in C is undefined. It could be signed int or unsigned int. In C++ it is well defined and treated as signed int

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
2 participants