xref: /netbsd-src/sys/external/bsd/compiler_rt/dist/lib/builtins/arm/clzsi2.S (revision b7b7574d3bf8eeb51a1fa3977b59142ec6434a55)
1/* ===-- clzsi2.c - Implement __clzsi2 -------------------------------------===
2 *
3 *               The LLVM Compiler Infrastructure
4 *
5 * This file is dual licensed under the MIT and the University of Illinois Open
6 * Source Licenses. See LICENSE.TXT for details.
7 *
8 * ===----------------------------------------------------------------------===
9 *
10 * This file implements count leading zeros for 32bit arguments.
11 *
12 * ===----------------------------------------------------------------------===
13 */
14#include "../assembly.h"
15
16	.syntax unified
17
18	.text
19	.p2align	2
20DEFINE_COMPILERRT_FUNCTION(__clzsi2)
21#ifdef __ARM_FEATURE_CLZ
22	clz	r0, r0
23	JMP(lr)
24#else
25	/* Assumption: n != 0 */
26
27	/*
28	 * r0: n
29	 * r1: count of leading zeros in n + 1
30	 * r2: scratch register for shifted r0
31	 */
32	mov	r1, 1
33
34	/*
35	 * Basic block:
36	 * if ((r0 >> SHIFT) == 0)
37	 *   r1 += SHIFT;
38	 * else
39	 *   r0 >>= SHIFT;
40	 * for descending powers of two as SHIFT.
41	 */
42
43#define BLOCK(shift) \
44	lsrs	r2, r0, shift; \
45	movne	r0, r2; \
46	addeq	r1, shift \
47
48	BLOCK(16)
49	BLOCK(8)
50	BLOCK(4)
51	BLOCK(2)
52
53	/*
54	 * The basic block invariants at this point are (r0 >> 2) == 0 and
55	 * r0 != 0. This means 1 <= r0 <= 3 and 0 <= (r0 >> 1) <= 1.
56	 *
57	 * r0 | (r0 >> 1) == 0 | (r0 >> 1) == 1 | -(r0 >> 1) | 1 - (r0 >> 1)
58	 * ---+----------------+----------------+------------+--------------
59	 * 1  | 1              | 0              | 0          | 1
60	 * 2  | 0              | 1              | -1         | 0
61	 * 3  | 0              | 1              | -1         | 0
62	 *
63	 * The r1's initial value of 1 compensates for the 1 here.
64	 */
65	sub	r0, r1, r0, lsr #1
66
67	JMP(lr)
68#endif // __ARM_FEATURE_CLZ
69END_COMPILERRT_FUNCTION(__clzsi2)
70