3a_asm/2_isa: fixed our examples
[calu.git] / 2_isa / src / bittwiddling.s
1 .data
2 B0: .fill 0x55555555
3 B1: .fill 0x33333333
4 B2: .fill 0x0F0F0F0F
5 B3: .fill 0x001F001F
6 B4: .fill 0x0000003F
7
8 .text
9
10 ;int countbits(int x) {
11 countbits:
12         ;x == r1
13
14         ;load address of B0 into r3
15         ldil r3, B0@lo;
16         ldih r3, B0@hi;
17
18         ;x = (x & B0) + ((x >>  1) & B0);
19         ;r0 = (x >> 1)
20         lrs r0,r1,1;
21
22         ;load B0 into r2
23         ldw r2, 0(r3);
24
25         ;(x >> 1) & B0  
26         and r0, r0, r2;
27
28         ;x & B0
29         and r1, r1, r2;
30
31         ;x = (x & B0) + ((x >>  1) & B0);
32         add r0, r0, r1;
33
34         ;load B1 into r2, use displacment for address of B1 (or add?)
35         ldw r2, B1-B0(r3);
36
37         ;x = (x & B1) + ((x >>  2) & B1);
38         lrs r1, r0, 2;
39         and r1, r1, r2;
40         and r0, r0, r2;
41         add r0, r0, r1;
42
43         ;x = (x + (x >>  4)) & B2;
44         ldw r2, B2-B0(r3);
45
46         lrs r1, r0, 4;
47         and r1, r1, r2;
48         and r0, r0, r2;
49         add r0, r0, r1;
50
51         ;x = (x + (x >>  8)) /*& B3 */
52         lrs r1, r0, 8;
53         add r0, r0, r1;
54
55         ldw r2, B4-B0(r3);
56         ;x = (x + (x >> 16)) & B4;
57         lrs r1, r0, 16;
58         add r0, r0, r1;
59         and r0, r0, r2;
60
61         ;return x;
62         ret;
63 ;}