Diary Of An x264 Developer

05/16/2008 (11:43 pm)

Write combining

Filed under: gcc,speed,ugly code,x264 ::

Let’s say we need to copy a few variables from one array to another. The obvious way is something like this:

byte array1[4] = {1,2,3,4};
byte array2[4];
int i;
for(i = 0; i < 4; i++) array2[i] = array1[i];

But this is suboptimal for many reasons. For one, we’re doing 8-bit reads and writes, which on 32-bit systems may actually be slower than 32-bit reads and writes; i.e. a single 32-bit read/write may be faster than a single 8-bit read/write. But the main issue is that we could be doing this:

DECLARE_ALIGNED_4(byte array1[4] = {1,2,3,4});
DECLARE_ALIGNED_4(byte array2[4]);
*(uint32_t*)array2 = *(uint32_t*)array1;

In a single operation instead of 4, we just copied the whole array. Faster speed-wise and shorter code-wise, too. The alignment is to ensure that we don’t copy between unaligned arrays, which could crash on non-x86 architectures (e.g. PowerPC) and would also go slightly slower on x86 (but still faster than the uncombined write). But, one might ask, can’t the compiler do this? Well, there are many reasons it doesn’t happen. We’ll start from the easiest case and go to the hardest case.

The easiest case is a simple zeroing of a struct (say s={a,b} where a and b are 16-bit integers). The struct is likely to be aligned by the compiler to begin with and writing zero to {a,b} is the same as writing a 32-bit zero to the whole struct. But GCC doesn’t even optimize this; it still assigns the zeroes separately! How stupid.

The second-easiest case is the generalization of this; if you’re dealing with arrays in which the function is directly accessing them (rather than pointers to arrays, which it might not know whether they’re aligned or not) and assigning zero or constant value, write-combining is trivial. But again, GCC doesn’t do it.

Now, we get to the harder stuff. What if we’re copying between two arrays, both of which are directly accessed? Now, we have to be able to detect this sequential copying and merge it. This basically is a simple form of autovectorization; its no surprise at all that GCC doesn’t do this.

The hardest, and in fact nearly impossible case is the one in which we’re dealing with pointers to arrays as arguments; the compiler really has no reliable way of knowing that the pointers are aligned (though we as programmers might know that they always are). There are cases where it could make accurate derivations (by annotating pointers passed between functions) as to whether they are aligned or not, in which case it might be able to do write combining; this would of course be very difficult.  Of course, on x86, its still worthwhile to combine even if there’s a misalignment risk, since it will only go slightly slower rather than crash.

The end result of this kind of operation is a massive speed boost in such functions; for example, in the section where motion vectors are cached (in macroblock_cache_save) I got over double the speed by converting 16-bit copies to write-combined copies. This of course is only on a 32-bit system; on a 64-bit system we could do even better. The code of course uses 64-bit so that a 64-bit compiled binary will do it as best it can. The compiler is smart enough to split the copies on 32-bit systems, of course.

We could actually do even better if we were willing to use MMX or SSE, since MMX could be used for 64-bit copies on 32-bit systems and SSE could be used for 128-bit copies. Unfortunately, this would completely sacrifice portability and at this point the speed boost would be pretty small from the current merged copies.

One of the big tricks currently is the ability to treat two motion vectors as one, and since all motion vectors come in pairs (X and Y, 16-bit signed integers each), its quite easy to manipulate them as pairs. This allowed me to drastically speed up a lot of manipulation involved in motion vector prediction and general copying and storing. The result of all the issues described in the article is this massive diff.

19 Responses to “Write combining”

  1. imcold Says:

    I’m using a similar trickery in evk when checking if block consists only of zeros by treating two int16 coefs as one int32 (4 coefs as int64 would be even better, of course, but the codec doesn’t compile in 64bit so easily… yet). Not quite related, but: what role does the macroblock_cache_*** have and how is it used?

  2. Dark Shikari Says:

    We use the same thing in array_non_zero(), which uses 64-bit ints to check if an array is zero or not. This is actually faster on 32-bit than a 32-bit solution, because the compiler compiles it as two 32-bit values or’d together.

    macroblock_cache_load loads all variables necessary for analysis and encoding (both pixel values of the current block and neighboring pixels, plus variables about neighboring blocks, etc) into the cache, and cache_save stores all such variables that resulted from choices made in analysis (e.g. motion vectors). Oh, and “cache” doesn’t mean CPU cache, it means a struct that stores such values (though one would expect it would be in the L1 cache!)

  3. Lexor Says:

    This isn’t very informative without knowing what DECLARE_ALIGNED does. It is too early where I am, but doesn’t you solution only points array2 to where array1 is? That’s not what the purpose of original code, original code makes second copy. Why not just do:

    memcpy(array2, array1, 4*sizeof(byte)); //or memmove if arrays overlap in memory

  4. imcold Says:

    That’s quite clever. Sadly it doesn’t apply to fpc; if i use int64, it generates two test & jne pairs instead (one pair with int32, just like gcc). I think it could be a bit faster since it makes fewer iterations, but I guess the removal of half of the jumps is much more beneficial.

    I will have a look at the cache soon (well, deeper look into x264 generally), just need to pass few exams first :) I currently load the pixels for current mb from encoded frame into separate memory before encoding too, I guess it’s somewhat similar in x264, but with much more stuff cached.

  5. Dark Shikari Says:

    Lexor, DECLARE_ALIGNED is just a shortcut to the GCC alignment intrinsic. The code does not point one array to another, it copies them; please read up on pointers again ;) . Memcpy would work, but that seems even uglier for this case given the very small copies.

  6. astrange Says:

    x86 doesn’t care about alignment for stores of anything below 128-bit, so that shouldn’t matter. Actually, it might make it worse, since gcc will copy the alignment padding too…

    Anyway, it write-combines structs fine for me, but not arrays.

    struct two_members {
    short a,b;
    } s1, s2;

    void a() {s1 = s2;}

    void b() {s1 = (struct two_members){0};}

    arr a1 = {1, 2, 3, 4}, a2;

    void c() {int i; for (i = 0; i < 4; i++) a1[i]=a2[i];}

  7. Ramiro Polla Says:

    What about gcc 2.95? It’s impressive how much smarter that compiler was than the 3 and 4 series for such optimizations…

  8. Lexor Says:

    Yeah I see what the code does now, clever, kinda like using base3 arithmetic so that the result of multiplying two 32 bit base10 integers is guaranteed to fit into 32 bits (Maple used to do that).

    Also I suggested memcpy because I didn’t realize that this small case is actually the intended use, I thought it was just for illustration’s sake. I automatically extended the problem to the common case in which I’d encounter it (with annoyance, in someone else’s code). That is copying an array of at least 100k doubles… at that point trying to outsmart memcpy (and it’s ilk as the case at hand may dictate) becomes an adventure in annoyance and failure.

  9. iive Says:

    The originally presented code have some portability problems. It causes warnings (breaking strict aliasing, i think). It would break in many ways when some type changes. Not saying that it is not always clear what it does. (As already illustrated above).

    Using memcpy() is preferable. The gcc is supposed to use its internal implementation and it should be additionally optimized if it is of constant size.

    The alignment won’t always work, as gcc < 4.2 are know not to align when variables are local (in the stack). In this case however it may work as gcc always aligns to 4 bytes, but for SSE that needs 8, it may be troublesome.

    Anyway there is simple solution.
    It is much simpler to define the array as struct and do simple assignment. aka:

    typedef struct {int8_t array[4];} mv_a;
    mv_a a,b;
    a=b;

    I hope wordpress doesn’t mangle my small buggy snippet.

    The compiler would align and pad the structs (if needed) and would do memcpy with their correct size using full machine words.
    The only problem is that you would have to write a.array[i] instead of a[i];

    Zeroing structure is
    memset(&a,0,sizeof(a));

    This would also zero the padding, so you won’t get “use of uninitialized memory” when doing memcpy under valgrind.

  10. Pengvado Says:

    > It causes warnings (breaking strict aliasing, i think).

    No warnings here. Which doesn’t mean that it doesn’t break strict aliasing, only that gcc can’t determine that it is aliased. (Does that imply that it also didn’t perform any optimizations that could break? It should, but you can never be sure when it comes to gcc.)
    I’ll do whatever it takes to generate fast code. And if that means disabling strict aliasing because gcc can’t make use of it anyway, so be it.

    > Using memcpy() is preferable.

    Works on x86, but how does gcc know what alignment my pointer really has on archs that need alignment? (Not having a non-x86 box, I can’t test whether gcc honors __attribute__((align)) in pointer declarations.)

    > The alignment won’t always work, as gcc 4 on the stack, regardless of whether you ask for alignment or not.

    Old gcc are known not to align scalar variables, and assume the stack itself is aligned (which the x86_32 abi doesn’t guarantee, but x264 does). Alignment of arrays worked as far back as I can remember. Or rather, gcc always 16-byte aligns arrays of size>4 on the stack, regardless of whether you ask for alignment or not.

    > It is much simpler to define the array as struct and do simple assignment.

    I thought of that too, and suggested it before Dark Shikari went on to write this patch. But in fact it doesn’t work. While your particular example is correctly optimized, as of gcc-4.2.3 any struct assignment via pointer gets compiled to individual assignments of the struct members, i.e. what we had before.

    > This would also zero the padding, so you won’t get “use of uninitialized memory” when doing memcpy under valgrind.

    Valgrind warns about use (branches, print, etc), never intermediate values. So memcpy can’t trigger a warning.

  11. iive Says:

    >as of gcc-4.2.3 any struct assignment via pointer gets compiled to individual assignments of the struct members, i.e. what we had before.

    I wasn’t able to create code that my own gcc-4.2.3 would miscompile in such way. The sample code was correctly optimized even on 2.95.4 (yeh debian).

    I can’t think of reason for this to not work. (even on arch that require alignment)

  12. Pengvado Says:

    ~> gcc –version
    gcc (GCC) 4.2.3 (Gentoo 4.2.3 p1.0)
    ~> cat foo.c
    typedef struct {int8_t array[4];} mv_a;
    mv_a a,b;
    void foo0() { a=b; }
    void foo1(mv_a *c, mv_a *d) { *c=*d; }
    ~> gcc -O3 -fomit-frame-pointer -c foo.c -o foo.o ; objdump -d foo.o
    0000000000000000 :
    mov eax,[rip+0x0]
    mov [rip+0x0],eax
    ret

    0000000000000010 :
    movzx edx,[rsi+0x2]
    movzx ecx,[rsi+0x1]
    movzx r8d,[rsi]
    movzx eax,[rsi+0x3]
    mov [rdi+0x2],dl
    mov [rdi+0x1],cl
    mov [rdi+0x3],al
    mov [rdi],r8b
    ret

    … -O1, -O2, -O3 all fail, but -Os works. So it seems not that gcc can’t perform that optimization, but that it thinks multiple stores are faster?

  13. astrange Says:

    -Os turns off the SRA pass which splits struct operations into member operations. This is usually really good since you can put all the members in registers, but that one’s not really helpful.

  14. iive Says:

    Your code is x86_64. In my test I didn’t specify architecture and it assumed i386 (32bit). The above wrong behavior seems to be triggered on any arch above i586 and -O3.

    I guess you have found another bug in gcc.

    Don’t forget to fill bugreport. Just like you, they consider that there is no bug if nobody complains. ;)

    BTW,
    Oh, gcc-2.95.4 works correctly with -march=i686. One more reason to keep support for it ;)

  15. astrange Says:

    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=36318

    regressions existing since 4.0 are pretty low priority though

  16. Shadowrun Says:

    Any good books talking about alingments and optimizing code?

    Thanks.

  17. delacroixP Says:

    Perhaps we should call on Dave Cutler to give us a hand !
    Nice to see you guys getting dirty with assembler… hopefully X264 will gain that extra mile.

    It’s all good !

    :) :devil::D
    Pascal

  18. woefulwabbit Says:

    What about using a union?

    typedef union {
    byte array[4];
    uint32_t dword;
    } bytes4;

    bytes4 array1, array2;
    array1.array = {1, 2, 3, 4};
    array2.dword = array1.dword;

  19. tufei Says:

    To make it more accurate on the aligned access of PowerPC from

    http://www.ibm.com/developerworks/library/pa-dalign/

    “The PowerPC takes a hybrid approach. Every PowerPC processor to date has hardware support for unaligned 32-bit integer access. While you still pay a performance penalty for unaligned access, it tends to be small.

    On the other hand, modern PowerPC processors lack hardware support for unaligned 64-bit floating-point access. When asked to load an unaligned floating-point number from memory, modern PowerPC processors will throw an exception and have the operating system perform the alignment chores in software. Performing alignment in software is much slower than performing it in hardware.”

    That is why there is no issue on PPC when the NAL is written in x264 as 32-bit words, instead of 8-bit bytes, although unaligned access is unavoidable when writing NALs.

    This is one of the reasons that people complained that SPARC does not work since it throws exception in NAL writing.

    On TI’s C64 it is actually more painful. It does support un/aligned accesses with different instructions. However, its compiler always assume aligned access. What is worse is that when there is unaligned access, the compiled code will not throw an exception, it simply truncates the address to make the address itself aligned, *silently*. That causes more trouble. If one really wants unaligned access on C64, s/he needs inline assembly or intrincs to use the unaligned access instructions.

Leave a Reply