Webcentive RISC-V Reference

cpop

Count set bits

Extension
Zbb
XLEN
RV32 and RV64
Assembly (riscv-unified-db)
cpop xd, xs1
Length
32-bit

Encoding

3120191514121176210
011000000010rs1001rd0010011

Match 0x60201013, mask 0xfff0707f. Source: cpop rd rs1 31..20=0x602 14..12=1 6..2=0x04 1..0=3 in riscv-opcodes/extensions/rv_zbb.

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

Description

Counts the number of 1's (i.e., set bits) in 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 < xlen(); 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