Wouldn't this be better with bitfields?

Steven Schveighoffer schveiguy at gmail.com
Wed Jul 3 03:26:57 UTC 2024


On Tuesday, 2 July 2024 at 23:32:22 UTC, Walter Bright wrote:
> Take a look at this instruction:
>
> https://www.scs.stanford.edu/~zyedidia/arm64/encodingindex.html#addsub_imm
>
> And this bit of implementation:
>
> https://github.com/dlang/dmd/pull/16554/files#diff-230d65c83f6bee1f96ea368513dbbe744372ed550c54ce6f0be171ef0848815dR38
>
> ```
> /* Add/subtract (immediate)
>  * ADD/ADDS/SUB/SUBS Rd,Rn,#imm{, shift}
>  * 
> https://www.scs.stanford.edu/~zyedidia/arm64/encodingindex.html#addsub_imm
>  */
> static uint addsub_imm(uint sf, uint op, uint S, uint sh, uint 
> imm12, ubyte Rn, ubyte Rd)
> {
>     return (sf     << 31) |
>            (op     << 30) |
>            (S      << 29) |
>            (0x22   << 23) |
>            (sh     << 22) |
>            (imm12  << 10) |
>            (Rn     <<  5) |
>             Rd;
> }
> ```
> That's just to initialize it. Never mind the shift/mask code to 
> read a fields, or change just one of the fields. There's a 
> large number of these functions in instr.d. Wouldn't it be 
> better with:
>
> ```
> struct addsub_imm { uint Rd:5, Rn:5, imm12:12, sh:1, x22:6, 
> S:1, op:1, sf: 1; }
> ```

Is there a guarantee that the bit pattern will match what the CPU 
expects?

I remember someone telling me that ["If you are still concerned 
about the layout, like you want a portable file format, don't use 
bit fields. Use 
std.bitmanip."](https://forum.dlang.org/post/usd5b3$23ni$1@digitalmars.com)

If you are going to use bitfields here, make sure you have tests 
to ensure the bit layout is as expected.

-Steve


More information about the Digitalmars-d mailing list