4 ms·
Regarding 12, alignment of bitfields, how I believe it works is that when the bitfield of type long is laid out, then the structure so far is considered to be a
by kazinator 4y ago
Regarding 12, alignment of bitfields, how I believe it works is that when the bitfield of type long is laid out, then the structure so far is considered to be a vector of storage cells whose size and alignment are those of long:
struct foo {
char a;
long b: 16;
char c;
};
So, a has been laid into the structure, so the current offset is 1 byte.
This is considered to be occupying a portion of an existing long type bitfield cell. In other words a is essentially taken to be an 8-bit field in the first long-sized cell of the structure. That cell looks like it has 56 bits left in it (if we assume 64 bit long). Since 56 > 16, the new bitfield b is placed into that cell. When that field is placed, the placement offset becomes 3. The type of c being char, that offset is acceptable for c.
I've painstakingly reverse engineered the rules when developing the FFI for TXR Lisp:
1> (sizeof (struct foo (a char) (b (bit 16 long)) (c char)))
8
2> (alignof (struct foo (a char) (b (bit 16 long)) (c char)))
8
3> (offsetof (struct foo (a char) (b (bit 16 long)) (c char)) a)
0
4> (offsetof (struct foo (a char) (b (bit 16 long)) (c char)) b)
** ffi-offsetof: b is a bitfield in #<ffi-type (struct foo (a char) (b (bit 16 long)) (c char))>
4> (offsetof (struct foo (a char) (b (bit 16 long)) (c char)) c)
3
I've summarized my empirically-obtained understanding for the benefit of users and anyone else doing similar work in a different project.
https://www.nongnu.org/txr/txr-manpage.html#N-027D075C https://www.nongnu.org/txr/txr-manpage.html#N-027D075C
- int_19h 4y agoThe cell size is not necessarily the same as "long" - it can be whatever the compiler wants, so long as alignment of non-bitfield fields is appropriate. It doesn't even have to be the same for every bitfield.
- kazinator 4y agoIf the bitfield is declared as long, then based on that specific cell size the decision is made whether to pack the bits into the current cell or a new cell. If a leading char member is followed by a uint64_t bitfield that is 57 bits wide, a new cell will be allocated for those 57 bits at offset 8. The char is considered to be a field of 8 bits allocated in an existing 64 bit cell, leaving 56. 57 cannot fit, and so the offset is bumped to the next cell alignment. This is testable. I'm only writing about GCC, not about ISO C, which specifies very little, allowing implementations latitude in choosing the underlying storage unit size and alignment for bitfields regardless of their declared type.