Jan Voung | 8acded0 | 2014-09-22 18:02:25 -0700 | [diff] [blame] | 1 | //===- subzero/src/IceUtils.h - Utility functions ---------------*- C++ -*-===// |
| 2 | // |
| 3 | // The Subzero Code Generator |
| 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 declares some utility functions |
| 11 | // |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
| 14 | #ifndef SUBZERO_SRC_ICEUTILS_H |
| 15 | #define SUBZERO_SRC_ICEUTILS_H |
| 16 | |
| 17 | #include <climits> |
| 18 | |
| 19 | namespace Ice { |
| 20 | |
| 21 | // Similar to bit_cast, but allows copying from types of unrelated |
| 22 | // sizes. This method was introduced to enable the strict aliasing |
| 23 | // optimizations of GCC 4.4. Basically, GCC mindlessly relies on |
| 24 | // obscure details in the C++ standard that make reinterpret_cast |
| 25 | // virtually useless. |
| 26 | template <class D, class S> inline D bit_copy(const S &source) { |
| 27 | D destination; |
| 28 | // This use of memcpy is safe: source and destination cannot overlap. |
| 29 | memcpy(&destination, reinterpret_cast<const void *>(&source), |
| 30 | sizeof(destination)); |
| 31 | return destination; |
| 32 | } |
| 33 | |
| 34 | class Utils { |
| 35 | public: |
| 36 | // Check whether an N-bit two's-complement representation can hold value. |
| 37 | template <typename T> static inline bool IsInt(int N, T value) { |
| 38 | assert((0 < N) && |
| 39 | (static_cast<unsigned int>(N) < (CHAR_BIT * sizeof(value)))); |
| 40 | T limit = static_cast<T>(1) << (N - 1); |
| 41 | return (-limit <= value) && (value < limit); |
| 42 | } |
| 43 | |
| 44 | template <typename T> static inline bool IsUint(int N, T value) { |
| 45 | assert((0 < N) && |
| 46 | (static_cast<unsigned int>(N) < (CHAR_BIT * sizeof(value)))); |
| 47 | T limit = static_cast<T>(1) << N; |
| 48 | return (0 <= value) && (value < limit); |
| 49 | } |
| 50 | |
| 51 | template <typename T> static inline bool WouldOverflowAdd(T X, T Y) { |
| 52 | return ((X > 0 && Y > 0 && (X > std::numeric_limits<T>::max() - Y)) || |
| 53 | (X < 0 && Y < 0 && (X < std::numeric_limits<T>::min() - Y))); |
| 54 | } |
| 55 | }; |
| 56 | |
| 57 | } // end of namespace Ice |
| 58 | |
| 59 | #endif // SUBZERO_SRC_ICEUTILS_H |