6 ms·
The core of the algorithm shows that UTF-8 is actually big-endian in its ordering of the bits, making it somewhat more difficult to implement efficiently on the
by userbinator 9y ago
The core of the algorithm shows that UTF-8 is actually big-endian in its ordering of the bits, making it somewhat more difficult to implement efficiently on the usual little-endian machine --- the first byte, at the lowest address, actually contains the most sigificant bits. Had it been the other way around, the final shift would not be length-dependent.
Also, none of the compilers I tried at https://godbolt.org/ https://godbolt.org/ were able to combine the 4 s[0...3] 8-bit reads into one 32-bit read, which is somewhat disappointing. They generated 4 separate byte-read instructions, one for each s[0..3]. Yes, I know it could be unaligned, but this is x86 where it would still be faster than 4 separate reads. You would need to do this instead (and sacrifice endianness/alignment-independence):
uint32_t v = *(uint32_t*)s;
*c = (uint32_t)(v & masks[len]) << 18;
*c |= (uint32_t)((v>>8) & 0x3f) << 12;
*c |= (uint32_t)((v>>16) & 0x3f) << 6;
*c |= (uint32_t)((v>>24) & 0x3f) << 0;
*c >>= shiftc[len];
We're still left with a bunch of shifts, ands, and ors, the purpose of which is to essentially "compact" the 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx bitstring into one 21-bit codepoint by removing the bits in the middle. All the compilers I tried weren't so clever as to do this (assuming eax = v from above after masking, and cl = slightly modified shiftc[len]) at any optimisation level:
bswap eax
mov ebx, eax
and ebx, 00FF00FFh
lea ebx, [ebx + ebx*2]
add eax, ebx
shr eax, 2
shl ax,4
shr eax, cl
I played around with optimising UTF-8 decoding a while ago, and the above resembles one of the fastest and smallest ways to "compact" the 4 bytes into a codepoint.
Of course, this bit string manipulation would be much faster and trivial in hardware (essentially rearranging wires), which makes me want a LODSUTF8 instruction that operates like LODSB but reads a whole codepoint instead, and sets CF on error...
- Dylan16807 9y ago> Yes, I know it could be unaligned, but this is x86 where it would still be faster than 4 separate reads. You have to worry about memory access violations too.
- zAy0LfpBZLC8mAC 9y agoWhere in the C standard are memory access violations specified as a language feature?!
- Dylan16807 9y agoIf you're worried about the actual C standard then you hit undefined behavior the moment you dereference a uint32_t* pointing to data that's actually char.
- zAy0LfpBZLC8mAC 9y agoWhich doesn't prevent the compiler from doing a 32 bit load, does it? Dereferencing a pointer to a location outside any object is also undefined, therefore, if there are no conditionals between subsequent byte reads, the compiler should be perfectly fine with combining them into a 32 bit load!?
- fourthark 9y agoThe issue is that once you hit undefined behavior, the optimizer is allowed to do whatever it wants - the proverbial launch nukes, crash, raid your fridge, etc. More likely, it could just not execute that instruction or any instruction that depends on it, because that's the fastest way to preserve undefined behavior.
- zAy0LfpBZLC8mAC 9y ago> The issue is that once you hit undefined behavior, the optimizer is allowed to do whatever it wants - the proverbial launch nukes, crash, raid your fridge, etc. That's not quite how it works, or at least not what usually happens. Optimizers don't look for undefined behaviour to then do whatever, they look for the set of defined behaviours and then try to generate the cheapest code that behaves correctly in all those cases--and if that means that undefined cases do weird stuff, that's an acceptable side effect. That in particular means that the potential for undefined behaviour to occur at runtime does not make the program undefined. If you ask the user to input a number and you then use that number as an index into some array without any input validation, the user could enter an out-of-range index, in which case the behaviour of the program would be undefined. But if the user inputs a valid index, the program must not exhibit any undefined behaviour. Therefore, yes, if any of the bytes are not inside any valid C object, then that would produce undefined behaviour. Which is precisely why the compiler would be allowed to combine the loads into one 32-bit load: As the code, if it takes that path, is going to load all four bytes, and accessing a byte outside any objects would result in undefined behaviour, the compiler may assume that all accesses are within valid objects, and therefore loading them all in one is correctness-preserving.
- userbinator 9y agoFrom the article: "One important consequence of always reading four bytes is that the caller must zero-pad the buffer to at least four bytes. In practice, this means padding the entire buffer with three bytes in case the last character is a single byte." In other words, both the byte-by-byte and dord-at-a-time code assume none of the bytes being read will be at an invalid address.
- Dylan16807 9y agoOh, sorry, I was confused about what exactly you were replacing.
- revelation 9y agoProcessors will never read anything under a cache line, so it doesn't really matter (as memory access goes)
- deleted 9y ago[deleted]
- wolf550e 9y agoYou have to use memcpy with length 4 to read that uint32_t from something that was a char pointer, those casts are not allowed anymore. On x86 it would become a single mov instruction.
- Cyph0n 9y agoAre you sure about this? I did this recently in C++ and it worked fine: cast a uint8_t* to a uint32_t* and read data as 32 bit ints. I had to use reinterpret_cast in C++ though and of course I had to swap words to get the correct ordering.
- hsivonen 9y agoPretty sure it's UB if the uint32_t* doesn't point to a correctly-aligned address. (IIRC, just computing the unaligned pointer is already UB before you dereference it.) On x86, the code might appear to work, though, if you don't happen to trigger autovectorization. The correct way to do an unaligned read is memcpy.
- wolf550e 9y agoI think even if you happen to know that the address is always aligned, but the compiler can't tell that it's guaranteed to be always aligned, the compiler can miscompile the code. Even without autovectorization.
- wahern 9y agoIf it's correctly aligned it will always work. The compiler must assume that your cast declares the proper type and behave accordingly. This is fundamental to C and (AFAIU) C++. The cast is the final word on the matter, but it's up to you to ensure the cast is telling the truth, the whole truth, and nothing but the truth. What the compiler cannot glean from casts are alias relationships, which are important for ensuring the order of operations are correctly maintained. As long as you're not mutating aliased objects, it's irrelevant. But if you are mutating aliased objects, you usually should derive the alias through a union with an in-scope definition. That way the compiler, by backtracking the derivation of the reference through the union, will recognize that the two objects of different types alias and ensure that loads and stores are properly ordered. Another way to signal alias relationships relevant to UTF-8 decoding is through pointers to char or unsigned char. Those types can legally alias anything, and the compiler must take note. Sometimes it's useful to cast an address to, e.g., (char *) even when using memcpy(), even though it's unnecessary in C for the immediate expression because of automatic void pointer conversions. I can't think of a concrete example at the moment to explain the point, but it's something to keep in mind. Note that int8_t and uint8_t are not necessarily the same type as char or unsigned char, even when they have the same representation, and thus aren't required to express to the compiler the possibility of aliasing with other types (that is, mutating a uint8_t object doesn't necessarily tell the compiler that another object of type uint32_t might have been mutated, while mutating an unsigned char object would have in the same context).
- bdonlan 9y agoOne thing you could do to optimize further (on CPUs with the BMI2 instruction set) is to use the PEXT instruction to perform the bit extract operation (after a BSWAP of course). The whole operation could be something like (untested): ; Parameters: RDI - pointer to input character ; Return value: RAX - Unicode codepoint, or -1 for error lea r8, [encoding_table] ; Load pointer to table base using rip-relative addressing mov edx, [rdi] ; unaligned (over)read of 32-bit utf8 codepoint mov ebx, edx ; Copy to EBX to construct our table index and ebx, 0xf8 ; Mask off the (potential) data bits ; Now we want to convert the top 5 bits into an index into a table of three * 32-bit entries ; Currently EBX = index * 8, we need index * 12, so we'll divide by two and then multiply by 3 shr ebx, 1 lea ebx, [ebx + ebx * 2] bswap edx ; Get the codepoint into big-endian representation pext ecx, edx, [ebx + 4] ; extract padding bits using mask pext eax, edx, [ebx] ; extract data bits cmp ecx, [ebx + 8] ; check padding bits cmovnz eax, -1 retq encoding_table: ; 00000xxx - 01111xxx times 16 dd 0x7F, 0x80, 0x00 ; 10000xxx - 10111xxx (invalid) times 8 dd 0, 0xFFFFFFFF, 0 ; The padding will never match here, forcing an error return ; 11000xxx - 11011xxx (two bytes) - padding value 11010 times 4 dd 0x1F3F, 0xE0C0, 0x1A ; 11100xxx - 11101xxx (three bytes) - padding value 1110 1010 times 2 dd 0x0F3F3F, 0xF0C0C0, 0xEA ; 11110xxx (four bytes) - padding value 111 1010 1010 dd 0x073F3F3F, 0xF8C0C0C0, 0x7AAAA
- goldenkey 9y agoPretty cool, a recent development, only in Haswell and later architectures (2013 and later.) https://en.m.wikipedia.org/wiki/Bit_Manipulation_Instruction_Sets https://en.m.wikipedia.org/wiki/Bit_Manipulation_Instruction...
- userbinator 9y ago...and on the Haswell PEXT runs in one uop with a latency of 3! That is nothing short of amazing for an operation which, from its description, would seem to require a microcode loop or at least a few more cycles to collect an arbitrary number of bits with arbitrary gaps between them: http://www.felixcloutier.com/x86/PEXT.html http://www.felixcloutier.com/x86/PEXT.html The only unfortunate thing is that it was introduced quite recently in terms of x86 history (instead of being present early on but just microcoded), so earlier software can't take advantage of it nor any subsequent improvements, and uses a pretty complex encoding (VEX) only usable in protected mode. But if anything, this is another datapoint in the argument in favour of CISC --- try doing this on a MIPS, RISC-V or even ARM! With less powerful ISAs, even something as simple as the "shl ax, 4" (shift the lower 16 bits only) turns into a multi-instruction sequence of masking and combining.
- sounds 9y agoI've been puzzling over your assembly code for a while. Assuming you just had the useful bits in eax and had just executed bswap: MSB .... byte1... byte2... LSB 00000xxx 00xxxxxx 00xxxxxx 00xxxxxx How does multiplying (byte1 | LSB) * 3 help? I'm asking about lea ebx, [ebx + ebx*2], which is a shortcut for multiplying by 3. Genuinely lost here, the 6 bits of byte1 and the 6 bits of LSB are separated by enough 0 bits that a multiplication by 3 won't mix them up. But within the 6 bits of byte1 and within the 6 bits of LSB, the multiplication will mean each bit is the sum of itself, the lower order bit, and any carried bits. What is that for? Thanks for any tips!
- userbinator 9y agoThe hint is to look at the next instruction. Spoiler: https://pastebin.com/msjkXkKd https://pastebin.com/msjkXkKd
- deleted 9y ago[deleted]
- sounds 9y agoYes, that makes sense now. Thanks! Edit: I fiddled around a bit and came up with: https://pastebin.com/WA1Tp2KK https://pastebin.com/WA1Tp2KK The nullprogram.com version is 0x185 bytes (gcc 4.8.4 x86_64 -O3; objdump -s -j .text -j .rodata) I switched to __builtin_clz (with cross platform support). I hesitate to put in your assembly code, though it would work great! My version still sticks to C and not inline assembly. My version takes 0xeb bytes. Benchmarking with clang-802.0.42 -O3 -march=native on a Core i7-4770HQ @ 2.20GHz: branchless: 490.666725 MB/s, 0 errors 0xeb small: 352.000042 MB/s, 0 errors Hoehrmann: 337.333374 MB/s, 0 errors With gcc 4.8.4 -O3 -march=native on a Xeon E5-1650v3 @ 3.50GHz: branchless: 436.000052 MB/s, 0 errors 0xeb small: 345.333375 MB/s, 0 errors Hoehrmann: 412.000049 MB/s, 0 errors [1] https://stackoverflow.com/questions/19527897/how-undefined-are-builtin-ctz0-or-builtin-clz0 https://stackoverflow.com/questions/19527897/how-undefined-a...
- sounds 9y ago