X-Git-Url: http://erislabs.net/gitweb/?a=blobdiff_plain;f=lib%2Fffsl.h;h=b3afc9b6a2ea9ca97db2568d857bf29734942953;hb=fc102289543631b711bc0bbd65c0090262b170b9;hp=673b0aa2ba9c4c7001a69c39ffc0c0f042c87dce;hpb=9c6e26caf1aeb2f0de445dc3fa568b6e82701bc2;p=gnulib.git diff --git a/lib/ffsl.h b/lib/ffsl.h index 673b0aa2b..b3afc9b6a 100644 --- a/lib/ffsl.h +++ b/lib/ffsl.h @@ -1,5 +1,5 @@ /* ffsl.h -- find the first set bit in a word. - Copyright (C) 2011 Free Software Foundation, Inc. + Copyright (C) 2011-2012 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -19,6 +19,9 @@ /* This file is meant to be included by ffsl.c and ffsll.c, after they have defined FUNC and TYPE. */ +#include + +/* Specification. */ #include #include @@ -31,17 +34,34 @@ int FUNC (TYPE i) { - int result = 0; +#if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) && defined GCC_BUILTIN + return GCC_BUILTIN (i); +#else unsigned TYPE j = i; + /* Split j into chunks, and look at one chunk after the other. */ + enum { chunk_bits = CHAR_BIT * sizeof (unsigned int) }; + /* The number of chunks is ceil (sizeof (TYPE) / sizeof (unsigned int)) + = (sizeof (TYPE) - 1) / sizeof (unsigned int) + 1. */ + enum { chunk_count = (sizeof (TYPE) - 1) / sizeof (unsigned int) + 1 }; - /* GCC has __builtin_ffs, but it is limited to int. */ - if (!i) - return 0; - while (1) + if (chunk_count > 1) { - if ((int) j) - return result + ffs (j); - j >>= CHAR_BIT * sizeof (int); - result += CHAR_BIT * sizeof (int); + size_t k; + + /* It is tempting to write if (!j) here, but if we do this, + Solaris 10/x86 "cc -O" miscompiles the code. */ + if (!i) + return 0; + /* Unroll the first loop round. k = 0. */ + if ((unsigned int) j) + return ffs ((unsigned int) j); + /* Generic loop. */ + for (k = 1; k < chunk_count - 1; k++) + if ((unsigned int) (j >> (k * chunk_bits)) != 0) + return k * chunk_bits + ffs ((unsigned int) (j >> (k * chunk_bits))); } + /* Last loop round. k = chunk_count - 1. */ + return (chunk_count - 1) * chunk_bits + + ffs ((unsigned int) (j >> ((chunk_count - 1) * chunk_bits))); +#endif }