Home | History | Annotate | Download | only in Support
      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 <algorithm>
     20 #include <cassert>
     21 #include <cstring>
     22 #include <type_traits>
     23 #include <limits>
     24 
     25 #ifdef _MSC_VER
     26 #include <intrin.h>
     27 #endif
     28 
     29 #ifdef __ANDROID_NDK__
     30 #include <android/api-level.h>
     31 #endif
     32 
     33 namespace llvm {
     34 /// \brief The behavior an operation has on an input of 0.
     35 enum ZeroBehavior {
     36   /// \brief The returned value is undefined.
     37   ZB_Undefined,
     38   /// \brief The returned value is numeric_limits<T>::max()
     39   ZB_Max,
     40   /// \brief The returned value is numeric_limits<T>::digits
     41   ZB_Width
     42 };
     43 
     44 namespace detail {
     45 template <typename T, std::size_t SizeOfT> struct TrailingZerosCounter {
     46   static std::size_t count(T Val, ZeroBehavior) {
     47     if (!Val)
     48       return std::numeric_limits<T>::digits;
     49     if (Val & 0x1)
     50       return 0;
     51 
     52     // Bisection method.
     53     std::size_t ZeroBits = 0;
     54     T Shift = std::numeric_limits<T>::digits >> 1;
     55     T Mask = std::numeric_limits<T>::max() >> Shift;
     56     while (Shift) {
     57       if ((Val & Mask) == 0) {
     58         Val >>= Shift;
     59         ZeroBits |= Shift;
     60       }
     61       Shift >>= 1;
     62       Mask >>= Shift;
     63     }
     64     return ZeroBits;
     65   }
     66 };
     67 
     68 #if __GNUC__ >= 4 || defined(_MSC_VER)
     69 template <typename T> struct TrailingZerosCounter<T, 4> {
     70   static std::size_t count(T Val, ZeroBehavior ZB) {
     71     if (ZB != ZB_Undefined && Val == 0)
     72       return 32;
     73 
     74 #if __has_builtin(__builtin_ctz) || LLVM_GNUC_PREREQ(4, 0, 0)
     75     return __builtin_ctz(Val);
     76 #elif defined(_MSC_VER)
     77     unsigned long Index;
     78     _BitScanForward(&Index, Val);
     79     return Index;
     80 #endif
     81   }
     82 };
     83 
     84 #if !defined(_MSC_VER) || defined(_M_X64)
     85 template <typename T> struct TrailingZerosCounter<T, 8> {
     86   static std::size_t count(T Val, ZeroBehavior ZB) {
     87     if (ZB != ZB_Undefined && Val == 0)
     88       return 64;
     89 
     90 #if __has_builtin(__builtin_ctzll) || LLVM_GNUC_PREREQ(4, 0, 0)
     91     return __builtin_ctzll(Val);
     92 #elif defined(_MSC_VER)
     93     unsigned long Index;
     94     _BitScanForward64(&Index, Val);
     95     return Index;
     96 #endif
     97   }
     98 };
     99 #endif
    100 #endif
    101 } // namespace detail
    102 
    103 /// \brief Count number of 0's from the least significant bit to the most
    104 ///   stopping at the first 1.
    105 ///
    106 /// Only unsigned integral types are allowed.
    107 ///
    108 /// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are
    109 ///   valid arguments.
    110 template <typename T>
    111 std::size_t countTrailingZeros(T Val, ZeroBehavior ZB = ZB_Width) {
    112   static_assert(std::numeric_limits<T>::is_integer &&
    113                     !std::numeric_limits<T>::is_signed,
    114                 "Only unsigned integral types are allowed.");
    115   return detail::TrailingZerosCounter<T, sizeof(T)>::count(Val, ZB);
    116 }
    117 
    118 namespace detail {
    119 template <typename T, std::size_t SizeOfT> struct LeadingZerosCounter {
    120   static std::size_t count(T Val, ZeroBehavior) {
    121     if (!Val)
    122       return std::numeric_limits<T>::digits;
    123 
    124     // Bisection method.
    125     std::size_t ZeroBits = 0;
    126     for (T Shift = std::numeric_limits<T>::digits >> 1; Shift; Shift >>= 1) {
    127       T Tmp = Val >> Shift;
    128       if (Tmp)
    129         Val = Tmp;
    130       else
    131         ZeroBits |= Shift;
    132     }
    133     return ZeroBits;
    134   }
    135 };
    136 
    137 #if __GNUC__ >= 4 || defined(_MSC_VER)
    138 template <typename T> struct LeadingZerosCounter<T, 4> {
    139   static std::size_t count(T Val, ZeroBehavior ZB) {
    140     if (ZB != ZB_Undefined && Val == 0)
    141       return 32;
    142 
    143 #if __has_builtin(__builtin_clz) || LLVM_GNUC_PREREQ(4, 0, 0)
    144     return __builtin_clz(Val);
    145 #elif defined(_MSC_VER)
    146     unsigned long Index;
    147     _BitScanReverse(&Index, Val);
    148     return Index ^ 31;
    149 #endif
    150   }
    151 };
    152 
    153 #if !defined(_MSC_VER) || defined(_M_X64)
    154 template <typename T> struct LeadingZerosCounter<T, 8> {
    155   static std::size_t count(T Val, ZeroBehavior ZB) {
    156     if (ZB != ZB_Undefined && Val == 0)
    157       return 64;
    158 
    159 #if __has_builtin(__builtin_clzll) || LLVM_GNUC_PREREQ(4, 0, 0)
    160     return __builtin_clzll(Val);
    161 #elif defined(_MSC_VER)
    162     unsigned long Index;
    163     _BitScanReverse64(&Index, Val);
    164     return Index ^ 63;
    165 #endif
    166   }
    167 };
    168 #endif
    169 #endif
    170 } // namespace detail
    171 
    172 /// \brief Count number of 0's from the most significant bit to the least
    173 ///   stopping at the first 1.
    174 ///
    175 /// Only unsigned integral types are allowed.
    176 ///
    177 /// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are
    178 ///   valid arguments.
    179 template <typename T>
    180 std::size_t countLeadingZeros(T Val, ZeroBehavior ZB = ZB_Width) {
    181   static_assert(std::numeric_limits<T>::is_integer &&
    182                     !std::numeric_limits<T>::is_signed,
    183                 "Only unsigned integral types are allowed.");
    184   return detail::LeadingZerosCounter<T, sizeof(T)>::count(Val, ZB);
    185 }
    186 
    187 /// \brief Get the index of the first set bit starting from the least
    188 ///   significant bit.
    189 ///
    190 /// Only unsigned integral types are allowed.
    191 ///
    192 /// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are
    193 ///   valid arguments.
    194 template <typename T> T findFirstSet(T Val, ZeroBehavior ZB = ZB_Max) {
    195   if (ZB == ZB_Max && Val == 0)
    196     return std::numeric_limits<T>::max();
    197 
    198   return countTrailingZeros(Val, ZB_Undefined);
    199 }
    200 
    201 /// \brief Get the index of the last set bit starting from the least
    202 ///   significant bit.
    203 ///
    204 /// Only unsigned integral types are allowed.
    205 ///
    206 /// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are
    207 ///   valid arguments.
    208 template <typename T> T 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 /// \brief Macro compressed bit reversal table for 256 bits.
    219 ///
    220 /// http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable
    221 static const unsigned char BitReverseTable256[256] = {
    222 #define R2(n) n, n + 2 * 64, n + 1 * 64, n + 3 * 64
    223 #define R4(n) R2(n), R2(n + 2 * 16), R2(n + 1 * 16), R2(n + 3 * 16)
    224 #define R6(n) R4(n), R4(n + 2 * 4), R4(n + 1 * 4), R4(n + 3 * 4)
    225   R6(0), R6(2), R6(1), R6(3)
    226 #undef R2
    227 #undef R4
    228 #undef R6
    229 };
    230 
    231 /// \brief Reverse the bits in \p Val.
    232 template <typename T>
    233 T reverseBits(T Val) {
    234   unsigned char in[sizeof(Val)];
    235   unsigned char out[sizeof(Val)];
    236   std::memcpy(in, &Val, sizeof(Val));
    237   for (unsigned i = 0; i < sizeof(Val); ++i)
    238     out[(sizeof(Val) - i) - 1] = BitReverseTable256[in[i]];
    239   std::memcpy(&Val, out, sizeof(Val));
    240   return Val;
    241 }
    242 
    243 // NOTE: The following support functions use the _32/_64 extensions instead of
    244 // type overloading so that signed and unsigned integers can be used without
    245 // ambiguity.
    246 
    247 /// Hi_32 - This function returns the high 32 bits of a 64 bit value.
    248 inline uint32_t Hi_32(uint64_t Value) {
    249   return static_cast<uint32_t>(Value >> 32);
    250 }
    251 
    252 /// Lo_32 - This function returns the low 32 bits of a 64 bit value.
    253 inline uint32_t Lo_32(uint64_t Value) {
    254   return static_cast<uint32_t>(Value);
    255 }
    256 
    257 /// Make_64 - This functions makes a 64-bit integer from a high / low pair of
    258 ///           32-bit integers.
    259 inline uint64_t Make_64(uint32_t High, uint32_t Low) {
    260   return ((uint64_t)High << 32) | (uint64_t)Low;
    261 }
    262 
    263 /// isInt - Checks if an integer fits into the given bit width.
    264 template<unsigned N>
    265 inline bool isInt(int64_t x) {
    266   return N >= 64 || (-(INT64_C(1)<<(N-1)) <= x && x < (INT64_C(1)<<(N-1)));
    267 }
    268 // Template specializations to get better code for common cases.
    269 template<>
    270 inline bool isInt<8>(int64_t x) {
    271   return static_cast<int8_t>(x) == x;
    272 }
    273 template<>
    274 inline bool isInt<16>(int64_t x) {
    275   return static_cast<int16_t>(x) == x;
    276 }
    277 template<>
    278 inline bool isInt<32>(int64_t x) {
    279   return static_cast<int32_t>(x) == x;
    280 }
    281 
    282 /// isShiftedInt<N,S> - Checks if a signed integer is an N bit number shifted
    283 ///                     left by S.
    284 template<unsigned N, unsigned S>
    285 inline bool isShiftedInt(int64_t x) {
    286   return isInt<N+S>(x) && (x % (1<<S) == 0);
    287 }
    288 
    289 /// isUInt - Checks if an unsigned integer fits into the given bit width.
    290 template<unsigned N>
    291 inline bool isUInt(uint64_t x) {
    292   return N >= 64 || x < (UINT64_C(1)<<(N));
    293 }
    294 // Template specializations to get better code for common cases.
    295 template<>
    296 inline bool isUInt<8>(uint64_t x) {
    297   return static_cast<uint8_t>(x) == x;
    298 }
    299 template<>
    300 inline bool isUInt<16>(uint64_t x) {
    301   return static_cast<uint16_t>(x) == x;
    302 }
    303 template<>
    304 inline bool isUInt<32>(uint64_t x) {
    305   return static_cast<uint32_t>(x) == x;
    306 }
    307 
    308 /// isShiftedUInt<N,S> - Checks if a unsigned integer is an N bit number shifted
    309 ///                     left by S.
    310 template<unsigned N, unsigned S>
    311 inline bool isShiftedUInt(uint64_t x) {
    312   return isUInt<N+S>(x) && (x % (1<<S) == 0);
    313 }
    314 
    315 /// Gets the maximum value for a N-bit unsigned integer.
    316 inline uint64_t maxUIntN(uint64_t N) {
    317   assert(N > 0 && N <= 64 && "integer width out of range");
    318 
    319   return (UINT64_C(1) << N) - 1;
    320 }
    321 
    322 /// Gets the minimum value for a N-bit signed integer.
    323 inline int64_t minIntN(int64_t N) {
    324   assert(N > 0 && N <= 64 && "integer width out of range");
    325 
    326   return -(INT64_C(1)<<(N-1));
    327 }
    328 
    329 /// Gets the maximum value for a N-bit signed integer.
    330 inline int64_t maxIntN(int64_t N) {
    331   assert(N > 0 && N <= 64 && "integer width out of range");
    332 
    333   return (INT64_C(1)<<(N-1)) - 1;
    334 }
    335 
    336 /// isUIntN - Checks if an unsigned integer fits into the given (dynamic)
    337 /// bit width.
    338 inline bool isUIntN(unsigned N, uint64_t x) {
    339   return N >= 64 || x <= maxUIntN(N);
    340 }
    341 
    342 /// isIntN - Checks if an signed integer fits into the given (dynamic)
    343 /// bit width.
    344 inline bool isIntN(unsigned N, int64_t x) {
    345   return N >= 64 || (minIntN(N) <= x && x <= maxIntN(N));
    346 }
    347 
    348 /// isMask_32 - This function returns true if the argument is a non-empty
    349 /// sequence of ones starting at the least significant bit with the remainder
    350 /// zero (32 bit version).  Ex. isMask_32(0x0000FFFFU) == true.
    351 inline bool isMask_32(uint32_t Value) {
    352   return Value && ((Value + 1) & Value) == 0;
    353 }
    354 
    355 /// isMask_64 - This function returns true if the argument is a non-empty
    356 /// sequence of ones starting at the least significant bit with the remainder
    357 /// zero (64 bit version).
    358 inline bool isMask_64(uint64_t Value) {
    359   return Value && ((Value + 1) & Value) == 0;
    360 }
    361 
    362 /// isShiftedMask_32 - This function returns true if the argument contains a
    363 /// non-empty sequence of ones with the remainder zero (32 bit version.)
    364 /// Ex. isShiftedMask_32(0x0000FF00U) == true.
    365 inline bool isShiftedMask_32(uint32_t Value) {
    366   return Value && isMask_32((Value - 1) | Value);
    367 }
    368 
    369 /// isShiftedMask_64 - This function returns true if the argument contains a
    370 /// non-empty sequence of ones with the remainder zero (64 bit version.)
    371 inline bool isShiftedMask_64(uint64_t Value) {
    372   return Value && isMask_64((Value - 1) | Value);
    373 }
    374 
    375 /// isPowerOf2_32 - This function returns true if the argument is a power of
    376 /// two > 0. Ex. isPowerOf2_32(0x00100000U) == true (32 bit edition.)
    377 inline bool isPowerOf2_32(uint32_t Value) {
    378   return Value && !(Value & (Value - 1));
    379 }
    380 
    381 /// isPowerOf2_64 - This function returns true if the argument is a power of two
    382 /// > 0 (64 bit edition.)
    383 inline bool isPowerOf2_64(uint64_t Value) {
    384   return Value && !(Value & (Value - int64_t(1L)));
    385 }
    386 
    387 /// ByteSwap_16 - This function returns a byte-swapped representation of the
    388 /// 16-bit argument, Value.
    389 inline uint16_t ByteSwap_16(uint16_t Value) {
    390   return sys::SwapByteOrder_16(Value);
    391 }
    392 
    393 /// ByteSwap_32 - This function returns a byte-swapped representation of the
    394 /// 32-bit argument, Value.
    395 inline uint32_t ByteSwap_32(uint32_t Value) {
    396   return sys::SwapByteOrder_32(Value);
    397 }
    398 
    399 /// ByteSwap_64 - This function returns a byte-swapped representation of the
    400 /// 64-bit argument, Value.
    401 inline uint64_t ByteSwap_64(uint64_t Value) {
    402   return sys::SwapByteOrder_64(Value);
    403 }
    404 
    405 /// \brief Count the number of ones from the most significant bit to the first
    406 /// zero bit.
    407 ///
    408 /// Ex. CountLeadingOnes(0xFF0FFF00) == 8.
    409 /// Only unsigned integral types are allowed.
    410 ///
    411 /// \param ZB the behavior on an input of all ones. Only ZB_Width and
    412 /// ZB_Undefined are valid arguments.
    413 template <typename T>
    414 std::size_t countLeadingOnes(T Value, ZeroBehavior ZB = ZB_Width) {
    415   static_assert(std::numeric_limits<T>::is_integer &&
    416                     !std::numeric_limits<T>::is_signed,
    417                 "Only unsigned integral types are allowed.");
    418   return countLeadingZeros(~Value, ZB);
    419 }
    420 
    421 /// \brief Count the number of ones from the least significant bit to the first
    422 /// zero bit.
    423 ///
    424 /// Ex. countTrailingOnes(0x00FF00FF) == 8.
    425 /// Only unsigned integral types are allowed.
    426 ///
    427 /// \param ZB the behavior on an input of all ones. Only ZB_Width and
    428 /// ZB_Undefined are valid arguments.
    429 template <typename T>
    430 std::size_t countTrailingOnes(T Value, ZeroBehavior ZB = ZB_Width) {
    431   static_assert(std::numeric_limits<T>::is_integer &&
    432                     !std::numeric_limits<T>::is_signed,
    433                 "Only unsigned integral types are allowed.");
    434   return countTrailingZeros(~Value, ZB);
    435 }
    436 
    437 namespace detail {
    438 template <typename T, std::size_t SizeOfT> struct PopulationCounter {
    439   static unsigned count(T Value) {
    440     // Generic version, forward to 32 bits.
    441     static_assert(SizeOfT <= 4, "Not implemented!");
    442 #if __GNUC__ >= 4
    443     return __builtin_popcount(Value);
    444 #else
    445     uint32_t v = Value;
    446     v = v - ((v >> 1) & 0x55555555);
    447     v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
    448     return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
    449 #endif
    450   }
    451 };
    452 
    453 template <typename T> struct PopulationCounter<T, 8> {
    454   static unsigned count(T Value) {
    455 #if __GNUC__ >= 4
    456     return __builtin_popcountll(Value);
    457 #else
    458     uint64_t v = Value;
    459     v = v - ((v >> 1) & 0x5555555555555555ULL);
    460     v = (v & 0x3333333333333333ULL) + ((v >> 2) & 0x3333333333333333ULL);
    461     v = (v + (v >> 4)) & 0x0F0F0F0F0F0F0F0FULL;
    462     return unsigned((uint64_t)(v * 0x0101010101010101ULL) >> 56);
    463 #endif
    464   }
    465 };
    466 } // namespace detail
    467 
    468 /// \brief Count the number of set bits in a value.
    469 /// Ex. countPopulation(0xF000F000) = 8
    470 /// Returns 0 if the word is zero.
    471 template <typename T>
    472 inline unsigned countPopulation(T Value) {
    473   static_assert(std::numeric_limits<T>::is_integer &&
    474                     !std::numeric_limits<T>::is_signed,
    475                 "Only unsigned integral types are allowed.");
    476   return detail::PopulationCounter<T, sizeof(T)>::count(Value);
    477 }
    478 
    479 /// Log2 - This function returns the log base 2 of the specified value
    480 inline double Log2(double Value) {
    481 #if defined(__ANDROID_API__) && __ANDROID_API__ < 18
    482   return __builtin_log(Value) / __builtin_log(2.0);
    483 #else
    484   return log2(Value);
    485 #endif
    486 }
    487 
    488 /// Log2_32 - This function returns the floor log base 2 of the specified value,
    489 /// -1 if the value is zero. (32 bit edition.)
    490 /// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2
    491 inline unsigned Log2_32(uint32_t Value) {
    492   return 31 - countLeadingZeros(Value);
    493 }
    494 
    495 /// Log2_64 - This function returns the floor log base 2 of the specified value,
    496 /// -1 if the value is zero. (64 bit edition.)
    497 inline unsigned Log2_64(uint64_t Value) {
    498   return 63 - countLeadingZeros(Value);
    499 }
    500 
    501 /// Log2_32_Ceil - This function returns the ceil log base 2 of the specified
    502 /// value, 32 if the value is zero. (32 bit edition).
    503 /// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3
    504 inline unsigned Log2_32_Ceil(uint32_t Value) {
    505   return 32 - countLeadingZeros(Value - 1);
    506 }
    507 
    508 /// Log2_64_Ceil - This function returns the ceil log base 2 of the specified
    509 /// value, 64 if the value is zero. (64 bit edition.)
    510 inline unsigned Log2_64_Ceil(uint64_t Value) {
    511   return 64 - countLeadingZeros(Value - 1);
    512 }
    513 
    514 /// GreatestCommonDivisor64 - Return the greatest common divisor of the two
    515 /// values using Euclid's algorithm.
    516 inline uint64_t GreatestCommonDivisor64(uint64_t A, uint64_t B) {
    517   while (B) {
    518     uint64_t T = B;
    519     B = A % B;
    520     A = T;
    521   }
    522   return A;
    523 }
    524 
    525 /// BitsToDouble - This function takes a 64-bit integer and returns the bit
    526 /// equivalent double.
    527 inline double BitsToDouble(uint64_t Bits) {
    528   union {
    529     uint64_t L;
    530     double D;
    531   } T;
    532   T.L = Bits;
    533   return T.D;
    534 }
    535 
    536 /// BitsToFloat - This function takes a 32-bit integer and returns the bit
    537 /// equivalent float.
    538 inline float BitsToFloat(uint32_t Bits) {
    539   union {
    540     uint32_t I;
    541     float F;
    542   } T;
    543   T.I = Bits;
    544   return T.F;
    545 }
    546 
    547 /// DoubleToBits - This function takes a double and returns the bit
    548 /// equivalent 64-bit integer.  Note that copying doubles around
    549 /// changes the bits of NaNs on some hosts, notably x86, so this
    550 /// routine cannot be used if these bits are needed.
    551 inline uint64_t DoubleToBits(double Double) {
    552   union {
    553     uint64_t L;
    554     double D;
    555   } T;
    556   T.D = Double;
    557   return T.L;
    558 }
    559 
    560 /// FloatToBits - This function takes a float and returns the bit
    561 /// equivalent 32-bit integer.  Note that copying floats around
    562 /// changes the bits of NaNs on some hosts, notably x86, so this
    563 /// routine cannot be used if these bits are needed.
    564 inline uint32_t FloatToBits(float Float) {
    565   union {
    566     uint32_t I;
    567     float F;
    568   } T;
    569   T.F = Float;
    570   return T.I;
    571 }
    572 
    573 /// MinAlign - A and B are either alignments or offsets.  Return the minimum
    574 /// alignment that may be assumed after adding the two together.
    575 inline uint64_t MinAlign(uint64_t A, uint64_t B) {
    576   // The largest power of 2 that divides both A and B.
    577   //
    578   // Replace "-Value" by "1+~Value" in the following commented code to avoid
    579   // MSVC warning C4146
    580   //    return (A | B) & -(A | B);
    581   return (A | B) & (1 + ~(A | B));
    582 }
    583 
    584 /// \brief Aligns \c Addr to \c Alignment bytes, rounding up.
    585 ///
    586 /// Alignment should be a power of two.  This method rounds up, so
    587 /// alignAddr(7, 4) == 8 and alignAddr(8, 4) == 8.
    588 inline uintptr_t alignAddr(const void *Addr, size_t Alignment) {
    589   assert(Alignment && isPowerOf2_64((uint64_t)Alignment) &&
    590          "Alignment is not a power of two!");
    591 
    592   assert((uintptr_t)Addr + Alignment - 1 >= (uintptr_t)Addr);
    593 
    594   return (((uintptr_t)Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1));
    595 }
    596 
    597 /// \brief Returns the necessary adjustment for aligning \c Ptr to \c Alignment
    598 /// bytes, rounding up.
    599 inline size_t alignmentAdjustment(const void *Ptr, size_t Alignment) {
    600   return alignAddr(Ptr, Alignment) - (uintptr_t)Ptr;
    601 }
    602 
    603 /// NextPowerOf2 - Returns the next power of two (in 64-bits)
    604 /// that is strictly greater than A.  Returns zero on overflow.
    605 inline uint64_t NextPowerOf2(uint64_t A) {
    606   A |= (A >> 1);
    607   A |= (A >> 2);
    608   A |= (A >> 4);
    609   A |= (A >> 8);
    610   A |= (A >> 16);
    611   A |= (A >> 32);
    612   return A + 1;
    613 }
    614 
    615 /// Returns the power of two which is less than or equal to the given value.
    616 /// Essentially, it is a floor operation across the domain of powers of two.
    617 inline uint64_t PowerOf2Floor(uint64_t A) {
    618   if (!A) return 0;
    619   return 1ull << (63 - countLeadingZeros(A, ZB_Undefined));
    620 }
    621 
    622 /// Returns the next integer (mod 2**64) that is greater than or equal to
    623 /// \p Value and is a multiple of \p Align. \p Align must be non-zero.
    624 ///
    625 /// If non-zero \p Skew is specified, the return value will be a minimal
    626 /// integer that is greater than or equal to \p Value and equal to
    627 /// \p Align * N + \p Skew for some integer N. If \p Skew is larger than
    628 /// \p Align, its value is adjusted to '\p Skew mod \p Align'.
    629 ///
    630 /// Examples:
    631 /// \code
    632 ///   alignTo(5, 8) = 8
    633 ///   alignTo(17, 8) = 24
    634 ///   alignTo(~0LL, 8) = 0
    635 ///   alignTo(321, 255) = 510
    636 ///
    637 ///   alignTo(5, 8, 7) = 7
    638 ///   alignTo(17, 8, 1) = 17
    639 ///   alignTo(~0LL, 8, 3) = 3
    640 ///   alignTo(321, 255, 42) = 552
    641 /// \endcode
    642 inline uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew = 0) {
    643   Skew %= Align;
    644   return (Value + Align - 1 - Skew) / Align * Align + Skew;
    645 }
    646 
    647 /// Returns the largest uint64_t less than or equal to \p Value and is
    648 /// \p Skew mod \p Align. \p Align must be non-zero
    649 inline uint64_t alignDown(uint64_t Value, uint64_t Align, uint64_t Skew = 0) {
    650   Skew %= Align;
    651   return (Value - Skew) / Align * Align + Skew;
    652 }
    653 
    654 /// Returns the offset to the next integer (mod 2**64) that is greater than
    655 /// or equal to \p Value and is a multiple of \p Align. \p Align must be
    656 /// non-zero.
    657 inline uint64_t OffsetToAlignment(uint64_t Value, uint64_t Align) {
    658   return alignTo(Value, Align) - Value;
    659 }
    660 
    661 /// SignExtend32 - Sign extend B-bit number x to 32-bit int.
    662 /// Usage int32_t r = SignExtend32<5>(x);
    663 template <unsigned B> inline int32_t SignExtend32(uint32_t x) {
    664   return int32_t(x << (32 - B)) >> (32 - B);
    665 }
    666 
    667 /// \brief Sign extend number in the bottom B bits of X to a 32-bit int.
    668 /// Requires 0 < B <= 32.
    669 inline int32_t SignExtend32(uint32_t X, unsigned B) {
    670   return int32_t(X << (32 - B)) >> (32 - B);
    671 }
    672 
    673 /// SignExtend64 - Sign extend B-bit number x to 64-bit int.
    674 /// Usage int64_t r = SignExtend64<5>(x);
    675 template <unsigned B> inline int64_t SignExtend64(uint64_t x) {
    676   return int64_t(x << (64 - B)) >> (64 - B);
    677 }
    678 
    679 /// \brief Sign extend number in the bottom B bits of X to a 64-bit int.
    680 /// Requires 0 < B <= 64.
    681 inline int64_t SignExtend64(uint64_t X, unsigned B) {
    682   return int64_t(X << (64 - B)) >> (64 - B);
    683 }
    684 
    685 /// \brief Subtract two unsigned integers, X and Y, of type T and return their
    686 /// absolute value.
    687 template <typename T>
    688 typename std::enable_if<std::is_unsigned<T>::value, T>::type
    689 AbsoluteDifference(T X, T Y) {
    690   return std::max(X, Y) - std::min(X, Y);
    691 }
    692 
    693 /// \brief Add two unsigned integers, X and Y, of type T.
    694 /// Clamp the result to the maximum representable value of T on overflow.
    695 /// ResultOverflowed indicates if the result is larger than the maximum
    696 /// representable value of type T.
    697 template <typename T>
    698 typename std::enable_if<std::is_unsigned<T>::value, T>::type
    699 SaturatingAdd(T X, T Y, bool *ResultOverflowed = nullptr) {
    700   bool Dummy;
    701   bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
    702   // Hacker's Delight, p. 29
    703   T Z = X + Y;
    704   Overflowed = (Z < X || Z < Y);
    705   if (Overflowed)
    706     return std::numeric_limits<T>::max();
    707   else
    708     return Z;
    709 }
    710 
    711 /// \brief Multiply two unsigned integers, X and Y, of type T.
    712 /// Clamp the result to the maximum representable value of T on overflow.
    713 /// ResultOverflowed indicates if the result is larger than the maximum
    714 /// representable value of type T.
    715 template <typename T>
    716 typename std::enable_if<std::is_unsigned<T>::value, T>::type
    717 SaturatingMultiply(T X, T Y, bool *ResultOverflowed = nullptr) {
    718   bool Dummy;
    719   bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
    720 
    721   // Hacker's Delight, p. 30 has a different algorithm, but we don't use that
    722   // because it fails for uint16_t (where multiplication can have undefined
    723   // behavior due to promotion to int), and requires a division in addition
    724   // to the multiplication.
    725 
    726   Overflowed = false;
    727 
    728   // Log2(Z) would be either Log2Z or Log2Z + 1.
    729   // Special case: if X or Y is 0, Log2_64 gives -1, and Log2Z
    730   // will necessarily be less than Log2Max as desired.
    731   int Log2Z = Log2_64(X) + Log2_64(Y);
    732   const T Max = std::numeric_limits<T>::max();
    733   int Log2Max = Log2_64(Max);
    734   if (Log2Z < Log2Max) {
    735     return X * Y;
    736   }
    737   if (Log2Z > Log2Max) {
    738     Overflowed = true;
    739     return Max;
    740   }
    741 
    742   // We're going to use the top bit, and maybe overflow one
    743   // bit past it. Multiply all but the bottom bit then add
    744   // that on at the end.
    745   T Z = (X >> 1) * Y;
    746   if (Z & ~(Max >> 1)) {
    747     Overflowed = true;
    748     return Max;
    749   }
    750   Z <<= 1;
    751   if (X & 1)
    752     return SaturatingAdd(Z, Y, ResultOverflowed);
    753 
    754   return Z;
    755 }
    756 
    757 /// \brief Multiply two unsigned integers, X and Y, and add the unsigned
    758 /// integer, A to the product. Clamp the result to the maximum representable
    759 /// value of T on overflow. ResultOverflowed indicates if the result is larger
    760 /// than the maximum representable value of type T.
    761 /// Note that this is purely a convenience function as there is no distinction
    762 /// where overflow occurred in a 'fused' multiply-add for unsigned numbers.
    763 template <typename T>
    764 typename std::enable_if<std::is_unsigned<T>::value, T>::type
    765 SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed = nullptr) {
    766   bool Dummy;
    767   bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
    768 
    769   T Product = SaturatingMultiply(X, Y, &Overflowed);
    770   if (Overflowed)
    771     return Product;
    772 
    773   return SaturatingAdd(A, Product, &Overflowed);
    774 }
    775 
    776 extern const float huge_valf;
    777 } // End llvm namespace
    778 
    779 #endif
    780