/* =============================================================================
 * 01_struct_layout.c  --  where the compiler puts each field, and why
 * =============================================================================
 *
 * [Questions this demo answers]
 *   - What are the offsets and the size of the slides' structs S1 ... S5?
 *   - Can we PREDICT them with the two alignment rules from the slides?
 *       (1) a field of alignment K starts at a multiple of K;
 *       (2) the struct's alignment is the largest field alignment, and its
 *           size is rounded up to a multiple of it.
 *   - How much space does reordering the fields save?
 *   - What does an array of structs look like, and where does a union put its
 *     fields?
 *
 * [How to build & run]
 *   make && ./build/01_struct_layout          (native)
 *          ./build/01_struct_layout_x86      (x86-64 under Rosetta 2)
 *
 * [How to read the output]
 *   For every struct, a row per field: the offset the COMPILER chose
 *   (offsetof), the offset the RULES predict, and the padding inserted
 *   before it. Then the total size, compiler vs rules, and the size after
 *   sorting the fields by decreasing alignment. Every line should say "ok".
 *
 * [Systems link / CS:APP 3.9.3]
 *   Alignment is a hardware convenience made into an ABI rule: a value that
 *   never straddles an 8-byte boundary can be fetched in one access and
 *   never spans two cache lines or two pages. x86-64 tolerates misaligned
 *   data (slowly); some machines trap on it. The rules make every compiler
 *   on a platform agree on struct layouts, so binaries can share them.
 * -------------------------------------------------------------------------- */

#include <stdalign.h>
#include <stddef.h>
#include <stdio.h>
#include "structs.h"

/* One field as the layout rules see it: a size and an alignment. */
struct field {
    const char *name;
    size_t size;
    size_t align;
    size_t actual_offset;      /* offsetof() from the compiler */
};

/*
 * [Idea] Lay fields out by the two rules, in the given order.
 * [Parameters] f, n -- the fields; offsets -- receives the predicted offsets.
 * [Returns] the predicted struct size (rounded up to the struct alignment).
 * [Edge cases] an empty struct is not legal C; n >= 1 here.
 */
static size_t layout(const struct field *f, int n, size_t *offsets, size_t *struct_align)
{
    size_t pos = 0, k = 1;
    for (int j = 0; j < n; j++) {
        pos = (pos + f[j].align - 1) / f[j].align * f[j].align;     /* rule 1 */
        offsets[j] = pos;
        pos += f[j].size;
        if (f[j].align > k) k = f[j].align;
    }
    *struct_align = k;
    return (pos + k - 1) / k * k;                                 /* rule 2 */
}

/* [Idea] Size of the same fields sorted by decreasing alignment (insertion
 *   sort on a copy) -- the slides' "put large data types first". */
static size_t sorted_size(const struct field *f, int n)
{
    struct field g[8];
    size_t off[8], k;
    for (int j = 0; j < n; j++) {
        g[j] = f[j];
        for (int m = j; m > 0 && g[m].align > g[m - 1].align; m--) {
            struct field t = g[m]; g[m] = g[m - 1]; g[m - 1] = t;
        }
    }
    return layout(g, n, off, &k);
}

static int show(const char *decl, const struct field *f, int n, size_t actual_size,
                size_t actual_align)
{
    size_t off[8], k;
    size_t size = layout(f, n, off, &k);
    int ok = (size == actual_size) && (k == actual_align);
    printf("  %s\n", decl);
    printf("    %-6s %-5s %-6s %-10s %-10s %s\n", "field", "size", "align", "offsetof", "rules say",
           "padding before");
    size_t end = 0;
    for (int j = 0; j < n; j++) {
        printf("    %-6s %-5zu %-6zu %-10zu %-10zu %zu%s\n", f[j].name, f[j].size, f[j].align,
               f[j].actual_offset, off[j], off[j] - end,
               off[j] == f[j].actual_offset ? "" : "   <-- MISMATCH");
        ok &= off[j] == f[j].actual_offset;
        end = off[j] + f[j].size;
    }
    printf("    sizeof = %zu (rules: %zu; %zu bytes of padding at the end), alignment K = %zu; "
           "sorted by alignment: %zu   %s\n\n",
           actual_size, size, size - end, actual_align, sorted_size(f, n), ok ? "ok" : "MISMATCH");
    return ok;
}

/* [C tip] F(T, m) builds one `struct field` entry for member m of type T:
 * sizeof and _Alignof of the member, and offsetof from the compiler. */
#define F(T, m) {#m, sizeof(((T *)0)->m), alignof(__typeof__(((T *)0)->m)), offsetof(T, m)}

int main(void)
{
#if defined(__x86_64__)
    const char *arch = "x86-64";
#elif defined(__aarch64__)
    const char *arch = "arm64";
#else
    const char *arch = "unknown";
#endif
    int ok = 0, total = 0;
    printf("=== Demo 01: structure layout and alignment (%s) ===\n\n", arch);

    printf("PART A: primitive alignments on this machine (the slides' table)\n");
    printf("  char %zu   short %zu   int %zu   float %zu   long %zu   double %zu   pointer %zu\n\n",
           alignof(char), alignof(short), alignof(int), alignof(float), alignof(long),
           alignof(double), alignof(void *));

    printf("PART B: the slides' structs, compiler vs the two rules\n");
    struct field rec[] = {F(struct rec, a), F(struct rec, i), F(struct rec, next)};
    struct field s1[] = {F(struct S1, c), F(struct S1, i), F(struct S1, v)};
    struct field s2[] = {F(struct S2, v), F(struct S2, i), F(struct S2, c)};
    struct field s3[] = {F(struct S3, i), F(struct S3, v), F(struct S3, j)};
    struct field s4[] = {F(struct S4, c), F(struct S4, i), F(struct S4, d)};
    struct field s5[] = {F(struct S5, i), F(struct S5, c), F(struct S5, d)};
    total++; ok += show("struct rec { int a[4]; size_t i; struct rec *next; }", rec, 3,
                        sizeof(struct rec), alignof(struct rec));
    total++; ok += show("struct S1 { char c; int i[2]; double v; }", s1, 3,
                        sizeof(struct S1), alignof(struct S1));
    total++; ok += show("struct S2 { long v; int i[2]; char c; }", s2, 3,
                        sizeof(struct S2), alignof(struct S2));
    total++; ok += show("struct S3 { short i; float v; short j; }", s3, 3,
                        sizeof(struct S3), alignof(struct S3));
    total++; ok += show("struct S4 { char c; int i; char d; }", s4, 3,
                        sizeof(struct S4), alignof(struct S4));
    total++; ok += show("struct S5 { int i; char c; char d; }", s5, 3,
                        sizeof(struct S5), alignof(struct S5));
    printf("  %d of %d structs: the rules predict the compiler exactly.\n\n", ok, total);

    printf("PART C: an array of structs -- struct S2 a[3]\n");
    struct S2 arr[3];
    for (int j = 0; j < 3; j++)
        printf("  &a[%d] = a + %-3ld  &a[%d].c = a + %ld\n", j, (long)((char *)&arr[j] - (char *)arr),
               j, (long)((char *)&arr[j].c - (char *)arr));
    printf("  The 7 bytes of padding at the END of S2 are what keep a[1].v and a[2].v\n"
           "  on multiples of 8: sizeof includes them, so a + 24*k stays aligned.\n\n");

    printf("PART D: union U1 { char c; int i[2]; long v; } vs struct with the same fields\n");
    printf("  union:  sizeof = %zu; offsets c %zu, i %zu, v %zu (all fields overlap)\n",
           sizeof(union U1), offsetof(union U1, c), offsetof(union U1, i), offsetof(union U1, v));
    struct SU { char c; int i[2]; long v; };
    printf("  struct: sizeof = %zu; offsets c %zu, i %zu, v %zu\n\n", sizeof(struct SU),
           offsetof(struct SU, c), offsetof(struct SU, i), offsetof(struct SU, v));

    printf("Observations:\n");
    printf("  * Two rules explain every layout: each field starts at a multiple of its\n"
           "    alignment, and the struct is padded to a multiple of its largest one.\n");
    printf("  * Fields stay in declaration order (C requires it); padding is the price.\n"
           "    Sorting by decreasing alignment minimizes it: S4 (12 bytes) has the same\n"
           "    fields as S5 (8 bytes).\n");
    printf("  * The same numbers come out on arm64 and x86-64: both follow LP64 rules\n"
           "    with natural alignment.\n");
    return ok == total ? 0 : 1;
}
