/****************************************************************************/
/*	Copyright (c) 2009, Bendor Research Pty. Ltd. All rights reserved.		*/
/*	This software is released under the GNU General Public License, version	*/
/*	3, with the exemptions that 1) the header files installed by this 	 	*/
/*	package can be included in closed-source code and 2) the libraries		*/
/*	built by this package can be statically linked into a closed-source 	*/
/*	binary. See the file LICENSE for the details.							*/
/*	This software is provided "AS IS", without any warranty or guarantee.	*/
/*	By using this software you acknowledge that neither Bendor Research nor	*/
/*	any of its personnel or affiliates can be held liable for any damages,	*/
/*	including, but not limited to, loss of business, loss of money, loss of */
/*	life, loss of reputation, arising out of this software being faulty or	*/
/*	not performing as advertised, even if Bendor Research was aware of such	*/
/*	faults in the software. You use this software at your own risk, any and */
/*	all liabilities that arise out of your using this software are strictly	*/
/*	yours.																	*/
/****************************************************************************/

#include <arm_func.h>

/*
*	The function returns the number of leading 0 bits in a 32-bit word.
*	That is, if the word is 1xxx ... xxxx then 0 is returned, if the word
*	is 01xx ... xxxx then 1 is returned, 0000 ... 0001 returns 31 and if the
*	argument is 0000 ... 0000 then 32 is returned.
*
*	Algorithm:
*
*	unsigned ldzcnt( unsigned x )
*	{
*	unsigned n = 0;
*
*		if ( ! ( x & 0xffff0000 ) ) { n += 16; x <<= 16; }
*		if ( ! ( x & 0xff000000 ) ) { n +=  8; x <<=  8; }
*		if ( ! ( x & 0xf0000000 ) ) { n +=  4; x <<=  4; }
*		if ( ! ( x & 0xc0000000 ) ) { n +=  2; x <<=  2; }
*		if ( ! ( x & 0x80000000 ) ) { n +=  1; x <<=  1; }
*		if ( ! ( x & 0x80000000 ) ) n++;
*		return( n );
*	}
*/

	afunc	ldzcnt
	mov		r1,#1
	movs	r2,r0,lsr #16
	addeq	r1,r1,#16
	moveq	r0,r0,lsl #16
	movs	r2,r0,lsr #24
	addeq	r1,r1,#8
	moveq	r0,r0,lsl #8
	movs	r2,r0,lsr #28
	addeq	r1,r1,#4
	moveq	r0,r0,lsl #4
	movs	r2,r0,lsr #30
	addeq	r1,r1,#2
	moveq	r0,r0,lsl #2
	movs	r2,r0,lsr #31
	addeq	r1,r1,#1
	subeq	r0,r1,r0,lsr #30
	subne	r0,r1,r0,lsr #31
	bx		lr

