blob: cc8c96fe421cfb58696bea192c32a673d2db5e2b [file] [log] [blame]
Edward O'Callaghan2bf62722009-08-05 04:02:56 +00001/* ===-- clzdi2.c - Implement __clzdi2 -------------------------------------===
2 *
Chandler Carruth7a739a02019-01-19 10:56:40 +00003 * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 * See https://llvm.org/LICENSE.txt for license information.
5 * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Edward O'Callaghan2bf62722009-08-05 04:02:56 +00006 *
7 * ===----------------------------------------------------------------------===
8 *
9 * This file implements __clzdi2 for the compiler_rt library.
10 *
11 * ===----------------------------------------------------------------------===
12 */
Daniel Dunbarb3a69012009-06-26 16:47:03 +000013
14#include "int_lib.h"
15
Edward O'Callaghan2bf62722009-08-05 04:02:56 +000016/* Returns: the number of leading 0-bits */
Daniel Dunbarb3a69012009-06-26 16:47:03 +000017
Kristina Brooksd57a71d2018-09-18 18:56:52 +000018#if !defined(__clang__) && \
19 ((defined(__sparc__) && defined(__arch64__)) || \
20 defined(__mips64) || \
21 (defined(__riscv) && __SIZEOF_POINTER__ >= 8))
22/* On 64-bit architectures with neither a native clz instruction nor a native
23 * ctz instruction, gcc resolves __builtin_clz to __clzdi2 rather than
24 * __clzsi2, leading to infinite recursion. */
Jonas Devlieghere816aba32018-02-08 11:14:11 +000025#define __builtin_clz(a) __clzsi2(a)
26extern si_int __clzsi2(si_int);
27#endif
28
Edward O'Callaghan2bf62722009-08-05 04:02:56 +000029/* Precondition: a != 0 */
Daniel Dunbarb3a69012009-06-26 16:47:03 +000030
Anton Korobeynikov1c5f89b2011-04-19 17:52:09 +000031COMPILER_RT_ABI si_int
Daniel Dunbarb3a69012009-06-26 16:47:03 +000032__clzdi2(di_int a)
33{
34 dwords x;
35 x.all = a;
Edward O'Callaghan8bf1e092009-08-09 18:41:02 +000036 const si_int f = -(x.s.high == 0);
37 return __builtin_clz((x.s.high & ~f) | (x.s.low & f)) +
Daniel Dunbarb3a69012009-06-26 16:47:03 +000038 (f & ((si_int)(sizeof(si_int) * CHAR_BIT)));
39}