Size a primitive type to its alignment #62852
This function can be deleted and replaced with ispacked now that sizeof(T) is the same as aligned_sizeof(T).
thanks, done
For example primitive type Int24 <: Signed 24 end (which has been valid since at least Julia 1.0) is affected; that one goes from sizeof 3 to 4.
I think this will likely fix more packages than it will break. For example https://github.com/JuliaSIMD/Polyester.jl/issues/167
@mkitti 's package https://github.com/JaneliaSciComp/UInt12Arrays.jl might need some updates (the package tests are failing on both nightly and this PR).
I'm a little confused about what changed and when.
I think there might be a need to specify if a primitive should be aligned or packed.
Packed data is of particular interest for data that has been serialized to disk and where alignment may not be congruent with the primary objective of minimizing space.
@mkitti here is a fix for UInt12Arrays.jl https://github.com/JaneliaSciComp/UInt12Arrays.jl/pull/14
https://github.com/JuliaLang/julia/pull/62771 changed ReinterpretArray to use aligned_sizeof instead of sizeof for element size and with this PR sizeof is the same as aligned_sizeof for primitive types.
I think right now you would need to use a struct with UInt8 fields to make a 24 bit integer type with alignment of one byte.
@topolarity thanks for merging PR #62492 ! If you are up to it, here is my follow-up ;-)
`Base.elsize(Array{T})`. Bits past the declared width are padding and take no part in comparison
Base.aligned_sizeof is currently an internal function.
alignment rather than only up to a whole byte, so it always equals `Base.elsize(Array{T})`,
@nhz2 thanks, fixed
Thanks for this @fingolfin!
Changes largely look good to me. I think the intrinsics still need updating for the new padding bits IIUC (in particular, I think APINT_NBYTES is wrong now)
Got this together with Claude:
APINT_NBYTES itself is right: APInt reads and writes only the cld(N, 8) value bytes. The bugs were where a result becomes a sizeof-sized value, which now has padding:
FPtoInt copied sizeof bytes out of its word buffer, over-reading the stack (129 bits: 24-byte buffer, sizeof 32).
i24 into 4-byte boxes and stack slots, returned wide primitives through sret without their padding, and kept a C callee's sret padding as is.
db7c2d0715 and 2bb4429dd2 fix these, with tests that fail without the fixes.
Unfortunately this is not quite true.. Crazy as it is, the System V C ABI defines _BitInt(128) and int128_t to have different alignment.
Julia aligns Int128 to follow the int128_t convention, so its alignments diverge from BitInt for N > 64
Not really a bug, but APInt_sext should probably zero-pad rather than sign-pad since that is what we do in LLVM / everywhere else.
Claude 🤖 points out that static_constant_instance in cgutils also needs to be careful not to overread the (LLVM) APInt buffer for primitives with padding. I think the @cfunction sret fix is also incomplete - there's another pathway that still does a too-large store.
Thanks @topolarity, all four were real. An audit for the same class of bug found more, mostly older than this PR, so I split the work:
APInt_sext no longer sign-pads, and flipsign_int and out-of-range fptoui/fptosi clear the bits above the width too.
static_constant_instance copies only the APInt words, and a padded primitive no longer fuses the @cfunction sret with the callee's. The manual now says the _BitInt(N) match holds up to 64 bits, since wider types take Int128's alignment. Package images and compressed IR store the padding as zeros.
The size change also broke ccall's argument extension. It added signext/zeroext when sizeof < 4, so 17- to 24-bit types lost them once their sizeof became 4, although clang extends _BitInt(N) for N < 32 on most targets. It now decides by the width; RISC-V keeps sign-extending everything stored in 4 bytes, as clang does there.
Padding stays zero rather than sign-filled: C leaves it unspecified on x86-64 and AArch64, and zero does not depend on signedness, so it survives reinterpret between signed and unsigned types.
Does zext_struct_type also need to widen these primitive types? IIUC it still widens e.g. i17 to i24 ATM
FWIW I think the rollout of this is incomplete. We already write structs with non-zero'd padding bytes to serialized IR / heap objects IIUC.
We can try to clean that up of course (for determinism mostly?) but not sure the partial job is necessary until we do it completely
Yeah OK, agreed. I had Claude look into it and there are a bunch of places that would also need to be touched... but I think this is not the time and place to do it. So instead of doing ahead half-assed job, I'll instead drop it here, and then a follow-up PR can address this. Or, as Claude puts it: "canonicalizing all padding when serializing, nested fields and struct gaps included, belongs in its own PR"
Yes, in this fallback i17 still becomes i24. That happens when a tuple or struct is stored as one LLVM value, e.g. when it comes back from a non-inlined call: Claude checked that a Tuple{T17,UInt8} is then stored as store i24 plus store i8, so the 4th byte of the T17 field keeps whatever was there. Loads ignore that byte, so this is only about padding contents, same as the serialize question. Widening it here isn't straightforward: zext_struct_type only sees the LLVM type, and it is also used on memory coming from C, where e.g. a _BitInt(129) is smaller than our sizeof. So I'd leave that for a follow-up on padding.
I see - In that case, I think the only reason this exists is for Bool which is i1 but also !haspadding
I'm OK to leave it in this awkward state though. Maybe we can clean it up when we clean up Bool.
includes padding, while `Core.bitsizeof` does not.
for i in 1:div(Core.bitsizeof(T), 8, RoundUp)
or
cld if you prefer - just a suggestionThat said, I don't know if non_padding_bytes is well-defined for non-byte-multiple primitives. Might be good to error here for now.
The _BitInt(128) vs. uint128_t example might be more illustrative here, but just a suggestion
unsigned onumbits = jl_datatype_nbits(oty);
unsigned onumbytes = APINT_NBYTES(onumbits);
unsigned onumbytes_padding = jl_datatype_size(oty) - onumbytes;
// Bytes of a primitive type that hold value bits
too confusing to document one function by commenting on another IMO
"the callee need not define its padding" will probably be pretty cryptic when re-read outside of the context of this PR
out-of-date, IIUC
Changes look pretty good to me! Appreciate you keeping up this initiative.
Applied in afb8473a0f.
Switched to cld, and non_padding_bytes now throws an ArgumentError for types with bit padding, as its callers already did (270ea9b89e).
Good idea, done in ccad9f9b77; kept the 136-bit size example after it.
Done in bd71cfff66, naming the padding count opaddingbytes as in APInt_sext.
Done in d6715917a7.
Reworded in d6715917a7: the C function leaves the bits above N unspecified, so only the value bits are reloaded.
Removed in d6715917a7.
Right, fixed in d6715917a7: the _BitInt layout only matches up to 64 bits.
Agreed, let's do that together with Bool.
Follow-ups that came up in review are collected in https://github.com/JuliaLang/julia/issues/62441#issuecomment-5942312999
topolarity
fingolfin
First stab at addressing issue #61361. Would unblock item 2 of #62441.
Core.sizeofof a primitive type so far rounded its bit size up to the next multiple of 8. As a result, in many cases it was neither the allocation size nor the packed bit size. For example,primitive type T 17 endhadsizeof3 againstBase.aligned_sizeof4, where C23 givessizeof(unsigned _BitInt(17)) == 4. Triage settled on following C.Change the size of primitive types to
LLT_ALIGN(nbytes, alignment), soCore.sizeofandBase.aligned_sizeofnow agree. The trailing bytes are padding: we widenunused_bitsto hold up to8 * (MAX_ALIGN - 1) + 7. We only compare and hash the value bytes inprimitive_bits_equalandimmut_id_.Base.paddingreports the new trailing padding, and the packed-copy path learns to handle a type with no fields.On the upside, accessing an odd-bit integer (at least when used in isolation) now takes one power-of-two load or store instead of several sub-word ones. ABI-coerced register types keep their own width, since those may sit on a smaller object.
On the downside,
Core.sizeofchanges for some existing byte-multiple types. For exampleprimitive type Int24 <: Signed 24 end(which has been valid since at least Julia 1.0) is affected; that one goes fromsizeof3 to 4. This could break packages? Not sure if anyone uses that, though, perhaps @PatrickHaecker ? Anyway such types now returntruewhen passed todatatype_haspadding.Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
---
Note to reviewers: I have not yet de-sloppified comments, nor have I extensively reviewed this myself. I mainly post it here so people see I'm trying to tackle this; but of course if someone wants to give feedback, that's highly welcome.