SmallChess
SmallChess

Reputation: 8146

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;
}

Upvotes: 1

Views: 923

Answers (1)

user555045
user555045

Reputation: 64913

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

q is the operand-size suffix for AT&T syntax, which is redundant because the register destination operand implies a size anyway.

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. See the gcc inline-asm docs, and the tag wiki.

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). (https://gcc.gnu.org/wiki/DontUseInlineAsm)

Upvotes: 10

Related Questions