1
votes

I'm currently trying to use the builtin popcnt in order to count the number of 1's in an array of unsigned char.

I had the function working with the regular __builtin_popcount but with some more aggressive speed requirements, I decided to go with the inline asm approach.

size_t popcnt_manual( unsigned char *bytes, size_t len ) {
    size_t i, cnt = 0;
    for( i = 0; i < len; i++ ) {
        __asm__(
                 "popcnt %0, %0    \n\t"
                 "add    %0, %1    \n\t"
                 : "+r" (cnt)
                 : "r"  (bytes[i]));
    }

    return cnt;
}

And the compiler keeps saying

suffix or operands invalid for add

1

1 Answers

2
votes

Aside from the syntax error in your code (" "r" -> : "r"), your problem is mismatched parameters.

Looking at the output from -S:

 add    rax, r8b

Since cnt is size_t and bytes[i] is a byte, this is what you'd expect. Add requires them to be the same size.

Can I also suggest using builtins instead of inline asm? It avoids problems like this (as well as many others).


Is there any way to add up the result from popcnt without storing it off in a register first?

Umm. That's actually an entirely different question. The error you were asking about is due to mixing a byte and a size_t in a single add instruction. It can be resolved by doing:

    __asm__(
             "popcnt %0, %0    \n\t"
             "add    %0, %1    \n\t"
             : "+r" (cnt)
             : "r"  ((size_t)bytes[i]));

I shouldn't encourage you to keep adding new questions (how will I get my karma points?), but looking at that website, the code he seems to be messing with is this:

uint32_t builtin_popcnt_unrolled_errata(const uint64_t* buf, int len) {
  assert(len % 4 == 0);
  int cnt[4];
  for (int i = 0; i < 4; ++i) {
    cnt[i] = 0;
  }

  for (int i = 0; i < len; i+=4) {
    cnt[0] += __builtin_popcountll(buf[i]);
    cnt[1] += __builtin_popcountll(buf[i+1]);
    cnt[2] += __builtin_popcountll(buf[i+2]);
    cnt[3] += __builtin_popcountll(buf[i+3]);
  }
  return cnt[0] + cnt[1] + cnt[2] + cnt[3];
}

He is explicitly using cnt[x] in an attempt to avoid the 'false dependency' problem of popcnt.

Using gcc 6.1 and compiling with -m64 -O3 -march=native -mtune=native, I'm seeing this as output:

.L14:
        popcnt  r11, QWORD PTR [rcx]
        add     rcx, 32
        add     edx, r11d
        popcnt  r11, QWORD PTR -24[rcx]
        add     eax, r11d
        popcnt  r11, QWORD PTR -16[rcx]
        add     r10d, r11d
        popcnt  r11, QWORD PTR -8[rcx]
        add     r9d, r11d
        cmp     rcx, r8
        jne     .L14

Which "storing it off in a register" are you referring to?