4 ms·
> branchiness Memorize the following concept / pattern. int select(int choice, int A, int B){ return (A & (~choice)) | (B & (choice)); } You
by dragontamer 4y ago
> branchiness
Memorize the following concept / pattern.
int select(int choice, int A, int B){
return (A & (~choice)) | (B & (choice));
}
You can convert any "if(bool)" statement into the above 4 assembly instructions: two ands, an or, and a not.
This performs a 32-bit way parallel "choice" operation. For example, "choice = 0x00000000" will choose all bits from A. "choice = 0xFFFFFFFF" will choose all bits from B.
SIMD because "choice = 0xFFFF0000" will choose the first 16-bits from B, and the last-16 bits from A.
------
Any data-operation can be "simulated" with enough code operations, and vice versa. Obviously, use code when code is needed, and data when data is needed. But sometimes, you need to perform a "code/data" switcheroo and the above pattern helps.
EDIT: It doesn't always work. The combinational explosion of data may prevent such a technique from working in the general case. But still, its a good first step and "most if statements" are simple enough to work with the above pattern.
- fanf2 4y agoFor loading the rag end of a string, the branchiness looks like while (len-- > 0) { /* load */ } or switch (len) { /* 8 cases */ } https://en.wikipedia.org/wiki/Duff%27s_device https://en.wikipedia.org/wiki/Duff%27s_device
- nwallin 4y agoSSE4.1 added `blend` which does this for most data types. The lone exception is 32 bit integers for whatever reason, which wasn't added until AVX2.