1 /* $OpenBSD: reg.c,v 1.3 2016/08/14 23:01:13 guenther Exp $ */
2
3 /*
4 * Copyright (c) 2003 Jason L. Wright (jason@thought.net)
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
20 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
24 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
25 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 * POSSIBILITY OF SUCH DAMAGE.
27 */
28 #include <sys/types.h>
29 #include <stdio.h>
30
31 int64_t asm_popc(int64_t);
32 int64_t c_popc(int64_t);
33 int test_it(int64_t);
34 int test_ones(void);
35 int main(void);
36
37 int64_t
asm_popc(int64_t v)38 asm_popc(int64_t v)
39 {
40 asm("popc %1, %0" : "=r" (v) : "r" (v));
41 return (v);
42 }
43
44 int64_t
c_popc(int64_t v)45 c_popc(int64_t v)
46 {
47 int64_t bit, r;
48
49 for (bit = 1, r = 0; bit; bit <<= 1)
50 if (v & bit)
51 r++;
52 return (r);
53 }
54
55 int
test_it(int64_t v)56 test_it(int64_t v)
57 {
58 int64_t tc, ta;
59
60 tc = c_popc(v);
61 ta = asm_popc(v);
62 if (tc == ta)
63 return (0);
64 printf("%lld: C(%lld) ASM(%lld)\n", v, tc, ta);
65 return (1);
66 }
67
68 int
test_ones(void)69 test_ones(void)
70 {
71 int64_t v;
72 int i, r = 0;
73
74 for (i = 0; i < 64; i++) {
75 v = 1LL << i;
76 if (c_popc(v) != 1) {
77 printf("ONES popc(%lld) != 1\n", v);
78 r = 1;
79 }
80 if (test_it(v))
81 r = 1;
82 }
83 return (r);
84 }
85
86 int
main()87 main()
88 {
89 int r = 0;
90
91 if (test_ones())
92 r = 1;
93
94 return (r);
95 }
96