Webcentive RISC-V Reference

cpopw

Count set bits in word

Extension
Zbb
XLEN
RV64 only
Assembly (riscv-unified-db)
cpopw xd, xs1
Length
32-bit

Encoding

3120191514121176210
011000000010rs1001rd0011011

Match 0x6020101b, mask 0xfff0707f. Source: cpopw rd rs1 31..20=0x602 14..12=1 6..2=0x06 1..0=3 in riscv-opcodes/extensions/rv64_zbb.

FieldBitsriscv-opcodes name
rs119:15rs1
rd11:7rd

Description

Counts the number of 1's (i.e., set bits) in the least-significant word of the source register.

Software Hint

This operations is known as population count, popcount, sideways sum,
bit summation, or Hamming weight.

The GCC builtin function `__builtin_popcount (unsigned int x)` is
implemented by cpop on RV32 and by cpopw on RV64. The GCC builtin
function `__builtin_popcountl (unsigned long x)` for LP64 is
implemented by cpop on RV64.

Description from riscv-unified-db, reformatted.

Operation

XReg bitcount = 0;
XReg xs1_val = X[xs1];

for (U32 i=0; i < 32; i++) {
  if (xs1_val[i] == 1'b1) {
    bitcount = bitcount + 1;
  }
}

X[xd] = bitcount;

Pseudocode in riscv-unified-db’s IDL, quoted unchanged.

Specification and related pages