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