Path: blob/main/contrib/llvm-project/compiler-rt/lib/builtins/ctzsi2.c
35260 views
//===-- ctzsi2.c - Implement __ctzsi2 -------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements __ctzsi2 for the compiler_rt library.9//10//===----------------------------------------------------------------------===//1112#include "int_lib.h"1314// Returns: the number of trailing 0-bits1516// Precondition: a != 01718COMPILER_RT_ABI int __ctzsi2(si_int a) {19su_int x = (su_int)a;20si_int t = ((x & 0x0000FFFF) == 0)21<< 4; // if (x has no small bits) t = 16 else 022x >>= t; // x = [0 - 0xFFFF] + higher garbage bits23su_int r = t; // r = [0, 16]24// return r + ctz(x)25t = ((x & 0x00FF) == 0) << 3;26x >>= t; // x = [0 - 0xFF] + higher garbage bits27r += t; // r = [0, 8, 16, 24]28// return r + ctz(x)29t = ((x & 0x0F) == 0) << 2;30x >>= t; // x = [0 - 0xF] + higher garbage bits31r += t; // r = [0, 4, 8, 12, 16, 20, 24, 28]32// return r + ctz(x)33t = ((x & 0x3) == 0) << 1;34x >>= t;35x &= 3; // x = [0 - 3]36r += t; // r = [0 - 30] and is even37// return r + ctz(x)3839// The branch-less return statement below is equivalent40// to the following switch statement:41// switch (x)42// {43// case 0:44// return r + 2;45// case 2:46// return r + 1;47// case 1:48// case 3:49// return r;50// }51return r + ((2 - (x >> 1)) & -((x & 1) == 0));52}535455