intprops: work around C compiler bugs
[gnulib.git] / lib / intprops.h
1 /* intprops.h -- properties of integer types
2
3    Copyright (C) 2001-2005, 2009-2011 Free Software Foundation, Inc.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    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
25 /* Return a integer value, converted to the same type as the integer
26    expression E after integer type promotion.  V is the unconverted value.
27    E should not have side effects.  */
28 #define _GL_INT_CONVERT(e, v) ((e) - (e) + (v))
29
30 /* The extra casts in the following macros work around compiler bugs,
31    e.g., in Cray C 5.0.3.0.  */
32
33 /* True if the arithmetic type T is an integer type.  bool counts as
34    an integer.  */
35 #define TYPE_IS_INTEGER(t) ((t) 1.5 == 1)
36
37 /* True if negative values of the signed integer type T use two's
38    complement, ones' complement, or signed magnitude representation,
39    respectively.  Much GNU code assumes two's complement, but some
40    people like to be portable to all possible C hosts.  */
41 #define TYPE_TWOS_COMPLEMENT(t) ((t) ~ (t) 0 == (t) -1)
42 #define TYPE_ONES_COMPLEMENT(t) ((t) ~ (t) 0 == 0)
43 #define TYPE_SIGNED_MAGNITUDE(t) ((t) ~ (t) 0 < (t) -1)
44
45 /* True if the signed integer expression E uses two's complement.  */
46 #define _GL_INT_TWOS_COMPLEMENT(e) (~ _GL_INT_CONVERT (e, 0) == -1)
47
48 /* True if the arithmetic type T is signed.  */
49 #define TYPE_SIGNED(t) (! ((t) 0 < (t) -1))
50
51 /* Return 1 if the integer expression E, after integer promotion, has
52    a signed type.  E should not have side effects.  */
53 #define _GL_INT_SIGNED(e) (_GL_INT_CONVERT (e, -1) < 0)
54
55
56 /* Minimum and maximum values for integer types and expressions.  These
57    macros have undefined behavior if T is signed and has padding bits.
58    If this is a problem for you, please let us know how to fix it for
59    your host.  */
60
61 /* The maximum and minimum values for the integer type T.  */
62 #define TYPE_MINIMUM(t)                                                 \
63   ((t) (! TYPE_SIGNED (t)                                               \
64         ? (t) 0                                                         \
65         : TYPE_SIGNED_MAGNITUDE (t)                                     \
66         ? ~ (t) 0                                                       \
67         : ~ TYPE_MAXIMUM (t)))
68 #define TYPE_MAXIMUM(t)                                                 \
69   ((t) (! TYPE_SIGNED (t)                                               \
70         ? (t) -1                                                        \
71         : ((((t) 1 << (sizeof (t) * CHAR_BIT - 2)) - 1) * 2 + 1)))
72
73 /* The maximum and minimum values for the type of the expression E,
74    after integer promotion.  E should not have side effects.  */
75 #define _GL_INT_MINIMUM(e)                                              \
76   (_GL_INT_SIGNED (e)                                                   \
77    ? - _GL_INT_TWOS_COMPLEMENT (e) - _GL_SIGNED_INT_MAXIMUM (e)         \
78    : _GL_INT_CONVERT (e, 0))
79 #define _GL_INT_MAXIMUM(e)                                              \
80   (_GL_INT_SIGNED (e)                                                   \
81    ? _GL_SIGNED_INT_MAXIMUM (e)                                         \
82    : _GL_INT_CONVERT (e, -1))
83 #define _GL_SIGNED_INT_MAXIMUM(e)                                       \
84   (((_GL_INT_CONVERT (e, 1) << (sizeof ((e) + 0) * CHAR_BIT - 2)) - 1) * 2 + 1)
85
86
87 /* Return 1 if the __typeof__ keyword works.  This could be done by
88    'configure', but for now it's easier to do it by hand.  */
89 #if 2 <= __GNUC__ || 0x5110 <= __SUNPRO_C
90 # define _GL_HAVE___TYPEOF__ 1
91 #else
92 # define _GL_HAVE___TYPEOF__ 0
93 #endif
94
95 /* Return 1 if the integer type or expression T might be signed.  Return 0
96    if it is definitely unsigned.  This macro does not evaluate its argument,
97    and expands to an integer constant expression.  */
98 #if _GL_HAVE___TYPEOF__
99 # define _GL_SIGNED_TYPE_OR_EXPR(t) TYPE_SIGNED (__typeof__ (t))
100 #else
101 # define _GL_SIGNED_TYPE_OR_EXPR(t) 1
102 #endif
103
104 /* Bound on length of the string representing an unsigned integer
105    value representable in B bits.  log10 (2.0) < 146/485.  The
106    smallest value of B where this bound is not tight is 2621.  */
107 #define INT_BITS_STRLEN_BOUND(b) (((b) * 146 + 484) / 485)
108
109 /* Bound on length of the string representing an integer type or expression T.
110    Subtract 1 for the sign bit if T is signed, and then add 1 more for
111    a minus sign if needed.
112
113    Because _GL_SIGNED_TYPE_OR_EXPR sometimes returns 0 when its argument is
114    signed, this macro may overestimate the true bound by one byte when
115    applied to unsigned types of size 2, 4, 16, ... bytes.  */
116 #define INT_STRLEN_BOUND(t)                                     \
117   (INT_BITS_STRLEN_BOUND (sizeof (t) * CHAR_BIT                 \
118                           - _GL_SIGNED_TYPE_OR_EXPR (t))        \
119    + _GL_SIGNED_TYPE_OR_EXPR (t))
120
121 /* Bound on buffer size needed to represent an integer type or expression T,
122    including the terminating null.  */
123 #define INT_BUFSIZE_BOUND(t) (INT_STRLEN_BOUND (t) + 1)
124
125
126 /* Range overflow checks.
127
128    The INT_<op>_RANGE_OVERFLOW macros return 1 if the corresponding C
129    operators might not yield numerically correct answers due to
130    arithmetic overflow.  They do not rely on undefined or
131    implementation-defined behavior.  Their implementations are simple
132    and straightforward, but they are a bit harder to use than the
133    INT_<op>_OVERFLOW macros described below.
134
135    Example usage:
136
137      long int i = ...;
138      long int j = ...;
139      if (INT_MULTIPLY_RANGE_OVERFLOW (i, j, LONG_MIN, LONG_MAX))
140        printf ("multiply would overflow");
141      else
142        printf ("product is %ld", i * j);
143
144    Restrictions on *_RANGE_OVERFLOW macros:
145
146    These macros do not check for all possible numerical problems or
147    undefined or unspecified behavior: they do not check for division
148    by zero, for bad shift counts, or for shifting negative numbers.
149
150    These macros may evaluate their arguments zero or multiple times,
151    so the arguments should not have side effects.  The arithmetic
152    arguments (including the MIN and MAX arguments) must be of the same
153    integer type after the usual arithmetic conversions, and the type
154    must have minimum value MIN and maximum MAX.  Unsigned types should
155    use a zero MIN of the proper type.
156
157    These macros are tuned for constant MIN and MAX.  For commutative
158    operations such as A + B, they are also tuned for constant B.  */
159
160 /* Return 1 if A + B would overflow in [MIN,MAX] arithmetic.
161    See above for restrictions.  */
162 #define INT_ADD_RANGE_OVERFLOW(a, b, min, max)          \
163   ((b) < 0                                              \
164    ? (a) < (min) - (b)                                  \
165    : (max) - (b) < (a))
166
167 /* Return 1 if A - B would overflow in [MIN,MAX] arithmetic.
168    See above for restrictions.  */
169 #define INT_SUBTRACT_RANGE_OVERFLOW(a, b, min, max)     \
170   ((b) < 0                                              \
171    ? (max) + (b) < (a)                                  \
172    : (a) < (min) + (b))
173
174 /* Return 1 if - A would overflow in [MIN,MAX] arithmetic.
175    See above for restrictions.  */
176 #define INT_NEGATE_RANGE_OVERFLOW(a, min, max)          \
177   ((min) < 0                                            \
178    ? (a) < - (max)                                      \
179    : 0 < (a))
180
181 /* Return 1 if A * B would overflow in [MIN,MAX] arithmetic.
182    See above for restrictions.  Avoid && and || as they tickle
183    bugs in Sun C 5.11 2010/08/13 and other compilers; see
184    <http://lists.gnu.org/archive/html/bug-gnulib/2011-05/msg00401.html>.  */
185 #define INT_MULTIPLY_RANGE_OVERFLOW(a, b, min, max)     \
186   ((b) < 0                                              \
187    ? ((a) < 0                                           \
188       ? (a) < (max) / (b)                               \
189       : (b) == -1                                       \
190       ? 0                                               \
191       : (min) / (b) < (a))                              \
192    : (b) == 0                                           \
193    ? 0                                                  \
194    : ((a) < 0                                           \
195       ? (a) < (min) / (b)                               \
196       : (max) / (b) < (a)))
197
198 /* Return 1 if A / B would overflow in [MIN,MAX] arithmetic.
199    See above for restrictions.  Do not check for division by zero.  */
200 #define INT_DIVIDE_RANGE_OVERFLOW(a, b, min, max)       \
201   ((min) < 0 && (b) == -1 && (a) < - (max))
202
203 /* Return 1 if A % B would overflow in [MIN,MAX] arithmetic.
204    See above for restrictions.  Do not check for division by zero.
205    Mathematically, % should never overflow, but on x86-like hosts
206    INT_MIN % -1 traps, and the C standard permits this, so treat this
207    as an overflow too.  */
208 #define INT_REMAINDER_RANGE_OVERFLOW(a, b, min, max)    \
209   INT_DIVIDE_RANGE_OVERFLOW (a, b, min, max)
210
211 /* Return 1 if A << B would overflow in [MIN,MAX] arithmetic.
212    See above for restrictions.  Here, MIN and MAX are for A only, and B need
213    not be of the same type as the other arguments.  The C standard says that
214    behavior is undefined for shifts unless 0 <= B < wordwidth, and that when
215    A is negative then A << B has undefined behavior and A >> B has
216    implementation-defined behavior, but do not check these other
217    restrictions.  */
218 #define INT_LEFT_SHIFT_RANGE_OVERFLOW(a, b, min, max)   \
219   ((a) < 0                                              \
220    ? (a) < (min) >> (b)                                 \
221    : (max) >> (b) < (a))
222
223
224 /* The _GL*_OVERFLOW macros have the same restrictions as the
225    *_RANGE_OVERFLOW macros, except that they do not assume that operands
226    (e.g., A and B) have the same type as MIN and MAX.  Instead, they assume
227    that the result (e.g., A + B) has that type.  */
228 #define _GL_ADD_OVERFLOW(a, b, min, max)                                \
229   ((min) < 0 ? INT_ADD_RANGE_OVERFLOW (a, b, min, max)                  \
230    : (a) < 0 ? (b) <= (a) + (b)                                         \
231    : (b) < 0 ? (a) <= (a) + (b)                                         \
232    : (a) + (b) < (b))
233 #define _GL_SUBTRACT_OVERFLOW(a, b, min, max)                           \
234   ((min) < 0 ? INT_SUBTRACT_RANGE_OVERFLOW (a, b, min, max)             \
235    : (a) < 0 ? 1                                                        \
236    : (b) < 0 ? (a) - (b) <= (a)                                         \
237    : (a) < (b))
238 #define _GL_MULTIPLY_OVERFLOW(a, b, min, max)                           \
239   (((min) == 0 && (((a) < 0 && 0 < (b)) || ((b) < 0 && 0 < (a))))       \
240    || INT_MULTIPLY_RANGE_OVERFLOW (a, b, min, max))
241 #define _GL_DIVIDE_OVERFLOW(a, b, min, max)                             \
242   ((min) < 0 ? (b) == _GL_INT_CONVERT (min, -1) && (a) < - (max)        \
243    : (a) < 0 ? (b) <= (a) + (b) - 1                                     \
244    : (b) < 0 && (a) + (b) <= (a))
245 #define _GL_REMAINDER_OVERFLOW(a, b, min, max)                          \
246   ((min) < 0 ? (b) == _GL_INT_CONVERT (min, -1) && (a) < - (max)        \
247    : (a) < 0 ? (a) % (b) != ((max) - (b) + 1) % (b)                     \
248    : (b) < 0 && ! _GL_UNSIGNED_NEG_MULTIPLE (a, b, max))
249
250 /* Return a nonzero value if A is a mathematical multiple of B, where
251    A is unsigned, B is negative, and MAX is the maximum value of A's
252    type.  A's type must be the same as (A % B)'s type.  Normally (A %
253    -B == 0) suffices, but things get tricky if -B would overflow.  */
254 #define _GL_UNSIGNED_NEG_MULTIPLE(a, b, max)                            \
255   (((b) < -_GL_SIGNED_INT_MAXIMUM (b)                                   \
256     ? (_GL_SIGNED_INT_MAXIMUM (b) == (max)                              \
257        ? (a)                                                            \
258        : (a) % (_GL_INT_CONVERT (a, _GL_SIGNED_INT_MAXIMUM (b)) + 1))   \
259     : (a) % - (b))                                                      \
260    == 0)
261
262
263 /* Integer overflow checks.
264
265    The INT_<op>_OVERFLOW macros return 1 if the corresponding C operators
266    might not yield numerically correct answers due to arithmetic overflow.
267    They work correctly on all known practical hosts, and do not rely
268    on undefined behavior due to signed arithmetic overflow.
269
270    Example usage:
271
272      long int i = ...;
273      long int j = ...;
274      if (INT_MULTIPLY_OVERFLOW (i, j))
275        printf ("multiply would overflow");
276      else
277        printf ("product is %ld", i * j);
278
279    These macros do not check for all possible numerical problems or
280    undefined or unspecified behavior: they do not check for division
281    by zero, for bad shift counts, or for shifting negative numbers.
282
283    These macros may evaluate their arguments zero or multiple times, so the
284    arguments should not have side effects.
285
286    These macros are tuned for their last argument being a constant.
287
288    Return 1 if the integer expressions A * B, A - B, -A, A * B, A / B,
289    A % B, and A << B would overflow, respectively.  */
290
291 #define INT_ADD_OVERFLOW(a, b) \
292   _GL_BINARY_OP_OVERFLOW (a, b, _GL_ADD_OVERFLOW)
293 #define INT_SUBTRACT_OVERFLOW(a, b) \
294   _GL_BINARY_OP_OVERFLOW (a, b, _GL_SUBTRACT_OVERFLOW)
295 #define INT_NEGATE_OVERFLOW(a) \
296   INT_NEGATE_RANGE_OVERFLOW (a, _GL_INT_MINIMUM (a), _GL_INT_MAXIMUM (a))
297 #define INT_MULTIPLY_OVERFLOW(a, b) \
298   _GL_BINARY_OP_OVERFLOW (a, b, _GL_MULTIPLY_OVERFLOW)
299 #define INT_DIVIDE_OVERFLOW(a, b) \
300   _GL_BINARY_OP_OVERFLOW (a, b, _GL_DIVIDE_OVERFLOW)
301 #define INT_REMAINDER_OVERFLOW(a, b) \
302   _GL_BINARY_OP_OVERFLOW (a, b, _GL_REMAINDER_OVERFLOW)
303 #define INT_LEFT_SHIFT_OVERFLOW(a, b) \
304   INT_LEFT_SHIFT_RANGE_OVERFLOW (a, b, \
305                                  _GL_INT_MINIMUM (a), _GL_INT_MAXIMUM (a))
306
307 /* Return 1 if the expression A <op> B would overflow,
308    where OP_RESULT_OVERFLOW (A, B, MIN, MAX) does the actual test,
309    assuming MIN and MAX are the minimum and maximum for the result type.
310
311    This macro assumes that A | B is a valid integer if both A and B are,
312    which is true of all known practical hosts.  If this is a problem
313    for you, please let us know how to fix it for your host.  */
314 #define _GL_BINARY_OP_OVERFLOW(a, b, op_result_overflow)        \
315   op_result_overflow (a, b,                                     \
316                       _GL_INT_MINIMUM ((a) | (b)),              \
317                       _GL_INT_MAXIMUM ((a) | (b)))
318
319 #endif /* _GL_INTPROPS_H */