The SWAR population count sums the bits field by field without carries between fields full
This proof shows: correctness.
Fix w∈{8,16,32,64,128}. A word is an integer 0≤x<2w with bits xt. For a field width f that divides w, the field i of a word y is Fif(y)=⌊y/2fi⌋mod2f, for 0≤i<w/f, so y=∑iFif(y)2fi. Let x0 be the input, and let νif=∑t=fifi+f−1(x0)t be the number of 1-bits of x0 in field i of width f. Note νi2f=ν2if+ν2i+1f.
Tool (addition by fields). Let f divide w, and let a=∑iai2fi and b=∑ibi2fi with 0≤ai,bi and ai+bi<2f for each i. Then a+b=∑i(ai+bi)2fi<2w, and Fif(a+b)=ai+bi. Proof. The sum is the stated series by the distributive law. Each coefficient ai+bi lies in [0,2f), so the series is the base-2f expansion of a+b, its fields are the coefficients, and the value is at most ∑i(2f−1)2fi=2w−1. So no reduction modulo 2w happens. □
The same argument with ai≥bi≥0 gives Fif(a−b)=ai−bi and 0≤a−b<2w.
Step L1. Let x=x0, f=2. The word (x≫1)∧M1 has field i equal to (x0)2i+1: the shift moves bit 2i+1 to position 2i, and M1 keeps exactly the even positions. Field i of x is 2(x0)2i+1+(x0)2i≥(x0)2i+1. By the subtraction form of the tool, field i of the result is (x0)2i+1+(x0)2i=νi2.
Step L2. Let x have Fi2(x)=νi2≤2. The word x∧M2 has 4-bit field j equal to F2j2(x)=ν2j2, since M2 keeps the low 2 bits of each 4-bit field. The word (x≫2)∧M2 has 4-bit field j equal to F2j+12(x)=ν2j+12. Their sum per field is νj4≤4<16. By the tool, Fj4 of the result is νj4.
Step L3. Let x have Fj4(x)=νj4≤4. The word x+(x≫4) is a sum by 4-bit fields: field j gets νj4+νj+14≤8<16 (with νw/44=0 at the top). By the tool, field j of the sum is νj4+νj+14. The mask M4 keeps the even 4-bit fields j=2k and clears the odd ones. So byte k of the result is ν2k4+ν2k+14=νk8.
Step L4. Let x=∑kck28k with ck=νk8≤8 and m=w/8 bytes. With H=∑l=0m−128l,
x⋅H=j=0∑2m−2(k+l=j∑ck)28j. For j≤m−1, the coefficient is sj=∑k=0jck≤ν(x0)≤w≤128<256. Reduce modulo 2w=28m: the terms with j≥m are multiples of 2w and vanish, so x⋅Hmod2w=∑j=0m−1sj28j. Each sj<256, so this is the base-256 expansion, and its top byte is sm−1=∑kck=ν(x0). The shift right by w−8=8(m−1) returns that byte. For w=8, m=1, H=1 and the shift is 0, so the result is c0=ν(x0) directly.
Theorem. For each word x0, SWAR-POPCOUNT(x0) returns ν(x0).
Proof. Chain the four steps: after line L1 the 2-bit fields hold νi2, after line L2 the 4-bit fields hold νj4, after line L3 the bytes hold νk8, and line L4 returns ∑kνk8=ν(x0). Each step used only the hypothesis given by the step before it. The procedure has no loop, so it stops after a fixed number of operations. ■
Where the width bound is used. Step L4 needs sj<256, which holds because sj≤w≤128. For w≥256 a byte cannot hold the count w, and the fields must first be doubled to 16 bits.