Student T Student T - 6 days ago 8
C Question

What does this LSB function do?

I have the following code which I think (but not 100% sure) computes the LSB of a given 64-bit integer.

Unfortunately, I don't understand the implementation. What is

bsfq
? What is
=r
?

static inline unsigned lsb(uint64_t b)
{
size_t idx;
__asm__("bsfq %1, %0": "=r"(idx): "rm"(b));
return idx;
}

Answer

BSF finds the index of the lowest set bit, if there is any.

The = in =r is a modifier saying that the register is overwritten. The r means it must be a register. rm can be a register or a memory operand.

I would recommend that you replace this by __builtin_ffsll, since the compiler can reason about that but not about inline assembly (apart from whatever it can tell from the constraints/clobbers).