by aetherspawn · 8y ago · 0 comments
The assumed behaviour of bit fields is well defined between gcc and clang with the proper pragmas. It is therefore probably a non-issue. You even get better aliasing optimisations* using union/bit fields over just using bit shifts.
*) this means, if your union contains a way to read the whole field as ie uint_32t and also to read each field individually and also write struct as u32 via pointer, compiler can properly detect which actions cause read/write invalidation of each other instead of having to assume all volatile-like.
Use case 1: https://gist.github.com/donkeybonks/8749545
Use case 2 (with asm showing better codegen with union): https://gist.github.com/donkeybonks/11103152
nb these gists are ~4 years old because I don’t much care about micro-optimisation anymore.
nb2 it’s a really good idea to static assert the size of all your structs below their declaration for confidence and splash a few unit tests for ordering.
From the GCC documentation[1], it says:
> Determined by ABI.
This means that it may be different when compiling for different architectures. How you can say it well-defined? Here is a good example [2] on the compability issue when using bit fields
[1]: https://gcc.gnu.org/onlinedocs/gcc/Structures-unions-enumera...
In an immense majority of case you won't be serializing or exchanging your bitfields over the network ; this is entirely a non-problem.
My own experience with bit field optimizations was that they were worse in general for GCC and ARM compilers from 4+ years ago. LLVM was much better. For example if you tried to set a few fields that fit within a machine word to a constant value, it should be possible to set them in a single opcode but only LLVM takes the liberty to do this.