MathExtras.h revision 263508
1//===-- llvm/Support/MathExtras.h - Useful math functions -------*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file contains some functions that are useful for math stuff. 11// 12//===----------------------------------------------------------------------===// 13 14#ifndef LLVM_SUPPORT_MATHEXTRAS_H 15#define LLVM_SUPPORT_MATHEXTRAS_H 16 17#include "llvm/Support/Compiler.h" 18#include "llvm/Support/SwapByteOrder.h" 19#include "llvm/Support/type_traits.h" 20 21#include <cstring> 22 23#ifdef _MSC_VER 24#include <intrin.h> 25#include <limits> 26#endif 27 28namespace llvm { 29/// \brief The behavior an operation has on an input of 0. 30enum ZeroBehavior { 31 /// \brief The returned value is undefined. 32 ZB_Undefined, 33 /// \brief The returned value is numeric_limits<T>::max() 34 ZB_Max, 35 /// \brief The returned value is numeric_limits<T>::digits 36 ZB_Width 37}; 38 39/// \brief Count number of 0's from the least significant bit to the most 40/// stopping at the first 1. 41/// 42/// Only unsigned integral types are allowed. 43/// 44/// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are 45/// valid arguments. 46template <typename T> 47typename enable_if_c<std::numeric_limits<T>::is_integer && 48 !std::numeric_limits<T>::is_signed, std::size_t>::type 49countTrailingZeros(T Val, ZeroBehavior ZB = ZB_Width) { 50 (void)ZB; 51 52 if (!Val) 53 return std::numeric_limits<T>::digits; 54 if (Val & 0x1) 55 return 0; 56 57 // Bisection method. 58 std::size_t ZeroBits = 0; 59 T Shift = std::numeric_limits<T>::digits >> 1; 60 T Mask = std::numeric_limits<T>::max() >> Shift; 61 while (Shift) { 62 if ((Val & Mask) == 0) { 63 Val >>= Shift; 64 ZeroBits |= Shift; 65 } 66 Shift >>= 1; 67 Mask >>= Shift; 68 } 69 return ZeroBits; 70} 71 72// Disable signed. 73template <typename T> 74typename enable_if_c<std::numeric_limits<T>::is_integer && 75 std::numeric_limits<T>::is_signed, std::size_t>::type 76countTrailingZeros(T Val, ZeroBehavior ZB = ZB_Width) LLVM_DELETED_FUNCTION; 77 78#if __GNUC__ >= 4 || _MSC_VER 79template <> 80inline std::size_t countTrailingZeros<uint32_t>(uint32_t Val, ZeroBehavior ZB) { 81 if (ZB != ZB_Undefined && Val == 0) 82 return 32; 83 84#if __has_builtin(__builtin_ctz) || __GNUC_PREREQ(4, 0) 85 return __builtin_ctz(Val); 86#elif _MSC_VER 87 unsigned long Index; 88 _BitScanForward(&Index, Val); 89 return Index; 90#endif 91} 92 93#if !defined(_MSC_VER) || defined(_M_X64) 94template <> 95inline std::size_t countTrailingZeros<uint64_t>(uint64_t Val, ZeroBehavior ZB) { 96 if (ZB != ZB_Undefined && Val == 0) 97 return 64; 98 99#if __has_builtin(__builtin_ctzll) || __GNUC_PREREQ(4, 0) 100 return __builtin_ctzll(Val); 101#elif _MSC_VER 102 unsigned long Index; 103 _BitScanForward64(&Index, Val); 104 return Index; 105#endif 106} 107#endif 108#endif 109 110/// \brief Count number of 0's from the most significant bit to the least 111/// stopping at the first 1. 112/// 113/// Only unsigned integral types are allowed. 114/// 115/// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are 116/// valid arguments. 117template <typename T> 118typename enable_if_c<std::numeric_limits<T>::is_integer && 119 !std::numeric_limits<T>::is_signed, std::size_t>::type 120countLeadingZeros(T Val, ZeroBehavior ZB = ZB_Width) { 121 (void)ZB; 122 123 if (!Val) 124 return std::numeric_limits<T>::digits; 125 126 // Bisection method. 127 std::size_t ZeroBits = 0; 128 for (T Shift = std::numeric_limits<T>::digits >> 1; Shift; Shift >>= 1) { 129 T Tmp = Val >> Shift; 130 if (Tmp) 131 Val = Tmp; 132 else 133 ZeroBits |= Shift; 134 } 135 return ZeroBits; 136} 137 138// Disable signed. 139template <typename T> 140typename enable_if_c<std::numeric_limits<T>::is_integer && 141 std::numeric_limits<T>::is_signed, std::size_t>::type 142countLeadingZeros(T Val, ZeroBehavior ZB = ZB_Width) LLVM_DELETED_FUNCTION; 143 144#if __GNUC__ >= 4 || _MSC_VER 145template <> 146inline std::size_t countLeadingZeros<uint32_t>(uint32_t Val, ZeroBehavior ZB) { 147 if (ZB != ZB_Undefined && Val == 0) 148 return 32; 149 150#if __has_builtin(__builtin_clz) || __GNUC_PREREQ(4, 0) 151 return __builtin_clz(Val); 152#elif _MSC_VER 153 unsigned long Index; 154 _BitScanReverse(&Index, Val); 155 return Index ^ 31; 156#endif 157} 158 159#if !defined(_MSC_VER) || defined(_M_X64) 160template <> 161inline std::size_t countLeadingZeros<uint64_t>(uint64_t Val, ZeroBehavior ZB) { 162 if (ZB != ZB_Undefined && Val == 0) 163 return 64; 164 165#if __has_builtin(__builtin_clzll) || __GNUC_PREREQ(4, 0) 166 return __builtin_clzll(Val); 167#elif _MSC_VER 168 unsigned long Index; 169 _BitScanReverse64(&Index, Val); 170 return Index ^ 63; 171#endif 172} 173#endif 174#endif 175 176/// \brief Get the index of the first set bit starting from the least 177/// significant bit. 178/// 179/// Only unsigned integral types are allowed. 180/// 181/// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are 182/// valid arguments. 183template <typename T> 184typename enable_if_c<std::numeric_limits<T>::is_integer && 185 !std::numeric_limits<T>::is_signed, T>::type 186findFirstSet(T Val, ZeroBehavior ZB = ZB_Max) { 187 if (ZB == ZB_Max && Val == 0) 188 return std::numeric_limits<T>::max(); 189 190 return countTrailingZeros(Val, ZB_Undefined); 191} 192 193// Disable signed. 194template <typename T> 195typename enable_if_c<std::numeric_limits<T>::is_integer && 196 std::numeric_limits<T>::is_signed, T>::type 197findFirstSet(T Val, ZeroBehavior ZB = ZB_Max) LLVM_DELETED_FUNCTION; 198 199/// \brief Get the index of the last set bit starting from the least 200/// significant bit. 201/// 202/// Only unsigned integral types are allowed. 203/// 204/// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are 205/// valid arguments. 206template <typename T> 207typename enable_if_c<std::numeric_limits<T>::is_integer && 208 !std::numeric_limits<T>::is_signed, T>::type 209findLastSet(T Val, ZeroBehavior ZB = ZB_Max) { 210 if (ZB == ZB_Max && Val == 0) 211 return std::numeric_limits<T>::max(); 212 213 // Use ^ instead of - because both gcc and llvm can remove the associated ^ 214 // in the __builtin_clz intrinsic on x86. 215 return countLeadingZeros(Val, ZB_Undefined) ^ 216 (std::numeric_limits<T>::digits - 1); 217} 218 219// Disable signed. 220template <typename T> 221typename enable_if_c<std::numeric_limits<T>::is_integer && 222 std::numeric_limits<T>::is_signed, T>::type 223findLastSet(T Val, ZeroBehavior ZB = ZB_Max) LLVM_DELETED_FUNCTION; 224 225/// \brief Macro compressed bit reversal table for 256 bits. 226/// 227/// http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable 228static const unsigned char BitReverseTable256[256] = { 229#define R2(n) n, n + 2 * 64, n + 1 * 64, n + 3 * 64 230#define R4(n) R2(n), R2(n + 2 * 16), R2(n + 1 * 16), R2(n + 3 * 16) 231#define R6(n) R4(n), R4(n + 2 * 4), R4(n + 1 * 4), R4(n + 3 * 4) 232 R6(0), R6(2), R6(1), R6(3) 233}; 234 235/// \brief Reverse the bits in \p Val. 236template <typename T> 237T reverseBits(T Val) { 238 unsigned char in[sizeof(Val)]; 239 unsigned char out[sizeof(Val)]; 240 std::memcpy(in, &Val, sizeof(Val)); 241 for (unsigned i = 0; i < sizeof(Val); ++i) 242 out[(sizeof(Val) - i) - 1] = BitReverseTable256[in[i]]; 243 std::memcpy(&Val, out, sizeof(Val)); 244 return Val; 245} 246 247// NOTE: The following support functions use the _32/_64 extensions instead of 248// type overloading so that signed and unsigned integers can be used without 249// ambiguity. 250 251/// Hi_32 - This function returns the high 32 bits of a 64 bit value. 252inline uint32_t Hi_32(uint64_t Value) { 253 return static_cast<uint32_t>(Value >> 32); 254} 255 256/// Lo_32 - This function returns the low 32 bits of a 64 bit value. 257inline uint32_t Lo_32(uint64_t Value) { 258 return static_cast<uint32_t>(Value); 259} 260 261/// isInt - Checks if an integer fits into the given bit width. 262template<unsigned N> 263inline bool isInt(int64_t x) { 264 return N >= 64 || (-(INT64_C(1)<<(N-1)) <= x && x < (INT64_C(1)<<(N-1))); 265} 266// Template specializations to get better code for common cases. 267template<> 268inline bool isInt<8>(int64_t x) { 269 return static_cast<int8_t>(x) == x; 270} 271template<> 272inline bool isInt<16>(int64_t x) { 273 return static_cast<int16_t>(x) == x; 274} 275template<> 276inline bool isInt<32>(int64_t x) { 277 return static_cast<int32_t>(x) == x; 278} 279 280/// isShiftedInt<N,S> - Checks if a signed integer is an N bit number shifted 281/// left by S. 282template<unsigned N, unsigned S> 283inline bool isShiftedInt(int64_t x) { 284 return isInt<N+S>(x) && (x % (1<<S) == 0); 285} 286 287/// isUInt - Checks if an unsigned integer fits into the given bit width. 288template<unsigned N> 289inline bool isUInt(uint64_t x) { 290 return N >= 64 || x < (UINT64_C(1)<<(N)); 291} 292// Template specializations to get better code for common cases. 293template<> 294inline bool isUInt<8>(uint64_t x) { 295 return static_cast<uint8_t>(x) == x; 296} 297template<> 298inline bool isUInt<16>(uint64_t x) { 299 return static_cast<uint16_t>(x) == x; 300} 301template<> 302inline bool isUInt<32>(uint64_t x) { 303 return static_cast<uint32_t>(x) == x; 304} 305 306/// isShiftedUInt<N,S> - Checks if a unsigned integer is an N bit number shifted 307/// left by S. 308template<unsigned N, unsigned S> 309inline bool isShiftedUInt(uint64_t x) { 310 return isUInt<N+S>(x) && (x % (1<<S) == 0); 311} 312 313/// isUIntN - Checks if an unsigned integer fits into the given (dynamic) 314/// bit width. 315inline bool isUIntN(unsigned N, uint64_t x) { 316 return x == (x & (~0ULL >> (64 - N))); 317} 318 319/// isIntN - Checks if an signed integer fits into the given (dynamic) 320/// bit width. 321inline bool isIntN(unsigned N, int64_t x) { 322 return N >= 64 || (-(INT64_C(1)<<(N-1)) <= x && x < (INT64_C(1)<<(N-1))); 323} 324 325/// isMask_32 - This function returns true if the argument is a sequence of ones 326/// starting at the least significant bit with the remainder zero (32 bit 327/// version). Ex. isMask_32(0x0000FFFFU) == true. 328inline bool isMask_32(uint32_t Value) { 329 return Value && ((Value + 1) & Value) == 0; 330} 331 332/// isMask_64 - This function returns true if the argument is a sequence of ones 333/// starting at the least significant bit with the remainder zero (64 bit 334/// version). 335inline bool isMask_64(uint64_t Value) { 336 return Value && ((Value + 1) & Value) == 0; 337} 338 339/// isShiftedMask_32 - This function returns true if the argument contains a 340/// sequence of ones with the remainder zero (32 bit version.) 341/// Ex. isShiftedMask_32(0x0000FF00U) == true. 342inline bool isShiftedMask_32(uint32_t Value) { 343 return isMask_32((Value - 1) | Value); 344} 345 346/// isShiftedMask_64 - This function returns true if the argument contains a 347/// sequence of ones with the remainder zero (64 bit version.) 348inline bool isShiftedMask_64(uint64_t Value) { 349 return isMask_64((Value - 1) | Value); 350} 351 352/// isPowerOf2_32 - This function returns true if the argument is a power of 353/// two > 0. Ex. isPowerOf2_32(0x00100000U) == true (32 bit edition.) 354inline bool isPowerOf2_32(uint32_t Value) { 355 return Value && !(Value & (Value - 1)); 356} 357 358/// isPowerOf2_64 - This function returns true if the argument is a power of two 359/// > 0 (64 bit edition.) 360inline bool isPowerOf2_64(uint64_t Value) { 361 return Value && !(Value & (Value - int64_t(1L))); 362} 363 364/// ByteSwap_16 - This function returns a byte-swapped representation of the 365/// 16-bit argument, Value. 366inline uint16_t ByteSwap_16(uint16_t Value) { 367 return sys::SwapByteOrder_16(Value); 368} 369 370/// ByteSwap_32 - This function returns a byte-swapped representation of the 371/// 32-bit argument, Value. 372inline uint32_t ByteSwap_32(uint32_t Value) { 373 return sys::SwapByteOrder_32(Value); 374} 375 376/// ByteSwap_64 - This function returns a byte-swapped representation of the 377/// 64-bit argument, Value. 378inline uint64_t ByteSwap_64(uint64_t Value) { 379 return sys::SwapByteOrder_64(Value); 380} 381 382/// CountLeadingOnes_32 - this function performs the operation of 383/// counting the number of ones from the most significant bit to the first zero 384/// bit. Ex. CountLeadingOnes_32(0xFF0FFF00) == 8. 385/// Returns 32 if the word is all ones. 386inline unsigned CountLeadingOnes_32(uint32_t Value) { 387 return countLeadingZeros(~Value); 388} 389 390/// CountLeadingOnes_64 - This function performs the operation 391/// of counting the number of ones from the most significant bit to the first 392/// zero bit (64 bit edition.) 393/// Returns 64 if the word is all ones. 394inline unsigned CountLeadingOnes_64(uint64_t Value) { 395 return countLeadingZeros(~Value); 396} 397 398/// CountTrailingOnes_32 - this function performs the operation of 399/// counting the number of ones from the least significant bit to the first zero 400/// bit. Ex. CountTrailingOnes_32(0x00FF00FF) == 8. 401/// Returns 32 if the word is all ones. 402inline unsigned CountTrailingOnes_32(uint32_t Value) { 403 return countTrailingZeros(~Value); 404} 405 406/// CountTrailingOnes_64 - This function performs the operation 407/// of counting the number of ones from the least significant bit to the first 408/// zero bit (64 bit edition.) 409/// Returns 64 if the word is all ones. 410inline unsigned CountTrailingOnes_64(uint64_t Value) { 411 return countTrailingZeros(~Value); 412} 413 414/// CountPopulation_32 - this function counts the number of set bits in a value. 415/// Ex. CountPopulation(0xF000F000) = 8 416/// Returns 0 if the word is zero. 417inline unsigned CountPopulation_32(uint32_t Value) { 418#if __GNUC__ >= 4 419 return __builtin_popcount(Value); 420#else 421 uint32_t v = Value - ((Value >> 1) & 0x55555555); 422 v = (v & 0x33333333) + ((v >> 2) & 0x33333333); 423 return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; 424#endif 425} 426 427/// CountPopulation_64 - this function counts the number of set bits in a value, 428/// (64 bit edition.) 429inline unsigned CountPopulation_64(uint64_t Value) { 430#if __GNUC__ >= 4 431 return __builtin_popcountll(Value); 432#else 433 uint64_t v = Value - ((Value >> 1) & 0x5555555555555555ULL); 434 v = (v & 0x3333333333333333ULL) + ((v >> 2) & 0x3333333333333333ULL); 435 v = (v + (v >> 4)) & 0x0F0F0F0F0F0F0F0FULL; 436 return unsigned((uint64_t)(v * 0x0101010101010101ULL) >> 56); 437#endif 438} 439 440/// Log2_32 - This function returns the floor log base 2 of the specified value, 441/// -1 if the value is zero. (32 bit edition.) 442/// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2 443inline unsigned Log2_32(uint32_t Value) { 444 return 31 - countLeadingZeros(Value); 445} 446 447/// Log2_64 - This function returns the floor log base 2 of the specified value, 448/// -1 if the value is zero. (64 bit edition.) 449inline unsigned Log2_64(uint64_t Value) { 450 return 63 - countLeadingZeros(Value); 451} 452 453/// Log2_32_Ceil - This function returns the ceil log base 2 of the specified 454/// value, 32 if the value is zero. (32 bit edition). 455/// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3 456inline unsigned Log2_32_Ceil(uint32_t Value) { 457 return 32 - countLeadingZeros(Value - 1); 458} 459 460/// Log2_64_Ceil - This function returns the ceil log base 2 of the specified 461/// value, 64 if the value is zero. (64 bit edition.) 462inline unsigned Log2_64_Ceil(uint64_t Value) { 463 return 64 - countLeadingZeros(Value - 1); 464} 465 466/// GreatestCommonDivisor64 - Return the greatest common divisor of the two 467/// values using Euclid's algorithm. 468inline uint64_t GreatestCommonDivisor64(uint64_t A, uint64_t B) { 469 while (B) { 470 uint64_t T = B; 471 B = A % B; 472 A = T; 473 } 474 return A; 475} 476 477/// BitsToDouble - This function takes a 64-bit integer and returns the bit 478/// equivalent double. 479inline double BitsToDouble(uint64_t Bits) { 480 union { 481 uint64_t L; 482 double D; 483 } T; 484 T.L = Bits; 485 return T.D; 486} 487 488/// BitsToFloat - This function takes a 32-bit integer and returns the bit 489/// equivalent float. 490inline float BitsToFloat(uint32_t Bits) { 491 union { 492 uint32_t I; 493 float F; 494 } T; 495 T.I = Bits; 496 return T.F; 497} 498 499/// DoubleToBits - This function takes a double and returns the bit 500/// equivalent 64-bit integer. Note that copying doubles around 501/// changes the bits of NaNs on some hosts, notably x86, so this 502/// routine cannot be used if these bits are needed. 503inline uint64_t DoubleToBits(double Double) { 504 union { 505 uint64_t L; 506 double D; 507 } T; 508 T.D = Double; 509 return T.L; 510} 511 512/// FloatToBits - This function takes a float and returns the bit 513/// equivalent 32-bit integer. Note that copying floats around 514/// changes the bits of NaNs on some hosts, notably x86, so this 515/// routine cannot be used if these bits are needed. 516inline uint32_t FloatToBits(float Float) { 517 union { 518 uint32_t I; 519 float F; 520 } T; 521 T.F = Float; 522 return T.I; 523} 524 525/// Platform-independent wrappers for the C99 isnan() function. 526int IsNAN(float f); 527int IsNAN(double d); 528 529/// Platform-independent wrappers for the C99 isinf() function. 530int IsInf(float f); 531int IsInf(double d); 532 533/// MinAlign - A and B are either alignments or offsets. Return the minimum 534/// alignment that may be assumed after adding the two together. 535inline uint64_t MinAlign(uint64_t A, uint64_t B) { 536 // The largest power of 2 that divides both A and B. 537 // 538 // Replace "-Value" by "1+~Value" in the following commented code to avoid 539 // MSVC warning C4146 540 // return (A | B) & -(A | B); 541 return (A | B) & (1 + ~(A | B)); 542} 543 544/// NextPowerOf2 - Returns the next power of two (in 64-bits) 545/// that is strictly greater than A. Returns zero on overflow. 546inline uint64_t NextPowerOf2(uint64_t A) { 547 A |= (A >> 1); 548 A |= (A >> 2); 549 A |= (A >> 4); 550 A |= (A >> 8); 551 A |= (A >> 16); 552 A |= (A >> 32); 553 return A + 1; 554} 555 556/// Returns the next integer (mod 2**64) that is greater than or equal to 557/// \p Value and is a multiple of \p Align. \p Align must be non-zero. 558/// 559/// Examples: 560/// \code 561/// RoundUpToAlignment(5, 8) = 8 562/// RoundUpToAlignment(17, 8) = 24 563/// RoundUpToAlignment(~0LL, 8) = 0 564/// \endcode 565inline uint64_t RoundUpToAlignment(uint64_t Value, uint64_t Align) { 566 return ((Value + Align - 1) / Align) * Align; 567} 568 569/// Returns the offset to the next integer (mod 2**64) that is greater than 570/// or equal to \p Value and is a multiple of \p Align. \p Align must be 571/// non-zero. 572inline uint64_t OffsetToAlignment(uint64_t Value, uint64_t Align) { 573 return RoundUpToAlignment(Value, Align) - Value; 574} 575 576/// abs64 - absolute value of a 64-bit int. Not all environments support 577/// "abs" on whatever their name for the 64-bit int type is. The absolute 578/// value of the largest negative number is undefined, as with "abs". 579inline int64_t abs64(int64_t x) { 580 return (x < 0) ? -x : x; 581} 582 583/// SignExtend32 - Sign extend B-bit number x to 32-bit int. 584/// Usage int32_t r = SignExtend32<5>(x); 585template <unsigned B> inline int32_t SignExtend32(uint32_t x) { 586 return int32_t(x << (32 - B)) >> (32 - B); 587} 588 589/// \brief Sign extend number in the bottom B bits of X to a 32-bit int. 590/// Requires 0 < B <= 32. 591inline int32_t SignExtend32(uint32_t X, unsigned B) { 592 return int32_t(X << (32 - B)) >> (32 - B); 593} 594 595/// SignExtend64 - Sign extend B-bit number x to 64-bit int. 596/// Usage int64_t r = SignExtend64<5>(x); 597template <unsigned B> inline int64_t SignExtend64(uint64_t x) { 598 return int64_t(x << (64 - B)) >> (64 - B); 599} 600 601/// \brief Sign extend number in the bottom B bits of X to a 64-bit int. 602/// Requires 0 < B <= 64. 603inline int64_t SignExtend64(uint64_t X, unsigned B) { 604 return int64_t(X << (64 - B)) >> (64 - B); 605} 606 607#if defined(_MSC_VER) 608 // Visual Studio defines the HUGE_VAL class of macros using purposeful 609 // constant arithmetic overflow, which it then warns on when encountered. 610 const float huge_valf = std::numeric_limits<float>::infinity(); 611#else 612 const float huge_valf = HUGE_VALF; 613#endif 614} // End llvm namespace 615 616#endif 617