0031. Unions use a tagged C union
- Status: Accepted
- Date: 2026-10-30
- Plan: M4.3 (experiment
union-layout, CP-4.1) - Review: Backend and performance
- Owner review: Maintainer delegated M4 syntax and layout choices on 2026-10-30; recorded by the orchestrating agent on measured evidence.
Context
M4.3 lowers enum values to C. Two layouts were
candidates (EXPERIMENTS.md, CP-4.1 union-layout):
A, a uint32_t tag plus a C
union of one payload struct per variant;
B, a uint32_t tag plus every
variant's payload struct side by side with no overlap. B's
hypothesis was that it matches A's speed and avoids any union-read
warning. Values are passed by value (no pointers before M5), so
sizeof is paid on every copy, call and return.
The experiment generated equivalent C for both layouts and
timed it with gcc -std=c11 -Wall -Wextra -O2, 7 runs
each (median and min), at default alignment and with
-falign-functions=32. Outputs were byte-identical
between layouts; neither layout produced any gcc warning.
| Workload | Align | Layout | sizeof | Median s | Min s |
|---|---|---|---|---|---|
| small (3 variants, ≤3 fields) | default | A | 32 | 0.632 | 0.552 |
| small | default | B | 56 | 0.493 | 0.343 |
| small | align 32 | A | 32 | 0.568 | 0.522 |
| small | align 32 | B | 56 | 0.469 | 0.285 |
| wide (8 variants, ≤6 fields) | default | A | 56 | 0.978 | 0.960 |
| wide | default | B | 200 | 2.964 | 2.842 |
| wide | align 32 | A | 56 | 1.033 | 0.961 |
| wide | align 32 | B | 200 | 2.929 | 2.872 |
| pipeline (4 variants, array round trip) | default | A | 32 | 0.788 | 0.771 |
| pipeline | default | B | 56 | 1.308 | 1.255 |
Decision
Keep layout A: a uint32_t tag and a C
union of per-variant payload structs, as M4.3 emits
it. The plan's rule was to adopt B only if it was at least 10%
faster in 2 of 3 workloads under both alignments with
sizeof at most 2×. B won only the smallest workload,
lost wide by 3.0× and pipeline by 1.7×,
and grew wide's sizeof 3.6×. The
experiment is closed.
Alternatives considered
- B, one struct per variant without overlap. Simpler to read and never reads an inactive union member, but its size is the sum of all payloads, so copies grow with the number of variants. A has no union-read warnings under gcc either, so B's main advantage did not materialise.
- Boxed payloads. Needs heap allocation and ownership rules that M5 has not defined yet.
Consequences
sizeofof a union is the tag plus its largest payload, so wide unions stay cheap to copy.- cgen must only read the payload member selected by the tag;
the
Switchlowering (ADR-0023) guarantees that. - Revisit if M5's memory model introduces pointers to payloads, or if large single variants dominate copies (then box that variant instead).
- Raw data and generator:
/workspace/shared/harness/exp-union/on the build box, summarised here.