mojo icon indicating copy to clipboard operation
mojo copied to clipboard

[Feature Request] SIMD bitcasts to different length SIMD types

Open lsh opened this issue 1 year ago • 3 comments

Similar to #182, when working with the SIMD types, it would be nice to have an easy conversion from something like UI32 to SIMD[DType.ui8, 4]. Aliases like UI8x4 might make sense if such conversions are allowed (and these would be sensible as they appear in many SIMD libraries).

lsh avatar May 18 '23 00:05 lsh

We made quite a bit of effort not to expose bitcasts in stdlib (at least readily accessible). Bitcasts are super dangerous and can create issues. There is a way to implement what you want above which is via

fn bitcast[target_type : AnyType, src_type : AnyType](src : src_type) -> target_type:
     var tmp = src
     let addr = Pointer[src_type].address_of(tmp)
     return addr.bitcast[target_type]().load()

abduld avatar May 23 '23 00:05 abduld

That makes sense. I would be satisfied with that decision as long as there is a constructor for SIMD[DType.ui8, N] for other SIMD types. It could potentially take a Endianness param (as mentioned in #285), there's also the option of just having a from_le_bytes/from_be_bytes method like Rust does.

lsh avatar May 29 '23 20:05 lsh

We do not have a Target info to query endieness at the moment, but you can use https://docs.modular.com/mojo/MojoStdlib/Bit.html#bitreverse to reverse bits

abduld avatar May 29 '23 21:05 abduld

I'm going to close this issue. Please file an issue for the Endianness feature

abduld avatar Jun 06 '23 18:06 abduld

We made quite a bit of effort not to expose bitcasts in stdlib (at least readily accessible). Bitcasts are super dangerous and can create issues. There is a way to implement what you want above which is via

fn bitcast[target_type : AnyType, src_type : AnyType](src : src_type) -> target_type:
     var tmp = src
     let addr = Pointer[src_type].address_of(tmp)
     return src.bitcast[target_type]().load()

@abduld should that read return addr.bitcast[target_type]().load() at the end(?) So that would be finally :

fn bitcast[target_type : AnyType, src_type : AnyType](src : src_type) -> target_type:
     var tmp = src
     let addr = Pointer[src_type].address_of(tmp)
     return addr.bitcast[target_type]().load()

gautam-e avatar Jun 12 '23 07:06 gautam-e

FYI: A bitcast functions was added https://docs.modular.com/mojo/stdlib/memory/unsafe.html#bitcast-2

abduld avatar Oct 13 '23 04:10 abduld