//===-- llvm/Support/MathExtras.h - Useful math functions -------*- C++ -*-===//1//2// The LLVM Compiler Infrastructure3//4// This file is distributed under the University of Illinois Open Source5// License. See LICENSE.TXT for details.6//7//===----------------------------------------------------------------------===//8//9// This file contains some functions that are useful for math stuff.10//11//===----------------------------------------------------------------------===//1213/* Capstone Disassembly Engine */14/* By Nguyen Anh Quynh <[email protected]>, 2013-2019 */1516#ifndef CS_LLVM_SUPPORT_MATHEXTRAS_H17#define CS_LLVM_SUPPORT_MATHEXTRAS_H1819#if defined(_WIN32_WCE) && (_WIN32_WCE < 0x800)20#include "windowsce/intrin.h"21#elif defined(_MSC_VER)22#include <intrin.h>23#endif2425#ifndef __cplusplus26#if defined (WIN32) || defined (WIN64) || defined (_WIN32) || defined (_WIN64)27#define inline /* inline */28#endif29#endif3031// NOTE: The following support functions use the _32/_64 extensions instead of32// type overloading so that signed and unsigned integers can be used without33// ambiguity.3435/// Hi_32 - This function returns the high 32 bits of a 64 bit value.36static inline uint32_t Hi_32(uint64_t Value) {37return (uint32_t)(Value >> 32);38}3940/// Lo_32 - This function returns the low 32 bits of a 64 bit value.41static inline uint32_t Lo_32(uint64_t Value) {42return (uint32_t)(Value);43}4445/// isUIntN - Checks if an unsigned integer fits into the given (dynamic)46/// bit width.47static inline bool isUIntN(unsigned N, uint64_t x) {48return x == (x & (~0ULL >> (64 - N)));49}5051/// isIntN - Checks if an signed integer fits into the given (dynamic)52/// bit width.53//static inline bool isIntN(unsigned N, int64_t x) {54// return N >= 64 || (-(INT64_C(1)<<(N-1)) <= x && x < (INT64_C(1)<<(N-1)));55//}5657/// isMask_32 - This function returns true if the argument is a sequence of ones58/// starting at the least significant bit with the remainder zero (32 bit59/// version). Ex. isMask_32(0x0000FFFFU) == true.60static inline bool isMask_32(uint32_t Value) {61return Value && ((Value + 1) & Value) == 0;62}6364/// isMask_64 - This function returns true if the argument is a sequence of ones65/// starting at the least significant bit with the remainder zero (64 bit66/// version).67static inline bool isMask_64(uint64_t Value) {68return Value && ((Value + 1) & Value) == 0;69}7071/// isShiftedMask_32 - This function returns true if the argument contains a72/// sequence of ones with the remainder zero (32 bit version.)73/// Ex. isShiftedMask_32(0x0000FF00U) == true.74static inline bool isShiftedMask_32(uint32_t Value) {75return isMask_32((Value - 1) | Value);76}7778/// isShiftedMask_64 - This function returns true if the argument contains a79/// sequence of ones with the remainder zero (64 bit version.)80static inline bool isShiftedMask_64(uint64_t Value) {81return isMask_64((Value - 1) | Value);82}8384/// isPowerOf2_32 - This function returns true if the argument is a power of85/// two > 0. Ex. isPowerOf2_32(0x00100000U) == true (32 bit edition.)86static inline bool isPowerOf2_32(uint32_t Value) {87return Value && !(Value & (Value - 1));88}8990/// CountLeadingZeros_32 - this function performs the platform optimal form of91/// counting the number of zeros from the most significant bit to the first one92/// bit. Ex. CountLeadingZeros_32(0x00F000FF) == 8.93/// Returns 32 if the word is zero.94static inline unsigned CountLeadingZeros_32(uint32_t Value) {95unsigned Count; // result96#if __GNUC__ >= 497// PowerPC is defined for __builtin_clz(0)98#if !defined(__ppc__) && !defined(__ppc64__)99if (!Value) return 32;100#endif101Count = __builtin_clz(Value);102#else103unsigned Shift;104if (!Value) return 32;105Count = 0;106// bisection method for count leading zeros107for (Shift = 32 >> 1; Shift; Shift >>= 1) {108uint32_t Tmp = Value >> Shift;109if (Tmp) {110Value = Tmp;111} else {112Count |= Shift;113}114}115#endif116return Count;117}118119/// CountLeadingOnes_32 - this function performs the operation of120/// counting the number of ones from the most significant bit to the first zero121/// bit. Ex. CountLeadingOnes_32(0xFF0FFF00) == 8.122/// Returns 32 if the word is all ones.123static inline unsigned CountLeadingOnes_32(uint32_t Value) {124return CountLeadingZeros_32(~Value);125}126127/// CountLeadingZeros_64 - This function performs the platform optimal form128/// of counting the number of zeros from the most significant bit to the first129/// one bit (64 bit edition.)130/// Returns 64 if the word is zero.131static inline unsigned CountLeadingZeros_64(uint64_t Value) {132unsigned Count; // result133#if __GNUC__ >= 4134// PowerPC is defined for __builtin_clzll(0)135#if !defined(__ppc__) && !defined(__ppc64__)136if (!Value) return 64;137#endif138Count = __builtin_clzll(Value);139#else140#ifndef _MSC_VER141unsigned Shift;142if (sizeof(long) == sizeof(int64_t))143{144if (!Value) return 64;145Count = 0;146// bisection method for count leading zeros147for (Shift = 64 >> 1; Shift; Shift >>= 1) {148uint64_t Tmp = Value >> Shift;149if (Tmp) {150Value = Tmp;151} else {152Count |= Shift;153}154}155}156else157#endif158{159// get hi portion160uint32_t Hi = Hi_32(Value);161162// if some bits in hi portion163if (Hi) {164// leading zeros in hi portion plus all bits in lo portion165Count = CountLeadingZeros_32(Hi);166} else {167// get lo portion168uint32_t Lo = Lo_32(Value);169// same as 32 bit value170Count = CountLeadingZeros_32(Lo)+32;171}172}173#endif174return Count;175}176177/// CountLeadingOnes_64 - This function performs the operation178/// of counting the number of ones from the most significant bit to the first179/// zero bit (64 bit edition.)180/// Returns 64 if the word is all ones.181static inline unsigned CountLeadingOnes_64(uint64_t Value) {182return CountLeadingZeros_64(~Value);183}184185/// CountTrailingZeros_32 - this function performs the platform optimal form of186/// counting the number of zeros from the least significant bit to the first one187/// bit. Ex. CountTrailingZeros_32(0xFF00FF00) == 8.188/// Returns 32 if the word is zero.189static inline unsigned CountTrailingZeros_32(uint32_t Value) {190#if __GNUC__ >= 4191return Value ? __builtin_ctz(Value) : 32;192#else193static const unsigned Mod37BitPosition[] = {19432, 0, 1, 26, 2, 23, 27, 0, 3, 16, 24, 30, 28, 11, 0, 13,1954, 7, 17, 0, 25, 22, 31, 15, 29, 10, 12, 6, 0, 21, 14, 9,1965, 20, 8, 19, 18197};198// Replace "-Value" by "1+~Value" in the following commented code to avoid199// MSVC warning C4146200// return Mod37BitPosition[(-Value & Value) % 37];201return Mod37BitPosition[((1 + ~Value) & Value) % 37];202#endif203}204205/// CountTrailingOnes_32 - this function performs the operation of206/// counting the number of ones from the least significant bit to the first zero207/// bit. Ex. CountTrailingOnes_32(0x00FF00FF) == 8.208/// Returns 32 if the word is all ones.209static inline unsigned CountTrailingOnes_32(uint32_t Value) {210return CountTrailingZeros_32(~Value);211}212213/// CountTrailingZeros_64 - This function performs the platform optimal form214/// of counting the number of zeros from the least significant bit to the first215/// one bit (64 bit edition.)216/// Returns 64 if the word is zero.217static inline unsigned CountTrailingZeros_64(uint64_t Value) {218#if __GNUC__ >= 4219return Value ? __builtin_ctzll(Value) : 64;220#else221static const unsigned Mod67Position[] = {22264, 0, 1, 39, 2, 15, 40, 23, 3, 12, 16, 59, 41, 19, 24, 54,2234, 64, 13, 10, 17, 62, 60, 28, 42, 30, 20, 51, 25, 44, 55,22447, 5, 32, 65, 38, 14, 22, 11, 58, 18, 53, 63, 9, 61, 27,22529, 50, 43, 46, 31, 37, 21, 57, 52, 8, 26, 49, 45, 36, 56,2267, 48, 35, 6, 34, 33, 0227};228// Replace "-Value" by "1+~Value" in the following commented code to avoid229// MSVC warning C4146230// return Mod67Position[(-Value & Value) % 67];231return Mod67Position[((1 + ~Value) & Value) % 67];232#endif233}234235/// CountTrailingOnes_64 - This function performs the operation236/// of counting the number of ones from the least significant bit to the first237/// zero bit (64 bit edition.)238/// Returns 64 if the word is all ones.239static inline unsigned CountTrailingOnes_64(uint64_t Value) {240return CountTrailingZeros_64(~Value);241}242243/// CountPopulation_32 - this function counts the number of set bits in a value.244/// Ex. CountPopulation(0xF000F000) = 8245/// Returns 0 if the word is zero.246static inline unsigned CountPopulation_32(uint32_t Value) {247#if __GNUC__ >= 4248return __builtin_popcount(Value);249#else250uint32_t v = Value - ((Value >> 1) & 0x55555555);251v = (v & 0x33333333) + ((v >> 2) & 0x33333333);252return (((v + (v >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24;253#endif254}255256/// CountPopulation_64 - this function counts the number of set bits in a value,257/// (64 bit edition.)258static inline unsigned CountPopulation_64(uint64_t Value) {259#if __GNUC__ >= 4260return __builtin_popcountll(Value);261#else262uint64_t v = Value - ((Value >> 1) & 0x5555555555555555ULL);263v = (v & 0x3333333333333333ULL) + ((v >> 2) & 0x3333333333333333ULL);264v = (v + (v >> 4)) & 0x0F0F0F0F0F0F0F0FULL;265return (uint64_t)((v * 0x0101010101010101ULL) >> 56);266#endif267}268269/// Log2_32 - This function returns the floor log base 2 of the specified value,270/// -1 if the value is zero. (32 bit edition.)271/// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2272static inline unsigned Log2_32(uint32_t Value) {273return 31 - CountLeadingZeros_32(Value);274}275276/// Log2_64 - This function returns the floor log base 2 of the specified value,277/// -1 if the value is zero. (64 bit edition.)278static inline unsigned Log2_64(uint64_t Value) {279return 63 - CountLeadingZeros_64(Value);280}281282/// Log2_32_Ceil - This function returns the ceil log base 2 of the specified283/// value, 32 if the value is zero. (32 bit edition).284/// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3285static inline unsigned Log2_32_Ceil(uint32_t Value) {286return 32-CountLeadingZeros_32(Value-1);287}288289/// Log2_64_Ceil - This function returns the ceil log base 2 of the specified290/// value, 64 if the value is zero. (64 bit edition.)291static inline unsigned Log2_64_Ceil(uint64_t Value) {292return 64-CountLeadingZeros_64(Value-1);293}294295/// GreatestCommonDivisor64 - Return the greatest common divisor of the two296/// values using Euclid's algorithm.297static inline uint64_t GreatestCommonDivisor64(uint64_t A, uint64_t B) {298while (B) {299uint64_t T = B;300B = A % B;301A = T;302}303return A;304}305306/// BitsToDouble - This function takes a 64-bit integer and returns the bit307/// equivalent double.308static inline double BitsToDouble(uint64_t Bits) {309union {310uint64_t L;311double D;312} T;313T.L = Bits;314return T.D;315}316317/// BitsToFloat - This function takes a 32-bit integer and returns the bit318/// equivalent float.319static inline float BitsToFloat(uint32_t Bits) {320union {321uint32_t I;322float F;323} T;324T.I = Bits;325return T.F;326}327328/// DoubleToBits - This function takes a double and returns the bit329/// equivalent 64-bit integer. Note that copying doubles around330/// changes the bits of NaNs on some hosts, notably x86, so this331/// routine cannot be used if these bits are needed.332static inline uint64_t DoubleToBits(double Double) {333union {334uint64_t L;335double D;336} T;337T.D = Double;338return T.L;339}340341/// FloatToBits - This function takes a float and returns the bit342/// equivalent 32-bit integer. Note that copying floats around343/// changes the bits of NaNs on some hosts, notably x86, so this344/// routine cannot be used if these bits are needed.345static inline uint32_t FloatToBits(float Float) {346union {347uint32_t I;348float F;349} T;350T.F = Float;351return T.I;352}353354/// MinAlign - A and B are either alignments or offsets. Return the minimum355/// alignment that may be assumed after adding the two together.356static inline uint64_t MinAlign(uint64_t A, uint64_t B) {357// The largest power of 2 that divides both A and B.358//359// Replace "-Value" by "1+~Value" in the following commented code to avoid360// MSVC warning C4146361// return (A | B) & -(A | B);362return (A | B) & (1 + ~(A | B));363}364365/// NextPowerOf2 - Returns the next power of two (in 64-bits)366/// that is strictly greater than A. Returns zero on overflow.367static inline uint64_t NextPowerOf2(uint64_t A) {368A |= (A >> 1);369A |= (A >> 2);370A |= (A >> 4);371A |= (A >> 8);372A |= (A >> 16);373A |= (A >> 32);374return A + 1;375}376377/// Returns the next integer (mod 2**64) that is greater than or equal to378/// \p Value and is a multiple of \p Align. \p Align must be non-zero.379///380/// Examples:381/// \code382/// RoundUpToAlignment(5, 8) = 8383/// RoundUpToAlignment(17, 8) = 24384/// RoundUpToAlignment(~0LL, 8) = 0385/// \endcode386static inline uint64_t RoundUpToAlignment(uint64_t Value, uint64_t Align) {387return ((Value + Align - 1) / Align) * Align;388}389390/// Returns the offset to the next integer (mod 2**64) that is greater than391/// or equal to \p Value and is a multiple of \p Align. \p Align must be392/// non-zero.393static inline uint64_t OffsetToAlignment(uint64_t Value, uint64_t Align) {394return RoundUpToAlignment(Value, Align) - Value;395}396397/// abs64 - absolute value of a 64-bit int. Not all environments support398/// "abs" on whatever their name for the 64-bit int type is. The absolute399/// value of the largest negative number is undefined, as with "abs".400static inline int64_t abs64(int64_t x) {401return (x < 0) ? -x : x;402}403404/// \brief Sign extend number in the bottom B bits of X to a 32-bit int.405/// Requires 0 < B <= 32.406static inline int32_t SignExtend32(uint32_t X, unsigned B) {407return (int32_t)(X << (32 - B)) >> (32 - B);408}409410/// \brief Sign extend number in the bottom B bits of X to a 64-bit int.411/// Requires 0 < B <= 64.412static inline int64_t SignExtend64(uint64_t X, unsigned B) {413return (int64_t)(X << (64 - B)) >> (64 - B);414}415416/// \brief Count number of 0's from the most significant bit to the least417/// stopping at the first 1.418///419/// Only unsigned integral types are allowed.420///421/// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are422/// valid arguments.423static inline unsigned int countLeadingZeros(int x)424{425int i;426const unsigned bits = sizeof(x) * 8;427unsigned count = bits;428429if (x < 0) {430return 0;431}432for (i = bits; --i; ) {433if (x == 0) break;434count--;435x >>= 1;436}437438return count;439}440441#endif442443444