Repository navigation
C front-end: GCC and Clang placement of bit-fields - #9579
Open
tautschnig wants to merge 20 commits into
Open
tautschnig wants to merge 20 commits into
tautschnig wants to merge 20 commits into
Conversation
Packing needs to be evaluated as part of the definition of a type, while an alignment attribute also applies where the type is used. The position of an attribute also requires care, as GCC accepts some positions while ignoring the attribute there (Clang warns that it ignores them). - A typedef'd type no longer carries the packing of the type it names (which is already reflected in the layout of a packed struct/union), unless the use site requests packing, so that a packed-struct typedef used as a member does not pack the enclosing struct (diffblue#8443). - Alignments are combined (the stricter one applies) when a struct/union declared with an alignment attribute is completed, and when a typedef that carries an alignment is used with another one. - A packed attribute preceding the struct/union keyword of a declaration is dropped, as GCC and Clang ignore it. - Alignments must be positive powers of two (C11 6.2.8p4), which the type checker now verifies. An alignment of zero has no effect (C11 6.7.5p6, and GCC also ignores __attribute__((aligned(0))), with a warning), so the type checker drops it. - As the natural alignment of a scalar was its size, the 12-byte long double of i386 had an alignment of 12, which the new check would reject in the declaration of max_align_t in GCC's and Clang's stddef.h, which uses __attribute__((__aligned__(__alignof__(long double)))) GCC and Clang align this long double to 4, i.e., the largest power of two that divides its size, which is now the natural alignment of a scalar whose size is not a power of two. The new test ansi-c/gcc_attributes16 covers attributes in many positions, including a reduction of diffblue#8443, and gcc_attributes16_align_error covers an invalid alignment. alignas_zero covers an alignment of zero, and long_double_alignment_i386 uses Clang's support for targeting i386 on any host. Fixes: diffblue#8443 Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
A union's size must be a multiple of its alignment, including when the
alignment comes from an explicit aligned() attribute on a packed union.
Previously add_padding(union_typet) discarded any explicit alignment for
packed unions (rounding the size up to a single byte only), so e.g.
union __attribute__((packed)) __attribute__((aligned(16))) u
{ uint8_t c; int32_t i; };
had size 4 instead of 16. The alignment is now computed as the maximum
member alignment (one byte if packed), raised by an explicit aligned()
attribute regardless of packing, matching GCC and Clang.
Adds regression test union_packed_aligned, and checks the size of an
aligned union in gcc_attributes16.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The alignment of a struct/union member depends on whether the enclosing aggregate is packed, which a context-free alignment() could not capture: the same type (e.g. int aligned(2)) must align to 4 inside a non-packed struct (an aligned() attribute can only increase alignment there) but to 2 inside a packed struct (where it is honoured verbatim). alignment() now derives an aggregate's alignment from its members' layout alignments, computed in the aggregate's packing context via a new member_layout_alignment helper: - packed field: the explicit alignment verbatim, otherwise one byte; - non-packed field: max(explicit, natural) -- an aligned() request smaller than the natural alignment is ignored. An explicit alignment on the aggregate itself can only raise the result, while on a non-aggregate (e.g. a typedef) it is still taken verbatim. Padding members no longer contribute to an aggregate's alignment (they previously polluted _Alignof of e.g. a union with an array member). add_padding_gcc uses the same per-member computation for member offsets, and a packed struct is now padded up to the alignment forced by an explicitly-aligned member (it previously skipped end-of-struct padding for any packed struct). add_padding(union_typet) is simplified to rely on the corrected alignment(). This makes sizeof/_Alignof match GCC and Clang for member-level and struct/union-level aligned()/packed combinations. Adds regression test struct_member_alignment. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
An alignment attribute that follows a declarator, as in a struct member int32_t m __attribute__((aligned(8 + 8))); is attached to the declarator's type outside the already type-checked declaration type. typecheck_type only type-checked and folded the alignment of a type that is not already type-checked, so this alignment remained an unevaluated expression. padding then failed to convert it to a number and silently used the natural alignment instead: the member was placed at offset 4 rather than 16. Literal alignments happened to work, as the unevaluated literal converts to a number, and so did members of array type, whose attributes take a different path. Invalid alignments, such as aligned(5 + 0), were accepted silently. Type-check, fold, and validate such alignments as well, sharing the code with the existing alignment handling, and report errors at the location of the alignment expression, as the type may not carry a location. Extend struct_member_alignment by members with constant-expression alignments, and add the negative test gcc_attributes16_align_error_member. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Anonymous structs and unions are named after their members, and an
existing type symbol of the same name is re-used. As the name did not
include packing or alignment attributes, `struct { int i; } a1;` and
`struct { int i; } __attribute__((packed)) a2;` were conflated, and
whichever was declared first determined the layout of both. Include
packing and explicit alignment of the aggregate and of its members'
types in the name.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The parser used to communicate #pragma pack(n) by attaching both __attribute__((packed)) and __attribute__((aligned(n))) to each member whose type is not a struct or union, and additionally marked the aggregate as packed for pack(1). This conflated the pragma's cap on member alignment with explicit attributes, and was wrong in several ways: - an aligned attribute on the aggregate was capped by the pragma, but GCC, Clang, and Visual Studio do not cap it (and the aggregate-level packed of pack(1) had no such effect either); - packed on the aggregate no longer reduced member alignment to one; - explicit aligned() on members was replaced rather than capped; - members of struct or union type were not capped at all. Record the applicable #pragma pack value with each member declaration instead (ID_C_pragma_pack), and cap each member's layout alignment at that value in padding, for both GCC and Visual Studio layouts. The value that applies differs between compilers when the pragma changes within a definition: GCC uses the value in effect at the closing brace, Clang the value in effect where the definition starts, and Visual Studio the value in effect at each member. The parser determines the value accordingly. Bit-fields are capped as well. Anonymous aggregates are distinguished by the per-member value, and dump-c reproduces the pragma (which, for pack(1), it previously did via the aggregate-level packed attribute). The test goto-instrument/dump-c-pragma-pack checks the layout using pointer differences, which, unlike sizeof, dump-c does not replace by their value, so that compiling the output again checks the layout. dump-c-pragma-pack-anonymous (KNOWNBUG) documents that the inline definition of an anonymous struct member does not reproduce the #pragma pack in effect for that struct. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
`#pragma pack(n)` sets the current maximum alignment, and `#pragma pack()` resets it to the default; neither changes the stack used by `#pragma pack(push[, n])` and `#pragma pack(pop)`. We instead pushed n, and cleared the whole stack, respectively, so that, e.g., a `#pragma pack(pop)` following `#pragma pack(push, 1)` and `#pragma pack(2)` restored a maximum alignment of 1 rather than the value before the push. Furthermore, a `#pragma pack(pop)` without a matching push reset the current value to the default rather than retaining it. This matches the documentation and behaviour of GCC, Clang, and Visual Studio. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Bit-fields contributed the alignment of their underlying type to the
alignment of the enclosing struct (used for end-of-struct padding) even
when the struct is packed, so that, e.g.,
`struct { int m : 7; } __attribute__((packed))` had size 4 instead of
1. Use the member layout alignment instead, which now also covers
bit-fields:
- in a packed aggregate, bit-fields are densely packed, unless a
#pragma pack(n) is in effect, which then caps their alignment at n
(GCC and Clang agree on this);
- a zero-width bit-field aligns the next member to its underlying type
irrespective of packing, but, like any unnamed bit-field, only affects
the alignment of the aggregate where unnamed bit-fields do (see
unnamed_bit_fields_affect_alignment): on ARM (other than Apple's ABI),
and on Windows.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
GCC and Clang distinguish the alignment of a declared entity from that
of its type: an alignment attribute in a declaration applies to the
declared member, object, or typedef, irrespective of its position in
the declaration. For members, such an attribute can only increase the
alignment, also within packed aggregates and for bit-fields (whose
start it then aligns). For objects, it may also reduce the alignment.
In contrast, the alignment of a type (set by a typedef or a
struct/union definition) may be smaller than its natural alignment,
and packing overrides it.
We previously recorded every alignment attribute on whichever type it
was syntactically attached to, and treated all of them as increasing
the alignment of a member. This went wrong in several ways:
- a typedef that reduces the alignment of a type, as in
`typedef int T __attribute__((aligned(2)));`, did not reduce the
alignment of members of type T;
- `__attribute__((aligned(16))) char *p` or
`long __attribute__((aligned(2))) m[2]` aligned the pointee or
element type rather than the member;
- packing did not override the alignment of typedef'd types or of
struct/union definitions used as members, but did override member
attributes;
- a member attribute replaced, rather than combined with, the
alignment of a typedef'd type;
- the alignment of a struct/union definition was copied to every use
of its tag, where it was then taken verbatim, so that
`struct S { long l; } __attribute__((aligned(1)))` reduced the
alignment of members of type `struct S`;
- an attribute on an object could not reduce its alignment (as
reported by __alignof__).
Record alignments requested by declarations separately
(ID_C_declaration_alignment), move them to the outermost level of the
declared entity's type, and turn them into the type's alignment for
typedefs only. __typeof__ does not carry them over, as they are not
part of the type. Struct/union definitions keep their attributes with
the type symbol only. The parser drops packed and aligned attributes
between the keyword and the tag of a declaration without body, as in
`struct __attribute__((aligned(16))) S *p;`, which GCC ignores, so that
they do not become declaration alignments of p. GCC (but not Clang)
applies an attribute that follows the '*' of a pointer declarator to the
pointer type, which the parser now marks accordingly. When combining a
plain `__attribute__((aligned))` with an explicit alignment, retain the
latter, as we do not determine the target's maximum alignment. Encode
declaration alignments in the names of anonymous aggregates.
This promotes ansi-c/struct_member_alignment_typedef from KNOWNBUG to
CORE. The new test cbmc/Bitfields6 is the example of diffblue#7816, where the
alignment attributes of bit-field declarations did not align the start
of the bit-fields.
Fixes diffblue#7816
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The parser accepted Visual Studio's __declspec between `struct`/`union`
and the tag, but discarded it, so that, e.g.,
`struct __declspec(align(8)) S { char c; };` had size 1 and alignment
1 instead of 8. Retain the declspec with the type, which already
handles align(n).
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Differential testing against MSVC x64 (via Compiler Explorer) showed three differences in Visual Studio mode: - the trailing padding of a struct or union is capped by the #pragma pack in effect at the end of its definition, whereas the alignment of the aggregate is not; - #pragma pack does not reduce an alignment that __declspec(align(n)) requires (also via a typedef), neither for a member nor for the trailing padding; - bit-fields do not affect the alignment of a union (only its size). Record the #pragma pack value at the end of the definition with the aggregate in Visual Studio mode, and lay out members using the common member layout alignment, which now also implements the latter two rules. dump-c reproduces the value at the end of the definition. The new test goto-instrument/dump-c-pragma-pack-msvc covers dump-c in Visual Studio mode. For this, chain.sh passes options selecting a Visual Studio target to goto-cc (except on Windows, where this is the default), and does not compile the output of dump-c again, as this would require Visual Studio's system headers. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Reading an alignment or #pragma pack value from a type or component -- find the attribute, cast it to an expression, and convert it to a number with a default -- was repeated in padding (twice), type2name, and dump-c, not all of which handled an `aligned` attribute without argument (ID_default). layout_attribute now does this in one place. Also document member_layout_alignment, which implements the layout rules that depend on the context of a component. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Whether a packed or aligned attribute applies to a struct/union type or
to the declared object, member, or typedef depends on its position, as
GCC and Clang agree:
- between the struct/union keyword and the opening brace, and directly
after the closing brace, it applies to the type being defined;
- in any other position, e.g., preceding the keyword, following a
qualifier, or following the tag of a declaration without body, it
applies to the declared entity.
Attributes in the latter positions of a definition previously ended up
with the type being defined, so that, e.g.,
__attribute__((aligned(16))) struct S { char c; } s;
aligned struct S rather than just s, and
const __attribute__((packed)) struct P { char c; int i; } p;
packed struct P (only a packed attribute preceding the keyword was
dropped). Furthermore, the last of several alignment attributes of a
declaration applied.
The parser now marks the attributes in type positions, which become
attributes of the type (ID_C_alignment, ID_C_packed), while all others
become attributes of the declared entity, recording packing of a
struct/union definition as ID_C_declaration_packed until the type
checker moves it to the tag type. A packed attribute then packs a
member, as GCC and Clang do, and has no effect for an object. With
several alignment attributes of a declaration, the largest one now
applies, as with GCC and Clang. For a type, GCC uses the last one, and
Clang the largest one.
Visual Studio, in contrast, applies __declspec(align(n)) in the other
positions of a definition (e.g., preceding the keyword) to the declared
entity and also to the type being defined, unless a declspec between
the keyword and the opening brace sets the alignment of the type: with
__declspec(align(8)) struct S { char c; };
the size of struct S is 8, as Struct_Padding5 and Union_Padding1 expect
on Windows.
The new test ansi-c/alignment_attribute_positions covers these cases,
gcc_attributes16 now also covers attributes preceding the keyword of a
definition, and declspec_align_struct covers the Visual Studio rules.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The alignment that the declaration of an object or member requests (ID_C_declaration_alignment) is recorded with the type of the declared entity, and thus also travelled into the types of expressions computed from it: with int x __attribute__((aligned(16))), __alignof__(x + 0) was 16, where GCC and Clang give 4. __alignof__ now uses the declaration alignment for objects and members only. GCC and Clang disagree on __alignof__(*&x): GCC folds the dereference of the address of an object to that object, and thus yields 16, whereas Clang considers the operand as written, and yields 4. Furthermore, for a dereferenced pointer GCC uses the largest alignment of the pointee types of the pointer and of any pointers it was converted from, so that __alignof__(*(char *)&x) is 4 with GCC and 1 with Clang. Implement both behaviours depending on the compiler mode. The new test ansi-c/alignof_expression covers these cases, and runs in both GCC and Clang mode. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
GCC ignores packed and aligned attributes between the struct/union
keyword and the tag of a declaration without body, as in
struct __attribute__((aligned(16))) S;
struct S { char c; };
Clang, however, applies them to the type if it is not complete yet, so
that the above S has an alignment of 16 with Clang and of 1 with GCC.
Once the type is complete, Clang ignores them as well (with a warning).
With several such declarations, as well as with a definition that has
attributes of its own, the largest alignment applies, and the type is
packed if any of them requests packing.
The parser now marks these attributes as type attributes, and, in Clang
mode, the type checker records them with the incomplete type symbol,
from where the definition picks them up. In GCC mode they continue to
be ignored.
The new test ansi-c/attributes_declaration_without_body covers these
cases, and runs in both GCC and Clang mode.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Visual Studio accepts declspecs in the declaration of a member, e.g.,
struct M { char c; __declspec(align(16)) int i; };
for which goto-cc reported a syntax error, as the grammar only permits
declspecs where storage classes may occur. Members now also accept
declspecs preceding their type, which, like any other alignment
attribute of the declaration of a member, can only increase its
alignment.
The new test ansi-c/declspec_align_member checks the layouts that MSVC
19 for x64 yields for such members.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Visual Studio does not let __declspec(align(n)) reduce an alignment (it ignores such a declspec, warning C4359 for a struct), and it uses the last of several align declspecs of a declaration (warning C4141). Like for GCC's aligned attribute, goto-cc instead reduced the alignment of objects and typedefs, e.g., __alignof(x) was 2 with __declspec(align(2)) int x; and used the largest of several align declspecs. In Visual Studio mode, the explicit alignment of a type or of an object is now at least its natural alignment, and the last align declspec of a declaration applies. The new test ansi-c/declspec_align_msvc_rules checks the alignments that MSVC 19 for x64 yields. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
GCC and Clang do not let a bit-field span more units of the alignment
of its declared type than the type itself does (excess_unit_span in
GCC's stor-layout.cc, and the equivalent check in Clang's
RecordLayoutBuilder): a bit-field that would straddle such a boundary
starts at the next one instead. CBMC placed each bit-field directly
after the preceding one, so that, e.g., the size of
struct { char a; int x : 31; char b; }
was 8 rather than 12 on all targets that follow the System V or the Arm
ABIs (the Visual Studio layout is unaffected). This rule does not apply
in packed structs, to packed bit-fields, or when #pragma pack is in
effect. Note that a packed attribute of a bit-field's declaration is
recorded with its underlying type.
As inserting such padding moves the end of a sequence of bit-fields, the
padding that makes subsequent members start on a byte boundary is now
inserted while laying out the members rather than in a separate pass.
Differential testing against GCC 13 (x86-64, 32-bit Arm) and Clang 18
(x86-64, AArch64, RISC-V, and x86-64 FreeBSD, for which CBMC follows
Clang), comparing the sizes, alignments, member offsets, and the bytes
covered by each bit-field of 3000 randomly generated structs and unions
with bit-fields of all widths, unnamed and zero-width bit-fields,
packed structs and bit-fields, and #pragma pack: 492 of them differed
before this change, and 6 after, all of which have packed bit-fields
with #pragma pack, which a subsequent commit fixes.
The new test cbmc/bit_field_straddle checks a selection of such
layouts for x86-64 Linux and FreeBSD, and for Arm Linux.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
An alignment attribute of the declaration of a bit-field aligns the
start of the bit-field. CBMC did so only for alignments greater than
one, whereas GCC and Clang also start a bit-field with an aligned(1)
attribute on a byte boundary. Moreover, GCC and Clang differ in how
such attributes interact with the rule that a bit-field must not
straddle a unit of its declared type, and with #pragma pack:
- GCC first aligns the start as requested, with #pragma pack(n) capping
the requested alignment at n, and then checks for straddling.
- Clang first checks for straddling, using the larger of the alignment
of the declared type and the requested alignment, and honours the
attribute only when the bit-field does not need to move. With #pragma
pack(n), it ignores attributes requesting more than n.
For example, in
struct { char a[3]; __attribute__((aligned(2))) long long x : 37; }
GCC places x at offset 8, and Clang at offset 4. CBMC now follows Clang
in Clang mode (as used for macOS and FreeBSD), and GCC otherwise.
Differential testing with 1500 randomly generated structs and unions
with alignment attributes on bit-fields against GCC 13 for x86-64 and
32-bit Arm Linux, and Clang 18 for x86-64 FreeBSD: 23 of them differed
before this change, and none after.
The new test cbmc/bit_field_alignment_attribute checks a selection of
such layouts for both compilers.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
With #pragma pack(n), GCC and Clang align a bit-field whose declaration
has a packed attribute to the alignment of its declared type, capped at
n, as they do for other bit-fields; only without #pragma pack does the
attribute reduce the alignment to one. As the packed attribute is
recorded with the underlying type of the bit-field, CBMC computed the
alignment of the underlying type as one, which #pragma pack(n) then did
not raise, so that, e.g., the alignment of
#pragma pack(4)
struct { __attribute__((packed)) int m : 3; };
was 1 rather than 4.
Differential testing with 3000 randomly generated structs and unions
with packed bit-fields and #pragma pack against GCC 13 (x86-64, 32-bit
Arm) and Clang 18 (x86-64, AArch64, RISC-V, x86-64 FreeBSD): 6 of them
differed before this change, and none after.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
tautschnig
requested review from
kroening,
martin-cs,
peterschrammel and
remi-delmas-3000
as code owners
November 26, 2026 13:35
There was a problem hiding this comment.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing. Review the Copilot code review billing settings.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## develop #9579 +/- ##
===========================================
+ Coverage 81.29% 81.35% +0.06%
===========================================
Files 1725 1725
Lines 191680 192132 +452
Branches 73 74 +1
===========================================
+ Hits 155832 156316 +484
+ Misses 35848 35816 -32 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Depends-on: #8454
Three fixes to the placement of bit-fields with GCC and Clang (all targets other than Visual Studio):
#pragma pack. For example,struct { char a; int x : 31; char b; }now has size 12 rather than 8.aligned(1), aligns the start of the bit-field. GCC and Clang differ in how this interacts with straddling and with#pragma pack; CBMC follows Clang in Clang mode (macOS, FreeBSD, or goto-cc with clang as native compiler) and GCC otherwise.#pragma pack(n)takes precedence over a packed attribute of a bit-field's declaration, as with GCC and Clang.These were found by differential testing. The test compares sizes, alignments, member offsets, and the bytes covered by each bit-field of randomly generated structs and unions. The oracles are GCC 13 for x86-64 and 32-bit Arm Linux, and Clang 18 for x86-64, AArch64, and RISC-V Linux, and for x86-64 FreeBSD. On #8454, 492 of 3000 structs and unions without alignment attributes differed, and 387 of 1500 with them. With this PR, none differ for the GCC targets and FreeBSD. In Clang mode (goto-cc with clang), none differ for x86-64, AArch64, RISC-V and 32-bit Arm Linux, nor, combined with #9574, for i386 Linux.
cbmc --os linuxuses GCC mode, so against Clang it differs only where GCC and Clang disagree. Combined with #9574, i386 Linux (GCC) agrees as well. The commit messages give the numbers for each fix.