New upstream version 1.8
[debian/gzip] / lib / intprops.h
1 /* intprops.h -- properties of integer types
2
3    Copyright (C) 2001-2016 Free Software Foundation, Inc.
4
5    This program is free software: you can redistribute it and/or modify it
6    under the terms of the GNU General Public License as published
7    by the Free Software Foundation; either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17
18 /* Written by Paul Eggert.  */
19
20 #ifndef _GL_INTPROPS_H
21 #define _GL_INTPROPS_H
22
23 #include <limits.h>
24 #include <verify.h>
25
26 /* Return a value with the common real type of E and V and the value of V.  */
27 #define _GL_INT_CONVERT(e, v) (0 * (e) + (v))
28
29 /* Act like _GL_INT_CONVERT (E, -V) but work around a bug in IRIX 6.5 cc; see
30    <http://lists.gnu.org/archive/html/bug-gnulib/2011-05/msg00406.html>.  */
31 #define _GL_INT_NEGATE_CONVERT(e, v) (0 * (e) - (v))
32
33 /* The extra casts in the following macros work around compiler bugs,
34    e.g., in Cray C 5.0.3.0.  */
35
36 /* True if the arithmetic type T is an integer type.  bool counts as
37    an integer.  */
38 #define TYPE_IS_INTEGER(t) ((t) 1.5 == 1)
39
40 /* True if the real type T is signed.  */
41 #define TYPE_SIGNED(t) (! ((t) 0 < (t) -1))
42
43 /* Return 1 if the real expression E, after promotion, has a
44    signed or floating type.  */
45 #define EXPR_SIGNED(e) (_GL_INT_NEGATE_CONVERT (e, 1) < 0)
46
47
48 /* Minimum and maximum values for integer types and expressions.  */
49
50 /* The maximum and minimum values for the integer type T.  */
51 #define TYPE_MINIMUM(t) ((t) ~ TYPE_MAXIMUM (t))
52 #define TYPE_MAXIMUM(t)                                                 \
53   ((t) (! TYPE_SIGNED (t)                                               \
54         ? (t) -1                                                        \
55         : ((((t) 1 << (sizeof (t) * CHAR_BIT - 2)) - 1) * 2 + 1)))
56
57 /* The maximum and minimum values for the type of the expression E,
58    after integer promotion.  E should not have side effects.  */
59 #define _GL_INT_MINIMUM(e)                                              \
60   (EXPR_SIGNED (e)                                                      \
61    ? ~ _GL_SIGNED_INT_MAXIMUM (e)                                       \
62    : _GL_INT_CONVERT (e, 0))
63 #define _GL_INT_MAXIMUM(e)                                              \
64   (EXPR_SIGNED (e)                                                      \
65    ? _GL_SIGNED_INT_MAXIMUM (e)                                         \
66    : _GL_INT_NEGATE_CONVERT (e, 1))
67 #define _GL_SIGNED_INT_MAXIMUM(e)                                       \
68   (((_GL_INT_CONVERT (e, 1) << (sizeof ((e) + 0) * CHAR_BIT - 2)) - 1) * 2 + 1)
69
70 /* This include file assumes that signed types are two's complement without
71    padding bits; the above macros have undefined behavior otherwise.
72    If this is a problem for you, please let us know how to fix it for your host.
73    As a sanity check, test the assumption for some signed types that
74    <limits.h> bounds.  */
75 verify (TYPE_MINIMUM (signed char) == SCHAR_MIN);
76 verify (TYPE_MAXIMUM (signed char) == SCHAR_MAX);
77 verify (TYPE_MINIMUM (short int) == SHRT_MIN);
78 verify (TYPE_MAXIMUM (short int) == SHRT_MAX);
79 verify (TYPE_MINIMUM (int) == INT_MIN);
80 verify (TYPE_MAXIMUM (int) == INT_MAX);
81 verify (TYPE_MINIMUM (long int) == LONG_MIN);
82 verify (TYPE_MAXIMUM (long int) == LONG_MAX);
83 #ifdef LLONG_MAX
84 verify (TYPE_MINIMUM (long long int) == LLONG_MIN);
85 verify (TYPE_MAXIMUM (long long int) == LLONG_MAX);
86 #endif
87
88 /* Does the __typeof__ keyword work?  This could be done by
89    'configure', but for now it's easier to do it by hand.  */
90 #if (2 <= __GNUC__ || defined __IBM__TYPEOF__ \
91      || (0x5110 <= __SUNPRO_C && !__STDC__))
92 # define _GL_HAVE___TYPEOF__ 1
93 #else
94 # define _GL_HAVE___TYPEOF__ 0
95 #endif
96
97 /* Return 1 if the integer type or expression T might be signed.  Return 0
98    if it is definitely unsigned.  This macro does not evaluate its argument,
99    and expands to an integer constant expression.  */
100 #if _GL_HAVE___TYPEOF__
101 # define _GL_SIGNED_TYPE_OR_EXPR(t) TYPE_SIGNED (__typeof__ (t))
102 #else
103 # define _GL_SIGNED_TYPE_OR_EXPR(t) 1
104 #endif
105
106 /* Bound on length of the string representing an unsigned integer
107    value representable in B bits.  log10 (2.0) < 146/485.  The
108    smallest value of B where this bound is not tight is 2621.  */
109 #define INT_BITS_STRLEN_BOUND(b) (((b) * 146 + 484) / 485)
110
111 /* Bound on length of the string representing an integer type or expression T.
112    Subtract 1 for the sign bit if T is signed, and then add 1 more for
113    a minus sign if needed.
114
115    Because _GL_SIGNED_TYPE_OR_EXPR sometimes returns 0 when its argument is
116    signed, this macro may overestimate the true bound by one byte when
117    applied to unsigned types of size 2, 4, 16, ... bytes.  */
118 #define INT_STRLEN_BOUND(t)                                     \
119   (INT_BITS_STRLEN_BOUND (sizeof (t) * CHAR_BIT                 \
120                           - _GL_SIGNED_TYPE_OR_EXPR (t))        \
121    + _GL_SIGNED_TYPE_OR_EXPR (t))
122
123 /* Bound on buffer size needed to represent an integer type or expression T,
124    including the terminating null.  */
125 #define INT_BUFSIZE_BOUND(t) (INT_STRLEN_BOUND (t) + 1)
126
127
128 /* Range overflow checks.
129
130    The INT_<op>_RANGE_OVERFLOW macros return 1 if the corresponding C
131    operators might not yield numerically correct answers due to
132    arithmetic overflow.  They do not rely on undefined or
133    implementation-defined behavior.  Their implementations are simple
134    and straightforward, but they are a bit harder to use than the
135    INT_<op>_OVERFLOW macros described below.
136
137    Example usage:
138
139      long int i = ...;
140      long int j = ...;
141      if (INT_MULTIPLY_RANGE_OVERFLOW (i, j, LONG_MIN, LONG_MAX))
142        printf ("multiply would overflow");
143      else
144        printf ("product is %ld", i * j);
145
146    Restrictions on *_RANGE_OVERFLOW macros:
147
148    These macros do not check for all possible numerical problems or
149    undefined or unspecified behavior: they do not check for division
150    by zero, for bad shift counts, or for shifting negative numbers.
151
152    These macros may evaluate their arguments zero or multiple times,
153    so the arguments should not have side effects.  The arithmetic
154    arguments (including the MIN and MAX arguments) must be of the same
155    integer type after the usual arithmetic conversions, and the type
156    must have minimum value MIN and maximum MAX.  Unsigned types should
157    use a zero MIN of the proper type.
158
159    These macros are tuned for constant MIN and MAX.  For commutative
160    operations such as A + B, they are also tuned for constant B.  */
161
162 /* Return 1 if A + B would overflow in [MIN,MAX] arithmetic.
163    See above for restrictions.  */
164 #define INT_ADD_RANGE_OVERFLOW(a, b, min, max)          \
165   ((b) < 0                                              \
166    ? (a) < (min) - (b)                                  \
167    : (max) - (b) < (a))
168
169 /* Return 1 if A - B would overflow in [MIN,MAX] arithmetic.
170    See above for restrictions.  */
171 #define INT_SUBTRACT_RANGE_OVERFLOW(a, b, min, max)     \
172   ((b) < 0                                              \
173    ? (max) + (b) < (a)                                  \
174    : (a) < (min) + (b))
175
176 /* Return 1 if - A would overflow in [MIN,MAX] arithmetic.
177    See above for restrictions.  */
178 #define INT_NEGATE_RANGE_OVERFLOW(a, min, max)          \
179   ((min) < 0                                            \
180    ? (a) < - (max)                                      \
181    : 0 < (a))
182
183 /* Return 1 if A * B would overflow in [MIN,MAX] arithmetic.
184    See above for restrictions.  Avoid && and || as they tickle
185    bugs in Sun C 5.11 2010/08/13 and other compilers; see
186    <http://lists.gnu.org/archive/html/bug-gnulib/2011-05/msg00401.html>.  */
187 #define INT_MULTIPLY_RANGE_OVERFLOW(a, b, min, max)     \
188   ((b) < 0                                              \
189    ? ((a) < 0                                           \
190       ? (a) < (max) / (b)                               \
191       : (b) == -1                                       \
192       ? 0                                               \
193       : (min) / (b) < (a))                              \
194    : (b) == 0                                           \
195    ? 0                                                  \
196    : ((a) < 0                                           \
197       ? (a) < (min) / (b)                               \
198       : (max) / (b) < (a)))
199
200 /* Return 1 if A / B would overflow in [MIN,MAX] arithmetic.
201    See above for restrictions.  Do not check for division by zero.  */
202 #define INT_DIVIDE_RANGE_OVERFLOW(a, b, min, max)       \
203   ((min) < 0 && (b) == -1 && (a) < - (max))
204
205 /* Return 1 if A % B would overflow in [MIN,MAX] arithmetic.
206    See above for restrictions.  Do not check for division by zero.
207    Mathematically, % should never overflow, but on x86-like hosts
208    INT_MIN % -1 traps, and the C standard permits this, so treat this
209    as an overflow too.  */
210 #define INT_REMAINDER_RANGE_OVERFLOW(a, b, min, max)    \
211   INT_DIVIDE_RANGE_OVERFLOW (a, b, min, max)
212
213 /* Return 1 if A << B would overflow in [MIN,MAX] arithmetic.
214    See above for restrictions.  Here, MIN and MAX are for A only, and B need
215    not be of the same type as the other arguments.  The C standard says that
216    behavior is undefined for shifts unless 0 <= B < wordwidth, and that when
217    A is negative then A << B has undefined behavior and A >> B has
218    implementation-defined behavior, but do not check these other
219    restrictions.  */
220 #define INT_LEFT_SHIFT_RANGE_OVERFLOW(a, b, min, max)   \
221   ((a) < 0                                              \
222    ? (a) < (min) >> (b)                                 \
223    : (max) >> (b) < (a))
224
225
226 /* The _GL*_OVERFLOW macros have the same restrictions as the
227    *_RANGE_OVERFLOW macros, except that they do not assume that operands
228    (e.g., A and B) have the same type as MIN and MAX.  Instead, they assume
229    that the result (e.g., A + B) has that type.  */
230 #define _GL_ADD_OVERFLOW(a, b, min, max)                                \
231   ((min) < 0 ? INT_ADD_RANGE_OVERFLOW (a, b, min, max)                  \
232    : (a) < 0 ? (b) <= (a) + (b)                                         \
233    : (b) < 0 ? (a) <= (a) + (b)                                         \
234    : (a) + (b) < (b))
235 #define _GL_SUBTRACT_OVERFLOW(a, b, min, max)                           \
236   ((min) < 0 ? INT_SUBTRACT_RANGE_OVERFLOW (a, b, min, max)             \
237    : (a) < 0 ? 1                                                        \
238    : (b) < 0 ? (a) - (b) <= (a)                                         \
239    : (a) < (b))
240 #define _GL_MULTIPLY_OVERFLOW(a, b, min, max)                           \
241   (((min) == 0 && (((a) < 0 && 0 < (b)) || ((b) < 0 && 0 < (a))))       \
242    || INT_MULTIPLY_RANGE_OVERFLOW (a, b, min, max))
243 #define _GL_DIVIDE_OVERFLOW(a, b, min, max)                             \
244   ((min) < 0 ? (b) == _GL_INT_NEGATE_CONVERT (min, 1) && (a) < - (max)  \
245    : (a) < 0 ? (b) <= (a) + (b) - 1                                     \
246    : (b) < 0 && (a) + (b) <= (a))
247 #define _GL_REMAINDER_OVERFLOW(a, b, min, max)                          \
248   ((min) < 0 ? (b) == _GL_INT_NEGATE_CONVERT (min, 1) && (a) < - (max)  \
249    : (a) < 0 ? (a) % (b) != ((max) - (b) + 1) % (b)                     \
250    : (b) < 0 && ! _GL_UNSIGNED_NEG_MULTIPLE (a, b, max))
251
252 /* Return a nonzero value if A is a mathematical multiple of B, where
253    A is unsigned, B is negative, and MAX is the maximum value of A's
254    type.  A's type must be the same as (A % B)'s type.  Normally (A %
255    -B == 0) suffices, but things get tricky if -B would overflow.  */
256 #define _GL_UNSIGNED_NEG_MULTIPLE(a, b, max)                            \
257   (((b) < -_GL_SIGNED_INT_MAXIMUM (b)                                   \
258     ? (_GL_SIGNED_INT_MAXIMUM (b) == (max)                              \
259        ? (a)                                                            \
260        : (a) % (_GL_INT_CONVERT (a, _GL_SIGNED_INT_MAXIMUM (b)) + 1))   \
261     : (a) % - (b))                                                      \
262    == 0)
263
264 /* Check for integer overflow, and report low order bits of answer.
265
266    The INT_<op>_OVERFLOW macros return 1 if the corresponding C operators
267    might not yield numerically correct answers due to arithmetic overflow.
268    The INT_<op>_WRAPV macros also store the low-order bits of the answer.
269    These macros work correctly on all known practical hosts, and do not rely
270    on undefined behavior due to signed arithmetic overflow.
271
272    Example usage, assuming A and B are long int:
273
274      if (INT_MULTIPLY_OVERFLOW (a, b))
275        printf ("result would overflow\n");
276      else
277        printf ("result is %ld (no overflow)\n", a * b);
278
279    Example usage with WRAPV flavor:
280
281      long int result;
282      bool overflow = INT_MULTIPLY_WRAPV (a, b, &result);
283      printf ("result is %ld (%s)\n", result,
284              overflow ? "after overflow" : "no overflow");
285
286    Restrictions on these macros:
287
288    These macros do not check for all possible numerical problems or
289    undefined or unspecified behavior: they do not check for division
290    by zero, for bad shift counts, or for shifting negative numbers.
291
292    These macros may evaluate their arguments zero or multiple times, so the
293    arguments should not have side effects.
294
295    The WRAPV macros are not constant expressions.  They support only
296    +, binary -, and *.  The result type must be signed.
297
298    These macros are tuned for their last argument being a constant.
299
300    Return 1 if the integer expressions A * B, A - B, -A, A * B, A / B,
301    A % B, and A << B would overflow, respectively.  */
302
303 #define INT_ADD_OVERFLOW(a, b) \
304   _GL_BINARY_OP_OVERFLOW (a, b, _GL_ADD_OVERFLOW)
305 #define INT_SUBTRACT_OVERFLOW(a, b) \
306   _GL_BINARY_OP_OVERFLOW (a, b, _GL_SUBTRACT_OVERFLOW)
307 #define INT_NEGATE_OVERFLOW(a) \
308   INT_NEGATE_RANGE_OVERFLOW (a, _GL_INT_MINIMUM (a), _GL_INT_MAXIMUM (a))
309 #define INT_MULTIPLY_OVERFLOW(a, b) \
310   _GL_BINARY_OP_OVERFLOW (a, b, _GL_MULTIPLY_OVERFLOW)
311 #define INT_DIVIDE_OVERFLOW(a, b) \
312   _GL_BINARY_OP_OVERFLOW (a, b, _GL_DIVIDE_OVERFLOW)
313 #define INT_REMAINDER_OVERFLOW(a, b) \
314   _GL_BINARY_OP_OVERFLOW (a, b, _GL_REMAINDER_OVERFLOW)
315 #define INT_LEFT_SHIFT_OVERFLOW(a, b) \
316   INT_LEFT_SHIFT_RANGE_OVERFLOW (a, b, \
317                                  _GL_INT_MINIMUM (a), _GL_INT_MAXIMUM (a))
318
319 /* Return 1 if the expression A <op> B would overflow,
320    where OP_RESULT_OVERFLOW (A, B, MIN, MAX) does the actual test,
321    assuming MIN and MAX are the minimum and maximum for the result type.
322    Arguments should be free of side effects.  */
323 #define _GL_BINARY_OP_OVERFLOW(a, b, op_result_overflow)        \
324   op_result_overflow (a, b,                                     \
325                       _GL_INT_MINIMUM (0 * (b) + (a)),          \
326                       _GL_INT_MAXIMUM (0 * (b) + (a)))
327
328 /* Compute A + B, A - B, A * B, respectively, storing the result into *R.
329    Return 1 if the result overflows.  See above for restrictions.  */
330 #define INT_ADD_WRAPV(a, b, r) \
331   _GL_INT_OP_WRAPV (a, b, r, +, __builtin_add_overflow, INT_ADD_OVERFLOW)
332 #define INT_SUBTRACT_WRAPV(a, b, r) \
333   _GL_INT_OP_WRAPV (a, b, r, -, __builtin_sub_overflow, INT_SUBTRACT_OVERFLOW)
334 #define INT_MULTIPLY_WRAPV(a, b, r) \
335   _GL_INT_OP_WRAPV (a, b, r, *, __builtin_mul_overflow, INT_MULTIPLY_OVERFLOW)
336
337 #ifndef __has_builtin
338 # define __has_builtin(x) 0
339 #endif
340
341 /* Nonzero if this compiler has GCC bug 68193 or Clang bug 25390.  See:
342    https://gcc.gnu.org/bugzilla/show_bug.cgi?id=68193
343    https://llvm.org/bugs/show_bug.cgi?id=25390
344    For now, assume all versions of GCC-like compilers generate bogus
345    warnings for _Generic.  This matters only for older compilers that
346    lack __builtin_add_overflow.  */
347 #if __GNUC__
348 # define _GL__GENERIC_BOGUS 1
349 #else
350 # define _GL__GENERIC_BOGUS 0
351 #endif
352
353 /* Store A <op> B into *R, where OP specifies the operation.
354    BUILTIN is the builtin operation, and OVERFLOW the overflow predicate.
355    See above for restrictions.  */
356 #if 5 <= __GNUC__ || __has_builtin (__builtin_add_overflow)
357 # define _GL_INT_OP_WRAPV(a, b, r, op, builtin, overflow) builtin (a, b, r)
358 #elif 201112 <= __STDC_VERSION__ && !_GL__GENERIC_BOGUS
359 # define _GL_INT_OP_WRAPV(a, b, r, op, builtin, overflow) \
360    (_Generic \
361     (*(r), \
362      signed char: \
363        _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned char, \
364                         signed char, SCHAR_MIN, SCHAR_MAX), \
365      short int: \
366        _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned short int, \
367                         short int, SHRT_MIN, SHRT_MAX), \
368      int: \
369        _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, \
370                         int, INT_MIN, INT_MAX), \
371      long int: \
372        _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long int, \
373                         long int, LONG_MIN, LONG_MAX), \
374      long long int: \
375        _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long long int, \
376                         long long int, LLONG_MIN, LLONG_MAX)))
377 #else
378 # define _GL_INT_OP_WRAPV(a, b, r, op, builtin, overflow) \
379    (sizeof *(r) == sizeof (signed char) \
380     ? _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned char, \
381                        signed char, SCHAR_MIN, SCHAR_MAX) \
382     : sizeof *(r) == sizeof (short int) \
383     ? _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned short int, \
384                        short int, SHRT_MIN, SHRT_MAX) \
385     : sizeof *(r) == sizeof (int) \
386     ? _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, \
387                        int, INT_MIN, INT_MAX) \
388     : _GL_INT_OP_WRAPV_LONGISH(a, b, r, op, overflow))
389 # ifdef LLONG_MAX
390 #  define _GL_INT_OP_WRAPV_LONGISH(a, b, r, op, overflow) \
391     (sizeof *(r) == sizeof (long int) \
392      ? _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long int, \
393                         long int, LONG_MIN, LONG_MAX) \
394      : _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long long int, \
395                         long long int, LLONG_MIN, LLONG_MAX))
396 # else
397 #  define _GL_INT_OP_WRAPV_LONGISH(a, b, r, op, overflow) \
398     _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long int, \
399                      long int, LONG_MIN, LONG_MAX))
400 # endif
401 #endif
402
403 /* Store the low-order bits of A <op> B into *R, where the operation
404    is given by OP.  Use the unsigned type UT for calculation to avoid
405    overflow problems.  *R's type is T, with extremal values TMIN and
406    TMAX.  T must be a signed integer type.  */
407 #define _GL_INT_OP_CALC(a, b, r, op, overflow, ut, t, tmin, tmax) \
408   (sizeof ((a) op (b)) < sizeof (t) \
409    ? _GL_INT_OP_CALC1 ((t) (a), (t) (b), r, op, overflow, ut, t, tmin, tmax) \
410    : _GL_INT_OP_CALC1 (a, b, r, op, overflow, ut, t, tmin, tmax))
411 #define _GL_INT_OP_CALC1(a, b, r, op, overflow, ut, t, tmin, tmax) \
412   ((overflow (a, b) \
413     || (EXPR_SIGNED ((a) op (b)) && ((a) op (b)) < (tmin)) \
414     || (tmax) < ((a) op (b))) \
415    ? (*(r) = _GL_INT_OP_WRAPV_VIA_UNSIGNED (a, b, op, ut, t, tmin, tmax), 1) \
416    : (*(r) = _GL_INT_OP_WRAPV_VIA_UNSIGNED (a, b, op, ut, t, tmin, tmax), 0))
417
418 /* Return A <op> B, where the operation is given by OP.  Use the
419    unsigned type UT for calculation to avoid overflow problems.
420    Convert the result to type T without overflow by subtracting TMIN
421    from large values before converting, and adding it afterwards.
422    Compilers can optimize all the operations except OP.  */
423 #define _GL_INT_OP_WRAPV_VIA_UNSIGNED(a, b, op, ut, t, tmin, tmax) \
424   (((ut) (a) op (ut) (b)) <= (tmax) \
425    ? (t) ((ut) (a) op (ut) (b)) \
426    : ((t) (((ut) (a) op (ut) (b)) - (tmin)) + (tmin)))
427
428 #endif /* _GL_INTPROPS_H */