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