Skip to content

better LLVM struct layout for tagged unions (beating the C equivalent!) #2166

@andrewrk

Description

@andrewrk

To see the LLVM IR, use clang -nostdlib -S -g -emit-llvm test.c:

#include <inttypes.h>

// %struct.Foo = type { %union.anon, i8 }
// %union.anon = type { i64, [8 x i8] }
// ABI Size: 24

struct Foo {
    union {
        uint64_t a;
        uint8_t b[9];
    } bar;
    uint8_t c;
};

int main(void) {
    struct Foo foo;
    return 0;
}

For this tagged union, the C version will have ABI size = 24. However, when written in zig:

// %struct.Foo = type { i64, [1 x i8], i8 }
// ABI Size: 16
const Foo = union(enum) {
    a: u64,
    b: [9]u8,
};

A savings of 8 bytes for this case.

This will require implementing the above LLVM type. Currently, Zig matches the equivalent C code.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions