Saw this when randomly flipping through the code base of something posted to Lobsters. C or C++ is not the language for you if you think you can write code like that.
https://c.godbolt.org/z/8q5zoh6Ke
Compiler Explorer - C (x86-64 gcc 15.2)
// https://github.com/abdimoallim/jit
typedef int32_t i32;
typedef uint8_t u8;
typedef size_t usz;
typedef struct {
u8* buf;
usz len;
} jit_buf;
void jit_ensure(jit_buf* j, usz n) {}
// bad
void jit_emit_i32(jit_buf* j, i32 v) {
jit_ensure(j, 4);
j->buf[j->len + 0] = (u8)(v);
j->buf[j->len + 1] = (u8)(v >> 8);
j->buf[j->len + 2] = (u8)(v >> 16);
j->buf[j->len + 3] = (u8)(v >> 24);
j->len += 4;
}
// good
void jit_emit_i32_fixed(jit_buf* j, i32 v) {
jit_ensure(j, 4);
u8* buf = j->buf;
usz len = j->len;
buf[len + 0] = (u8)(v);
buf[len + 1] = (u8)(v >> 8);
buf[len + 2] = (u8)(v >> 16);
buf[len + 3] = (u8)(v >> 24);
j->len = len + 4;
}
int main() {}
There's a certain systems language with pervasive noalias guarantees where you can write code like that but C is assuredly not that language.
@pervognsen Isn't this one of the cases that strict aliasing optimizations are supposed to enable?
@nothings Not in this case. A store via a char pointer is expressly allowed to alias any type.
@pervognsen @nothings Both GCC & clang produce the desired if 'restrict' is added to the jit_buf pointer. That seems "wrong" to me.
https://c.godbolt.org/z/6sGsh7xnY

Compiler Explorer - C
// https://github.com/abdimoallim/jit
typedef int32_t i32;
typedef uint8_t u8;
typedef size_t usz;
typedef struct {
u8* buf;
usz len;
} jit_buf;
void jit_ensure(jit_buf*j, usz n) {}
// bad
void jit_emit_i32(jit_buf* j, i32 v) {
jit_ensure(j, 4);
j->buf[j->len + 0] = (u8)(v);
j->buf[j->len + 1] = (u8)(v >> 8);
j->buf[j->len + 2] = (u8)(v >> 16);
j->buf[j->len + 3] = (u8)(v >> 24);
j->len += 4;
}
// seems wrong to me
void jit_emit_i32_humm(jit_buf* restrict j, i32 v) {
jit_ensure(j, 4);
j->buf[j->len + 0] = (u8)(v);
j->buf[j->len + 1] = (u8)(v >> 8);
j->buf[j->len + 2] = (u8)(v >> 16);
j->buf[j->len + 3] = (u8)(v >> 24);
j->len += 4;
}
// good
void jit_emit_i32_fixed(jit_buf* j, i32 v) {
jit_ensure(j, 4);
u8* buf = j->buf;
usz len = j->len;
buf[len + 0] = (u8)(v);
buf[len + 1] = (u8)(v >> 8);
buf[len + 2] = (u8)(v >> 16);
buf[len + 3] = (u8)(v >> 24);
j->len = len + 4;
}
int main() {}