4

I'm porting some code from Rust to Swift and I noticed they use pext method to do some bit manipulation. Since it's an Intel instruction I can't get that into my Swift code so I was wondering what set of bitwise instructions (that I can use in Swift) would be able to get the same result as a PEXT operation.

For more context, here is a description of PEXT

Basically it uses a mask that maps high order bits to contiguous lower order bits and clears the higher order bits in the final output. Example:

source = 1011 1110 1001 0011
mask =   0110 0011 1000 0101 

s = pext(source, mask)

s -> 0000 0000 0011 0101 

I know replicating an advanced instruction is a performance hit but I'm really just trying to get the code to work.

phuclv
  • 37,963
  • 15
  • 156
  • 475
swigganicks
  • 1,109
  • 2
  • 14
  • 28
  • 1
    [Shift masked bits to the lsb](https://stackoverflow.com/q/28282869/995714), [pack the bits based on arbitrary mask](https://stackoverflow.com/q/41617369/995714)and [the reverse](https://stackoverflow.com/q/47692902/995714) – phuclv Jan 23 '18 at 05:41
  • Well, there're two built-in functions named `_pext_u32` and `_pext_u64` in Swift, but they're defined for Intel architecture only. – user28434'mstep Jan 23 '18 at 08:48
  • @user28434 how do you access those in swift? I can't find them – swigganicks Jan 23 '18 at 14:10
  • @swigganicks, it's in `simd` module. – user28434'mstep Jan 23 '18 at 15:13
  • @LưuVĩnhPhúc The first "shift masked bits to the lsb" aka "compress right" is all I need right? What are the other two operations you linked for? – swigganicks Jan 23 '18 at 15:57
  • 1
    [Standard C++11 code equivalent to the PEXT Haswell instruction (and likely to be optimized by compiler)](https://stackoverflow.com/q/21144237/995714) – phuclv Aug 21 '18 at 01:45

1 Answers1

1

@LưuVĩnhPhúc answer was correct. It's wildly inefficient on non-Intel architecture though so I would advise others looking to incorporate BMI2 instructions into Swift code to only do so when targeting macOS

swigganicks
  • 1,109
  • 2
  • 14
  • 28