Pitch: An opt-in warning for avoidable struct padding

Swift lays out stored properties in declaration order, so a poorly ordered struct silently wastes memory and bandwidth. Nothing in the toolchain tells you where that happens. This pitch proposes an off-by-default diagnostic group that answers one question: where do my struct layouts leave room for improvement?

Enable the group, build, and every struct whose stride a different order would shrink is reported together with the possible saving. The diagnostic changes no layout and suggests no order: the compiler points out the opportunity, the developer decides. Source order can carry intent, such as fields that are read together, so that decision belongs to the author. Intentional layouts are opted out per type through @diagnose and a written reason.

Motivation

The same three fields take 24 instead of 16 bytes per element (50 % more) when the large field is not first, and a bandwidth-bound loop pays that 1.5× directly. Measured with Swift 6.4 (-O, release build) on an Apple M4:

struct Bad {                 // stride 24
    var isActive: Bool
    var value: Int64
    var isVisible: Bool
}

struct Good {                // stride 16
    var value: Int64
    var isActive: Bool
    var isVisible: Bool
}
Type size stride Padding per element Sum of value, 2 M elements (p50 per element)
[Bad] 17 B 24 B 14 B 0.33 ns
[Good] 10 B 16 B 6 B 0.22 ns

The slowdown follows the stride ratio (24 / 16 = 1.5×; we measured 1.5–1.7× across runs) because the loop waits on memory, not arithmetic. Larger types show the same pattern: a Sprite with two Floats, a UInt32, a String and a Bool takes 40 bytes as written and 32 bytes with the String first.

Nothing in the toolchain points this out today. The compiler keeps declaration order (TypeLayout.rst), SwiftLint cannot see type sizes, and DWARF-based tools such as pahole do not work because Swift's debug info carries no member offsets for Swift structs (checked with dwarfdump). The only safeguard is a hand-written #expect(MemoryLayout<T>.stride == …) per type, and only for types someone already suspects.

Proposed diagnostic

A new diagnostic group, tentatively AvoidablePadding, suppressed by default and enabled with -Wwarning AvoidablePadding (SE-0443) or the SwiftPM warning settings (SE-0480).

Rule. For a struct whose stored properties all have a layout known at compile time:

  1. Let S be the stride of the struct as declared.
  2. Let S* be the stride the compiler's own layout algorithm produces with the stored properties sorted by alignment, largest first.
  3. If S* < S, emit the warning on the struct.

The sorted order is only used internally to prove that a better layout exists. It is never shown to the user, and the diagnostic makes no claim that S* is the minimum.

Message.

warning: the stride of 'Bad' could shrink from 24 to 16 bytes by reordering its stored properties [#AvoidablePadding]

Which fields to move, and whether to move them at all, stays with the author. The rule compares stride, because stride is what arrays, UnsafeMutablePointer.allocate(capacity:) and memory bandwidth pay for. Padding that no order can remove is never reported, which avoids the noise -Wpadded is known for.

Intentional layouts: @diagnose with a reason

Some layouts trade stride for locality on purpose, for example fields read together kept on one cache line, or producer and consumer indices kept apart to avoid false sharing. SE-0522 (implemented in Swift 6.4) already provides the opt-out, and its reason: parameter records why the layout is intentional, right at the type:

@diagnose(AvoidablePadding, as: ignored,
          reason: "head and tail stay on separate cache lines to avoid false sharing")
struct RingIndices {
    var head: Atomic<Int>
    var padding: InlineArray<15, Int>
    var tail: Atomic<Int>
}

The same attribute could also work the other way round, provided a default-suppressed group can be enabled per scope (see open question 2). A project that does not enable the group module-wide could then opt in for its hot-path types:

@diagnose(AvoidablePadding, as: warning)
struct Particle {
    // …
}

So the feature needs no new attribute and no new flag syntax: one diagnostic group, controlled by the mechanisms Swift 6.1 and 6.4 already ship. We checked that Swift 6.4 accepts @diagnose(<group>, as: ignored, reason: "…") on a struct declaration without an experimental flag and that it suppresses the group only inside that type.

Scope and limitations

The warning only fires where the compiler knows every field's layout; everything else is silently skipped.

Case Behaviour Why
Struct with fields of known, fixed layout Diagnosed The compiler can compute both strides
Field of a resilient type (library evolution, not @frozen) Containing struct skipped Size is only known at run time
Field of a generic parameter or opaque type Containing struct skipped Layout depends on the substitution
Generic @frozen struct Skipped No declaration order is right for every substitution
Struct imported from C Never diagnosed Layout is fixed by the C ABI
@frozen public struct in a library-evolution module Diagnosed, note says reordering is ABI-breaking once shipped Most useful before the first release
Classes, enums with payloads Out of scope for now Instance size and payload layout follow different rules

The computation must use Swift's layout algorithm, not C's. Swift distinguishes size from stride and places a field in the tail padding of a preceding struct-typed field, so a C-style estimate would report false positives for nested structs.

Target dependence. Layout depends on the target, so a struct that is clean on one platform can be reported on another, and in general there may be no single order that is clean on all targets. The diagnostic reports for the target being compiled. This is one more reason the group is off by default: projects that don't want target-dependent warnings simply don't enable it, and those that do want to know about such cases can.

Compile-time cost

When the group is disabled, the check is skipped entirely and costs nothing. When enabled, it computes one additional layout per struct with a fixed layout, from field type infos the compiler has already computed: a sort by alignment plus one layout computation. The diagnostic deliberately does not search for the optimal order: without C's size-multiple-of-alignment rule, no sub-quadratic algorithm for it is known.

Alternatives considered

Automatic reordering by the compiler. Reordering non-frozen structs has been discussed since 2016. It is not the goal of this pitch: source order is today the only tool developers have for locality, so it may carry intent, and it should only change where it makes a real difference and with the author's agreement. The diagnostic does not depend on reordering and does not rule it out.

An explicit layout attribute. An attribute such as @layout(compact) would keep today's behavior as the default and make a different layout an explicit opt-in. This is complementary, not an alternative: the attribute is a way to change a layout, the diagnostic is a way to find where a change pays off. Without the diagnostic, nobody knows which types would benefit from such an attribute. And for types that must keep their declared order, such as @frozen types that have already shipped, or where moving one field by hand is preferable to a different layout mode, the diagnostic is the only help. If such an attribute is pitched, a later version of the diagnostic could point to it directly.

A portable-layout check. A check that a type has the same layout on every target would give portable results, but it would have to forbid pointers, Int and other target-dependent types. It is aimed at binary serialization and complements this diagnostic rather than replacing it.

A -Wpadded-style warning. Reporting all padding is known to be noisy, because much of it cannot be removed. This pitch only reports padding that a reorder can remove.

Doing nothing. Projects can assert strides in tests today, but only for types someone already suspects, and the expected value has to be worked out by hand.

Future directions

Size, not only stride. A type stored inside another type contributes its size, not its stride, because Swift places the next field in its tail padding. A reorder that leaves a type's own stride unchanged can therefore still shrink every type that contains it:

struct Inner {          // size 8, stride 8
    var a: Int32
    var b: Bool
    var c: Int16
}
struct Outer {          // size 9, stride 12
    var inner: Inner
    var flag: Bool
}

Swapping b and c keeps Inner at stride 8 but reduces its size to 7, which brings Outer down to stride 8, a third less per element. The rule above does not report this case. It could be covered by a separate group, for example AvoidableTailPadding, so that the main group stays quiet.

A fix-it. Since the diagnostic suggests no order, there is nothing for a fix-it to apply. A follow-up could offer one when the memberwise initializer is not public, where reordering fields is not an API change.

Pointing to a layout attribute, if one is added (see Alternatives considered).

Open questions for the compiler team

  1. Where can this be diagnosed? As far as we understand, concrete struct layout is computed late, during IRGen, where warnings are unusual. Is there an earlier point (type lowering, SIL) that knows fixed layouts, or is an IRGen-time warning acceptable here? An IRGen-time warning would not appear during type-checking-only runs such as SourceKit.
  2. Default-suppressed groups. SE-0522 states that default-suppressed warnings can be enabled with -Wwarning. Can a new group be declared default-suppressed, and does @diagnose(Group, as: warning) enable such a group inside one type?
  3. Threshold. Clang's checker only reports above a configurable threshold. Diagnostic groups currently take no parameters. Should there be a fixed minimum saving, or is any stride reduction worth reporting for an opt-in group?
  4. Name. AvoidablePadding, StructPadding or SuboptimalLayout?

Prior art and prototype

Clang has shipped a similar idea since 2015: the static analyzer's opt-in checker optin.performance.Padding reports records "that could reduce [their] padding by reordering the fields", with a configurable threshold (AllowedPad, default 24 bytes). It skips cases with ABI complications, much like the scope table above.

Tool What it reports Noise
GCC / Clang -Wpadded Any padding at all High: also unavoidable padding
Clang optin.performance.Padding Padding a reordering would remove, above a threshold Low
This pitch The stride saving a reordering could achieve Low
Rust (repr(Rust)) Nothing: the compiler reorders fields itself None

The rule is cheap to compute and easy to prototype today. A test helper using Mirror, MemoryLayout and _openExistential reproduces the proposed result for these example types. Its output still lists one possible order, which the proposed diagnostic deliberately omits (messages translated):

⚠ Bad: stride 24, possible 16 with order ["value", "isActive", "isVisible"]
✔ Good: stride 16 is optimal
⚠ Sprite: stride 40, possible 32 with order ["name", "x", "y", "color", "flag"]

The prototype needs a sample value of each type and cannot see tail-padding reuse in nested structs; the compiler has neither limitation.

Sources

12 Likes

Why wouldn't we have the language do this automatically? I thought the reason that only @c structs, @frozen type, and tuples had stable layout was exactly to let the language evolve its native representation. At the least, can the pitch be updated to review why automatic optimal packing isn't possible or desirable?

13 Likes

If it’s not possible to get this automatically generally as suggested by Jon above, could this be enabled per module / package ? I understand one doesnt want its public api to change without code change but synthesized init are internal so I gladly apply a fix it in internal code, if I care about api / style I would write the init manually anyway.

For non-frozen types, it should absolutely be possible to have the compiler reorder fields' storage. That's been suggested before and AFAIK is just a question of available compiler engineering resources.

For frozen types on platforms with ABI stability (Apple), the layout cannot be safely reordered from its current order, but it is conceivable that a language mode change, minimum deployment target, etc. could introduce a different layout algorithm that involves reordering.

A diagnostic seems overly noisy to me.

3 Likes

This is one of those things which we've said we'd want to do all along, but it's been so long I wonder if it ought just to be explicitly opt-in (@reorderableFields or something).

This would not only avoid implicating Hyrum's law but gets us away from the matrix of availability + language mode + library evolution mode or not + frozen or not which, frankly, I find nigh impossible to reason about.

1 Like

Thanks for the feedback. To be clear up front: I think automatic reordering for non-frozen types is the real goal. I see this pitch as a step toward that, not as an alternative to it. I'll add an "Alternatives considered" section that makes this explicit.

@Jon_Shier, @grynspan: So why start with a warning?

  1. It can ship today.
    It needs no new layout, no ABI change and no new syntax, just a diagnostic group on top of the existing SE-0443/SE-0522 infrastructure.

  2. It stays useful for frozen types. On ABI-stable platforms their order can't be changed after the fact, so a warning before the first release is the only safeguard.

  3. Reordering narrows it rather than replacing it. Once the compiler reorders non-frozen types itself, the warning naturally only applies to frozen types. Nothing has to be rolled back.

A question for the compiler team: apart from engineering bandwidth, are there technical reasons reordering hasn't happened yet, such as reflection, LLDB, or code that relies on declaration order? Clarifying that seems like the next step toward the larger change.

On noise: the group is off by default and only reports padding that reordering can actually remove, unlike -Wpadded. I'd also add a threshold similar to Clang's AllowedPad.

@xwu: I agree an explicit opt-in avoids the matrix. I'd find a module- or package-level setting more ergonomic than a per-type attribute, though. Either way, the warning would show where reordering pays off.

@AlexisQapa: Offering a fix-it only when the memberwise initializer isn't public seems like a good compromise. I'll add it as an option.

Tangentially, you can only optimize the layout of a struct by declaration order if you know the layout at the time of declaration. Imagine:

@frozen struct  CannotOptimizeThisLayoutByDeclarationOrder<First, Second> {
	let first:  First
	let second: Second
}

So, in the general case, a @representation(convention) could be useful regardless of whether nonfrozen types are optimized automatically.

One more consideration is when you want explicit layout to avoid false sharing. Opt in and automatically optimized layout is good, but I could see some annotation help for optimizing layout by hand to be useful too.

3 Likes

That doesn't mean it should ship. If the right solution to some problem takes more time to implement than the ready solution, that doesn't mean we should ship that solution, especially when there is no inherent time constraint (like some regulatory deadline or pending CVE disclosure).

8 Likes

Is it? I think there’s more value in allowing explicit control of layout. The developer can apply knowledge about what properties are commonly accessed together and therefore should be in the same cache line.

2 Likes

Optimal layout without C’s size-multiple-of-alignment rule is trickier; I implemented a back-filling algorithm for it in LLVM, but it doesn’t guarantee optimality. I don’t know that there’s a general algorithm that’s sub-quadratic.

We also don’t want to disturb source order unless it actually makes a difference, and even then only to the degree it makes a difference. Adjacency in source often reflects some essential connection or similarity, which suggests that locating those things together might be good for locality, at least in the absence of better knowledge. Also, of course, source order is the only tool people have today for getting these locality effects, so it may be intent-carrying. So the one algorithm I know of — sorting by alignment and then possibly back-filling — isn’t really what we want anyway.

We would be optimizing size, not just stride. Yes, array layout is the thing most important for minimizing memory use. But types are often stored in other types, and minimizing size allows those types to be more compact, meaning that they have more efficient storage in arrays.

Switching to a design perspective, we would need some way to opt out, for people who really are trying to match some known layout. (Although I would hope people aren’t generally trying to match a layout with interior padding. In any case, a guarantee that we don’t disturb layouts without interior padding seems like a necessity here.) And the shape of that really is wide open, from some simple “just leave source order alone” attribute to a more complete “ensure this has portable layout” check to a really broad “layout control” feature.

7 Likes

There's a little trickiness here that layout optimality is target-dependent, which means that you'd build without warning on some systems, but then someone tries to port to a new system and starts getting warnings, and there may not (in full generality) be a single layout that avoids warnings on all targets. There's a group of programmers who very much want to know about that situation, but it can also be pretty annoying to stumble into (target-dependent warnings in general often end up being a little annoying).

I don't think any of that is a dealbreaker, but it's worth keeping in mind.

7 Likes

Right. That’s one of the merits of a feature based on checking for portable layout, that it has a portable result (assuming people don’t play silly games like declaring types portable in an #if). You would have to compose the type entirely from types with frozen, portable layout, so pointers, Int, etc. would all be disallowed. If we accept that it’s laser-targeted at people doing binary serialization, disallowing interior padding would be a natural thing to include.

Of course, those properties make it less useful as a general tool for controlling layout.

5 Likes

A new attribute like @layout(compact), @layout(c), @layout(compiler <= 6.4) (etc. etc. bikeshed bikeshed) seems like the right way to provide this feature, then. Default to what we have, but let the developer opt in to some alternate/better/custom/whatever mode.

2 Likes

Thanks for all the replies. They helped me sharpen what this pitch is actually about, so let me restate it.

This pitch is about diagnostics. The core use case is simple: I enable the group, build, and see every struct in my module whose layout leaves bytes on the table, together with the possible saving, e.g. "the stride of 'Bad' could shrink from 24 to 16 bytes by reordering its stored properties". It doesn't change any layout and doesn't suggest an order. It answers one question: where do I have room for improvement in my struct layouts? Today nothing in the toolchain answers that.

I no longer frame this as a step toward automatic reordering. Following @John_McCall's and @ksluder's points, source order can carry intent, so the compiler should point out the opportunity and leave the decision to the developer.

@grynspan: I like the @layout(…) direction, and I don't see the two as mutually exclusive. The attribute is a way to change a layout; the diagnostic is a way to find where a change would pay off. Without the diagnostic, nobody knows which types would benefit from @layout(compact). And for types that must keep their declared order, such as @frozen types that have already shipped, or types where I'd rather move one field by hand than opt into a different layout mode, the diagnostic is the only help there is. I'd be glad to see @layout pitched on its own; a later version of the diagnostic could then point to it directly.

@John_McCall: I'm narrowing the proposal accordingly:

  1. The diagnostic doesn't suggest an order at all, it only reports the possible saving. Which fields to move, and whether to move them, stays with the author.
  2. It makes no claim of optimality, only that a better layout exists.
  3. The first version only looks at stride. I agree size matters for types stored inside other types; I'd list that as a future direction, possibly as a separate group, so the main case stays quiet.

@scanon: I'll add target dependence as a documented limitation. The group is off by default, so people who don't want target-dependent warnings simply don't enable it. I see the portable-layout check John describes as a complementary tool for serialization, not a replacement.

@ksluder, @hassila: That's exactly the direction: explicit control, informed by the compiler. Intentional layouts, e.g. to avoid false sharing, can be documented right at the type with @diagnose(AvoidablePadding, as: ignored, reason: "…").

@oscbyspro: Generic @frozen types can't be checked by this diagnostic at all. A representation attribute would be a separate feature.

@AlexisQapa: With the diagnostic no longer suggesting a specific order, a fix-it doesn't fit into this first version. I still think your idea of offering one when the memberwise initializer isn't public is worth pursuing, and it could be a good topic for a follow-up pitch once the basic diagnostic is settled.

I'll update the pitch along these lines.

2 Likes

@John_McCall, to expand on point 3 from my previous post: here is the case I had in mind, because I think it shows why size deserves a diagnostic of its own. A reorder can leave a type's stride unchanged and still help, because the next field of a containing type goes into its tail padding:

struct Inner {          // size 8, stride 8
    var a: Int32
    var b: Bool
    var c: Int16
}
struct Outer {          // size 9, stride 12
    var inner: Inner
    var flag: Bool
}

Swapping b and c keeps Inner at stride 8 but brings its size down to 7, and Outer drops from stride 12 to 8. The stride rule never reports Inner, even though every type embedding it pays for it.

The reason I'd keep it in a separate, optional group is noise: most size-only findings only pay off if the type is actually embedded somewhere, and the compiler can't tell that from the type alone. It could come with this pitch, but it doesn't have to. Would you see value in it as an optional companion group, or would you rather fold size into the main rule from the start?

I feel like this approaches the problem space from the wrong direction. Intentionally opting out of a warning also opts out all unintentional transgressions of that warning. This approach increases the risk that someone who wants to opt out today accidentally lets a regression slip in.

It also feels presumptuous for the compiler to assume padding bytes are superfluous, when they may be very necessary for the performance of alignment- or cache-sensitive algorithms. In 3D graphics, a lot of operations on 3xFloat are parallelizable with SIMD, but only if your values are aligned to 4xFloat alignment. If I order my stored properties in a way that happens to result in SIMD-compatible alignment, it would be particularly bad for the compiler to “helpfully” rearrange my struct to eliminate the padding!

There are certainly times I’d like the compiler’s help, either by automatic reordering or just a warning—for example, when storing compact mesh data in memory, I’d want a warning about compactness rather than automatic reordering because I’m likely blitting the mesh data straight out of a file into a @frozen type. But compactness in memory is sometimes an anti-goal.

1 Like

Could an explicit layout opt-in be expressed by a marker protocol?

struct S: Compact { // removes avoidable padding, can only be on the main type body
    ....
}

What happens to the order of Mirror children for a type where the compiler reorders the fields? Is it still showing Swift source order, or binary order?

I feel that perhaps such an analysis is more akin to @_assemblyVision as a fairly specialised optimisation help annotation?