1/****************************************************************************
2**
3** Copyright (C) 2019 The Qt Company Ltd.
4** Copyright (C) 2018 Intel Corporation.
5** Contact: https://www.qt.io/licensing/
6**
7** This file is part of the QtCore module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial License Usage
11** Licensees holding valid commercial Qt licenses may use this file in
12** accordance with the commercial license agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and The Qt Company. For licensing terms
15** and conditions see https://www.qt.io/terms-conditions. For further
16** information use the contact form at https://www.qt.io/contact-us.
17**
18** GNU Lesser General Public License Usage
19** Alternatively, this file may be used under the terms of the GNU Lesser
20** General Public License version 3 as published by the Free Software
21** Foundation and appearing in the file LICENSE.LGPL3 included in the
22** packaging of this file. Please review the following information to
23** ensure the GNU Lesser General Public License version 3 requirements
24** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
25**
26** GNU General Public License Usage
27** Alternatively, this file may be used under the terms of the GNU
28** General Public License version 2.0 or (at your option) the GNU General
29** Public license version 3 or any later version approved by the KDE Free
30** Qt Foundation. The licenses are as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
32** included in the packaging of this file. Please review the following
33** information to ensure the GNU General Public License requirements will
34** be met: https://www.gnu.org/licenses/gpl-2.0.html and
35** https://www.gnu.org/licenses/gpl-3.0.html.
36**
37** $QT_END_LICENSE$
38**
39****************************************************************************/
40
41#ifndef QNUMERIC_P_H
42#define QNUMERIC_P_H
43
44//
45// W A R N I N G
46// -------------
47//
48// This file is not part of the Qt API. It exists purely as an
49// implementation detail. This header file may change from version to
50// version without notice, or even be removed.
51//
52// We mean it.
53//
54
55#include "QtCore/private/qglobal_p.h"
56#include <cmath>
57#include <limits>
58
59#if defined(Q_CC_MSVC)
60# include <intrin.h>
61# include <float.h>
62# if defined(Q_PROCESSOR_X86_64) || defined(Q_PROCESSOR_ARM_64)
63# define Q_INTRINSIC_MUL_OVERFLOW64
64# define Q_UMULH(v1, v2) __umulh(v1, v2);
65# define Q_SMULH(v1, v2) __mulh(v1, v2);
66# pragma intrinsic(__umulh)
67# pragma intrinsic(__mulh)
68# endif
69#endif
70
71# if defined(Q_OS_INTEGRITY) && defined(Q_PROCESSOR_ARM_64)
72#include <arm64_ghs.h>
73# define Q_INTRINSIC_MUL_OVERFLOW64
74# define Q_UMULH(v1, v2) __MULUH64(v1, v2);
75# define Q_SMULH(v1, v2) __MULSH64(v1, v2);
76#endif
77
78#if !defined(Q_CC_MSVC) && (defined(Q_OS_QNX) || defined(Q_CC_INTEL))
79# include <math.h>
80# ifdef isnan
81# define QT_MATH_H_DEFINES_MACROS
82QT_BEGIN_NAMESPACE
83namespace qnumeric_std_wrapper {
84// the 'using namespace std' below is cases where the stdlib already put the math.h functions in the std namespace and undefined the macros.
85Q_DECL_CONST_FUNCTION static inline bool math_h_isnan(double d) { using namespace std; return isnan(d); }
86Q_DECL_CONST_FUNCTION static inline bool math_h_isinf(double d) { using namespace std; return isinf(d); }
87Q_DECL_CONST_FUNCTION static inline bool math_h_isfinite(double d) { using namespace std; return isfinite(d); }
88Q_DECL_CONST_FUNCTION static inline int math_h_fpclassify(double d) { using namespace std; return fpclassify(d); }
89Q_DECL_CONST_FUNCTION static inline bool math_h_isnan(float f) { using namespace std; return isnan(f); }
90Q_DECL_CONST_FUNCTION static inline bool math_h_isinf(float f) { using namespace std; return isinf(f); }
91Q_DECL_CONST_FUNCTION static inline bool math_h_isfinite(float f) { using namespace std; return isfinite(f); }
92Q_DECL_CONST_FUNCTION static inline int math_h_fpclassify(float f) { using namespace std; return fpclassify(f); }
93}
94QT_END_NAMESPACE
95// These macros from math.h conflict with the real functions in the std namespace.
96# undef signbit
97# undef isnan
98# undef isinf
99# undef isfinite
100# undef fpclassify
101# endif // defined(isnan)
102#endif
103
104QT_BEGIN_NAMESPACE
105
106namespace qnumeric_std_wrapper {
107#if defined(QT_MATH_H_DEFINES_MACROS)
108# undef QT_MATH_H_DEFINES_MACROS
109Q_DECL_CONST_FUNCTION static inline bool isnan(double d) { return math_h_isnan(d); }
110Q_DECL_CONST_FUNCTION static inline bool isinf(double d) { return math_h_isinf(d); }
111Q_DECL_CONST_FUNCTION static inline bool isfinite(double d) { return math_h_isfinite(d); }
112Q_DECL_CONST_FUNCTION static inline int fpclassify(double d) { return math_h_fpclassify(d); }
113Q_DECL_CONST_FUNCTION static inline bool isnan(float f) { return math_h_isnan(f); }
114Q_DECL_CONST_FUNCTION static inline bool isinf(float f) { return math_h_isinf(f); }
115Q_DECL_CONST_FUNCTION static inline bool isfinite(float f) { return math_h_isfinite(f); }
116Q_DECL_CONST_FUNCTION static inline int fpclassify(float f) { return math_h_fpclassify(f); }
117#else
118Q_DECL_CONST_FUNCTION static inline bool isnan(double d) { return std::isnan(d); }
119Q_DECL_CONST_FUNCTION static inline bool isinf(double d) { return std::isinf(d); }
120Q_DECL_CONST_FUNCTION static inline bool isfinite(double d) { return std::isfinite(d); }
121Q_DECL_CONST_FUNCTION static inline int fpclassify(double d) { return std::fpclassify(d); }
122Q_DECL_CONST_FUNCTION static inline bool isnan(float f) { return std::isnan(f); }
123Q_DECL_CONST_FUNCTION static inline bool isinf(float f) { return std::isinf(f); }
124Q_DECL_CONST_FUNCTION static inline bool isfinite(float f) { return std::isfinite(f); }
125Q_DECL_CONST_FUNCTION static inline int fpclassify(float f) { return std::fpclassify(f); }
126#endif
127}
128
129Q_DECL_CONSTEXPR Q_DECL_CONST_FUNCTION static inline double qt_inf() noexcept
130{
131 Q_STATIC_ASSERT_X(std::numeric_limits<double>::has_infinity,
132 "platform has no definition for infinity for type double");
133 return std::numeric_limits<double>::infinity();
134}
135
136// Signaling NaN
137Q_DECL_CONSTEXPR Q_DECL_CONST_FUNCTION static inline double qt_snan() noexcept
138{
139 Q_STATIC_ASSERT_X(std::numeric_limits<double>::has_signaling_NaN,
140 "platform has no definition for signaling NaN for type double");
141 return std::numeric_limits<double>::signaling_NaN();
142}
143
144// Quiet NaN
145Q_DECL_CONSTEXPR Q_DECL_CONST_FUNCTION static inline double qt_qnan() noexcept
146{
147 Q_STATIC_ASSERT_X(std::numeric_limits<double>::has_quiet_NaN,
148 "platform has no definition for quiet NaN for type double");
149 return std::numeric_limits<double>::quiet_NaN();
150}
151
152Q_DECL_CONST_FUNCTION static inline bool qt_is_inf(double d)
153{
154 return qnumeric_std_wrapper::isinf(d);
155}
156
157Q_DECL_CONST_FUNCTION static inline bool qt_is_nan(double d)
158{
159 return qnumeric_std_wrapper::isnan(d);
160}
161
162Q_DECL_CONST_FUNCTION static inline bool qt_is_finite(double d)
163{
164 return qnumeric_std_wrapper::isfinite(d);
165}
166
167Q_DECL_CONST_FUNCTION static inline int qt_fpclassify(double d)
168{
169 return qnumeric_std_wrapper::fpclassify(d);
170}
171
172Q_DECL_CONST_FUNCTION static inline bool qt_is_inf(float f)
173{
174 return qnumeric_std_wrapper::isinf(f);
175}
176
177Q_DECL_CONST_FUNCTION static inline bool qt_is_nan(float f)
178{
179 return qnumeric_std_wrapper::isnan(f);
180}
181
182Q_DECL_CONST_FUNCTION static inline bool qt_is_finite(float f)
183{
184 return qnumeric_std_wrapper::isfinite(f);
185}
186
187Q_DECL_CONST_FUNCTION static inline int qt_fpclassify(float f)
188{
189 return qnumeric_std_wrapper::fpclassify(f);
190}
191
192#ifndef Q_CLANG_QDOC
193namespace {
194/*!
195 Returns true if the double \a v can be converted to type \c T, false if
196 it's out of range. If the conversion is successful, the converted value is
197 stored in \a value; if it was not successful, \a value will contain the
198 minimum or maximum of T, depending on the sign of \a d. If \c T is
199 unsigned, then \a value contains the absolute value of \a v.
200
201 This function works for v containing infinities, but not NaN. It's the
202 caller's responsibility to exclude that possibility before calling it.
203*/
204template <typename T> static inline bool convertDoubleTo(double v, T *value)
205{
206 Q_STATIC_ASSERT(std::numeric_limits<T>::is_integer);
207
208 // The [conv.fpint] (7.10 Floating-integral conversions) section of the C++
209 // standard says only exact conversions are guaranteed. Converting
210 // integrals to floating-point with loss of precision has implementation-
211 // defined behavior whether the next higher or next lower is returned;
212 // converting FP to integral is UB if it can't be represented.
213 //
214 // That means we can't write UINT64_MAX+1. Writing ldexp(1, 64) would be
215 // correct, but Clang, ICC and MSVC don't realize that it's a constant and
216 // the math call stays in the compiled code.
217
218 double supremum;
219 if (std::numeric_limits<T>::is_signed) {
220 supremum = -1.0 * std::numeric_limits<T>::min(); // -1 * (-2^63) = 2^63, exact (for T = qint64)
221 *value = std::numeric_limits<T>::min();
222 if (v < std::numeric_limits<T>::min())
223 return false;
224 } else {
225 using ST = typename std::make_signed<T>::type;
226 supremum = -2.0 * std::numeric_limits<ST>::min(); // -2 * (-2^63) = 2^64, exact (for T = quint64)
227 v = fabs(v);
228 }
229
230 *value = std::numeric_limits<T>::max();
231 if (v >= supremum)
232 return false;
233
234 // Now we can convert, these two conversions cannot be UB
235 *value = T(v);
236
237QT_WARNING_PUSH
238QT_WARNING_DISABLE_GCC("-Wfloat-equal")
239QT_WARNING_DISABLE_CLANG("-Wfloat-equal")
240
241 return *value == v;
242
243QT_WARNING_POP
244}
245
246// Overflow math.
247// This provides efficient implementations for int, unsigned, qsizetype and
248// size_t. Implementations for 8- and 16-bit types will work but may not be as
249// efficient. Implementations for 64-bit may be missing on 32-bit platforms.
250
251#if (defined(Q_CC_GNU) && (Q_CC_GNU >= 500) || (defined(Q_CC_INTEL) && !defined(Q_OS_WIN))) || QT_HAS_BUILTIN(__builtin_add_overflow)
252// GCC 5, ICC 18, and Clang 3.8 have builtins to detect overflows
253
254template <typename T> inline
255typename std::enable_if<std::is_unsigned<T>::value || std::is_signed<T>::value, bool>::type
256add_overflow(T v1, T v2, T *r)
257{ return __builtin_add_overflow(v1, v2, r); }
258
259template <typename T> inline
260typename std::enable_if<std::is_unsigned<T>::value || std::is_signed<T>::value, bool>::type
261sub_overflow(T v1, T v2, T *r)
262{ return __builtin_sub_overflow(v1, v2, r); }
263
264template <typename T> inline
265typename std::enable_if<std::is_unsigned<T>::value || std::is_signed<T>::value, bool>::type
266mul_overflow(T v1, T v2, T *r)
267{ return __builtin_mul_overflow(v1, v2, r); }
268
269#else
270// Generic implementations
271
272template <typename T> inline typename std::enable_if<std::is_unsigned<T>::value, bool>::type
273add_overflow(T v1, T v2, T *r)
274{
275 // unsigned additions are well-defined
276 *r = v1 + v2;
277 return v1 > T(v1 + v2);
278}
279
280template <typename T> inline typename std::enable_if<std::is_signed<T>::value, bool>::type
281add_overflow(T v1, T v2, T *r)
282{
283 // Here's how we calculate the overflow:
284 // 1) unsigned addition is well-defined, so we can always execute it
285 // 2) conversion from unsigned back to signed is implementation-
286 // defined and in the implementations we use, it's a no-op.
287 // 3) signed integer overflow happens if the sign of the two input operands
288 // is the same but the sign of the result is different. In other words,
289 // the sign of the result must be the same as the sign of either
290 // operand.
291
292 using U = typename std::make_unsigned<T>::type;
293 *r = T(U(v1) + U(v2));
294
295 // If int is two's complement, assume all integer types are too.
296 if (std::is_same<int32_t, int>::value) {
297 // Two's complement equivalent (generates slightly shorter code):
298 // x ^ y is negative if x and y have different signs
299 // x & y is negative if x and y are negative
300 // (x ^ z) & (y ^ z) is negative if x and z have different signs
301 // AND y and z have different signs
302 return ((v1 ^ *r) & (v2 ^ *r)) < 0;
303 }
304
305 bool s1 = (v1 < 0);
306 bool s2 = (v2 < 0);
307 bool sr = (*r < 0);
308 return s1 != sr && s2 != sr;
309 // also: return s1 == s2 && s1 != sr;
310}
311
312template <typename T> inline typename std::enable_if<std::is_unsigned<T>::value, bool>::type
313sub_overflow(T v1, T v2, T *r)
314{
315 // unsigned subtractions are well-defined
316 *r = v1 - v2;
317 return v1 < v2;
318}
319
320template <typename T> inline typename std::enable_if<std::is_signed<T>::value, bool>::type
321sub_overflow(T v1, T v2, T *r)
322{
323 // See above for explanation. This is the same with some signs reversed.
324 // We can't use add_overflow(v1, -v2, r) because it would be UB if
325 // v2 == std::numeric_limits<T>::min().
326
327 using U = typename std::make_unsigned<T>::type;
328 *r = T(U(v1) - U(v2));
329
330 if (std::is_same<int32_t, int>::value)
331 return ((v1 ^ *r) & (~v2 ^ *r)) < 0;
332
333 bool s1 = (v1 < 0);
334 bool s2 = !(v2 < 0);
335 bool sr = (*r < 0);
336 return s1 != sr && s2 != sr;
337 // also: return s1 == s2 && s1 != sr;
338}
339
340template <typename T> inline
341typename std::enable_if<std::is_unsigned<T>::value || std::is_signed<T>::value, bool>::type
342mul_overflow(T v1, T v2, T *r)
343{
344 // use the next biggest type
345 // Note: for 64-bit systems where __int128 isn't supported, this will cause an error.
346 using LargerInt = QIntegerForSize<sizeof(T) * 2>;
347 using Larger = typename std::conditional<std::is_signed<T>::value,
348 typename LargerInt::Signed, typename LargerInt::Unsigned>::type;
349 Larger lr = Larger(v1) * Larger(v2);
350 *r = T(lr);
351 return lr > std::numeric_limits<T>::max() || lr < std::numeric_limits<T>::min();
352}
353
354# if defined(Q_INTRINSIC_MUL_OVERFLOW64)
355template <> inline bool mul_overflow(quint64 v1, quint64 v2, quint64 *r)
356{
357 *r = v1 * v2;
358 return Q_UMULH(v1, v2);
359}
360template <> inline bool mul_overflow(qint64 v1, qint64 v2, qint64 *r)
361{
362 // This is slightly more complex than the unsigned case above: the sign bit
363 // of 'low' must be replicated as the entire 'high', so the only valid
364 // values for 'high' are 0 and -1. Use unsigned multiply since it's the same
365 // as signed for the low bits and use a signed right shift to verify that
366 // 'high' is nothing but sign bits that match the sign of 'low'.
367
368 qint64 high = Q_SMULH(v1, v2);
369 *r = qint64(quint64(v1) * quint64(v2));
370 return (*r >> 63) != high;
371}
372
373# if defined(Q_OS_INTEGRITY) && defined(Q_PROCESSOR_ARM_64)
374template <> inline bool mul_overflow(uint64_t v1, uint64_t v2, uint64_t *r)
375{
376 return mul_overflow<quint64>(v1,v2,reinterpret_cast<quint64*>(r));
377}
378
379template <> inline bool mul_overflow(int64_t v1, int64_t v2, int64_t *r)
380{
381 return mul_overflow<qint64>(v1,v2,reinterpret_cast<qint64*>(r));
382}
383# endif // OS_INTEGRITY ARM64
384# endif // Q_INTRINSIC_MUL_OVERFLOW64
385
386# if defined(Q_CC_MSVC) && defined(Q_PROCESSOR_X86)
387// We can use intrinsics for the unsigned operations with MSVC
388template <> inline bool add_overflow(unsigned v1, unsigned v2, unsigned *r)
389{ return _addcarry_u32(0, v1, v2, r); }
390
391// 32-bit mul_overflow is fine with the generic code above
392
393template <> inline bool add_overflow(quint64 v1, quint64 v2, quint64 *r)
394{
395# if defined(Q_PROCESSOR_X86_64)
396 return _addcarry_u64(0, v1, v2, reinterpret_cast<unsigned __int64 *>(r));
397# else
398 uint low, high;
399 uchar carry = _addcarry_u32(0, unsigned(v1), unsigned(v2), &low);
400 carry = _addcarry_u32(carry, v1 >> 32, v2 >> 32, &high);
401 *r = (quint64(high) << 32) | low;
402 return carry;
403# endif // !x86-64
404}
405# endif // MSVC X86
406#endif // !GCC
407}
408#endif // Q_CLANG_QDOC
409
410QT_END_NAMESPACE
411
412#endif // QNUMERIC_P_H
413