OSDN Git Service

2008-11-14 Thomas Schwinge <tschwinge@gnu.org>
[pf3gnuchains/gcc-fork.git] / libcpp / expr.c
1 /* Parse C expressions for cpplib.
2    Copyright (C) 1987, 1992, 1994, 1995, 1997, 1998, 1999, 2000, 2001,
3    2002, 2004, 2008 Free Software Foundation.
4    Contributed by Per Bothner, 1994.
5
6 This program is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 2, or (at your option) any
9 later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, 51 Franklin Street, Fifth Floor,
19 Boston, MA 02110-1301, USA.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "cpplib.h"
24 #include "internal.h"
25
26 #define PART_PRECISION (sizeof (cpp_num_part) * CHAR_BIT)
27 #define HALF_MASK (~(cpp_num_part) 0 >> (PART_PRECISION / 2))
28 #define LOW_PART(num_part) (num_part & HALF_MASK)
29 #define HIGH_PART(num_part) (num_part >> (PART_PRECISION / 2))
30
31 struct op
32 {
33   const cpp_token *token;       /* The token forming op (for diagnostics).  */
34   cpp_num value;                /* The value logically "right" of op.  */
35   source_location loc;          /* The location of this value.         */
36   enum cpp_ttype op;
37 };
38
39 /* Some simple utility routines on double integers.  */
40 #define num_zerop(num) ((num.low | num.high) == 0)
41 #define num_eq(num1, num2) (num1.low == num2.low && num1.high == num2.high)
42 static bool num_positive (cpp_num, size_t);
43 static bool num_greater_eq (cpp_num, cpp_num, size_t);
44 static cpp_num num_trim (cpp_num, size_t);
45 static cpp_num num_part_mul (cpp_num_part, cpp_num_part);
46
47 static cpp_num num_unary_op (cpp_reader *, cpp_num, enum cpp_ttype);
48 static cpp_num num_binary_op (cpp_reader *, cpp_num, cpp_num, enum cpp_ttype);
49 static cpp_num num_negate (cpp_num, size_t);
50 static cpp_num num_bitwise_op (cpp_reader *, cpp_num, cpp_num, enum cpp_ttype);
51 static cpp_num num_inequality_op (cpp_reader *, cpp_num, cpp_num,
52                                   enum cpp_ttype);
53 static cpp_num num_equality_op (cpp_reader *, cpp_num, cpp_num,
54                                 enum cpp_ttype);
55 static cpp_num num_mul (cpp_reader *, cpp_num, cpp_num);
56 static cpp_num num_div_op (cpp_reader *, cpp_num, cpp_num, enum cpp_ttype);
57 static cpp_num num_lshift (cpp_num, size_t, size_t);
58 static cpp_num num_rshift (cpp_num, size_t, size_t);
59
60 static cpp_num append_digit (cpp_num, int, int, size_t);
61 static cpp_num parse_defined (cpp_reader *);
62 static cpp_num eval_token (cpp_reader *, const cpp_token *);
63 static struct op *reduce (cpp_reader *, struct op *, enum cpp_ttype);
64 static unsigned int interpret_float_suffix (const uchar *, size_t);
65 static unsigned int interpret_int_suffix (const uchar *, size_t);
66 static void check_promotion (cpp_reader *, const struct op *);
67
68 /* Token type abuse to create unary plus and minus operators.  */
69 #define CPP_UPLUS ((enum cpp_ttype) (CPP_LAST_CPP_OP + 1))
70 #define CPP_UMINUS ((enum cpp_ttype) (CPP_LAST_CPP_OP + 2))
71
72 /* With -O2, gcc appears to produce nice code, moving the error
73    message load and subsequent jump completely out of the main path.  */
74 #define SYNTAX_ERROR(msgid) \
75   do { cpp_error (pfile, CPP_DL_ERROR, msgid); goto syntax_error; } while(0)
76 #define SYNTAX_ERROR2(msgid, arg) \
77   do { cpp_error (pfile, CPP_DL_ERROR, msgid, arg); goto syntax_error; } \
78   while(0)
79
80 /* Subroutine of cpp_classify_number.  S points to a float suffix of
81    length LEN, possibly zero.  Returns 0 for an invalid suffix, or a
82    flag vector describing the suffix.  */
83 static unsigned int
84 interpret_float_suffix (const uchar *s, size_t len)
85 {
86   size_t f, l, w, q, i, d;
87   size_t r, k, u, h;
88
89   f = l = w = q = i = d = 0;
90   r = k = u = h = 0;
91
92   while (len--)
93     switch (s[len])
94       {
95       case 'r': case 'R': r++; break;
96       case 'k': case 'K': k++; break;
97       case 'u': case 'U': u++; break;
98       case 'h': case 'H': h++; break;
99       case 'f': case 'F':
100         if (d > 0)
101           return 0;
102         f++;
103         break;
104       case 'l': case 'L':
105         if (d > 0)
106           return 0;
107         l++;
108         /* If there are two Ls, they must be adjacent and the same case.  */
109         if (l == 2 && s[len] != s[len + 1])
110           return 0;
111         break;
112       case 'w': case 'W':
113         if (d > 0)
114           return 0;
115         w++;
116         break;
117       case 'q': case 'Q':
118         if (d > 0)
119           return 0;
120         q++;
121         break;
122       case 'i': case 'I':
123       case 'j': case 'J': i++; break;
124       case 'd': case 'D': d++; break;
125       default:
126         return 0;
127       }
128
129   if (r + k > 1 || h > 1 || l > 2 || u > 1)
130     return 0;
131
132   if (r == 1)
133     {
134       if (f || i || d || w || q)
135         return 0;
136
137       return (CPP_N_FRACT
138               | (u ? CPP_N_UNSIGNED : 0)
139               | (h ? CPP_N_SMALL :
140                  l == 2 ? CPP_N_LARGE :
141                  l == 1 ? CPP_N_MEDIUM :  0));
142     }
143
144   if (k == 1)
145     {
146       if (f || i || d || w || q)
147         return 0;
148
149       return (CPP_N_ACCUM
150               | (u ? CPP_N_UNSIGNED : 0)
151               | (h ? CPP_N_SMALL :
152                  l == 2 ? CPP_N_LARGE :
153                  l == 1 ? CPP_N_MEDIUM :  0));
154     }
155
156   if (f + l + w + q > 1 || i > 1 || h + u > 0)
157     return 0;
158
159   /* Allow dd, df, dl suffixes for decimal float constants.  */
160   if (d && ((d + f + l != 2) || i))
161     return 0;
162
163   return ((i ? CPP_N_IMAGINARY : 0)
164           | (f ? CPP_N_SMALL :
165              l ? CPP_N_LARGE :
166              w ? CPP_N_MD_W :
167              q ? CPP_N_MD_Q : CPP_N_MEDIUM)
168           | (d ? CPP_N_DFLOAT : 0));
169 }
170
171 /* Subroutine of cpp_classify_number.  S points to an integer suffix
172    of length LEN, possibly zero. Returns 0 for an invalid suffix, or a
173    flag vector describing the suffix.  */
174 static unsigned int
175 interpret_int_suffix (const uchar *s, size_t len)
176 {
177   size_t u, l, i;
178
179   u = l = i = 0;
180
181   while (len--)
182     switch (s[len])
183       {
184       case 'u': case 'U':       u++; break;
185       case 'i': case 'I':
186       case 'j': case 'J':       i++; break;
187       case 'l': case 'L':       l++;
188         /* If there are two Ls, they must be adjacent and the same case.  */
189         if (l == 2 && s[len] != s[len + 1])
190           return 0;
191         break;
192       default:
193         return 0;
194       }
195
196   if (l > 2 || u > 1 || i > 1)
197     return 0;
198
199   return ((i ? CPP_N_IMAGINARY : 0)
200           | (u ? CPP_N_UNSIGNED : 0)
201           | ((l == 0) ? CPP_N_SMALL
202              : (l == 1) ? CPP_N_MEDIUM : CPP_N_LARGE));
203 }
204
205 /* Categorize numeric constants according to their field (integer,
206    floating point, or invalid), radix (decimal, octal, hexadecimal),
207    and type suffixes.  */
208 unsigned int
209 cpp_classify_number (cpp_reader *pfile, const cpp_token *token)
210 {
211   const uchar *str = token->val.str.text;
212   const uchar *limit;
213   unsigned int max_digit, result, radix;
214   enum {NOT_FLOAT = 0, AFTER_POINT, AFTER_EXPON} float_flag;
215
216   /* If the lexer has done its job, length one can only be a single
217      digit.  Fast-path this very common case.  */
218   if (token->val.str.len == 1)
219     return CPP_N_INTEGER | CPP_N_SMALL | CPP_N_DECIMAL;
220
221   limit = str + token->val.str.len;
222   float_flag = NOT_FLOAT;
223   max_digit = 0;
224   radix = 10;
225
226   /* First, interpret the radix.  */
227   if (*str == '0')
228     {
229       radix = 8;
230       str++;
231
232       /* Require at least one hex digit to classify it as hex.  */
233       if ((*str == 'x' || *str == 'X')
234           && (str[1] == '.' || ISXDIGIT (str[1])))
235         {
236           radix = 16;
237           str++;
238         }
239       else if ((*str == 'b' || *str == 'B') && (str[1] == '0' || str[1] == '1'))
240         {
241           radix = 2;
242           str++;
243         }
244     }
245
246   /* Now scan for a well-formed integer or float.  */
247   for (;;)
248     {
249       unsigned int c = *str++;
250
251       if (ISDIGIT (c) || (ISXDIGIT (c) && radix == 16))
252         {
253           c = hex_value (c);
254           if (c > max_digit)
255             max_digit = c;
256         }
257       else if (c == '.')
258         {
259           if (float_flag == NOT_FLOAT)
260             float_flag = AFTER_POINT;
261           else
262             SYNTAX_ERROR ("too many decimal points in number");
263         }
264       else if ((radix <= 10 && (c == 'e' || c == 'E'))
265                || (radix == 16 && (c == 'p' || c == 'P')))
266         {
267           float_flag = AFTER_EXPON;
268           break;
269         }
270       else
271         {
272           /* Start of suffix.  */
273           str--;
274           break;
275         }
276     }
277
278   /* The suffix may be for decimal fixed-point constants without exponent.  */
279   if (radix != 16 && float_flag == NOT_FLOAT)
280     {
281       result = interpret_float_suffix (str, limit - str);
282       if ((result & CPP_N_FRACT) || (result & CPP_N_ACCUM))
283         {
284           result |= CPP_N_FLOATING;
285           /* We need to restore the radix to 10, if the radix is 8.  */
286           if (radix == 8)
287             radix = 10;
288
289           if (CPP_PEDANTIC (pfile))
290             cpp_error (pfile, CPP_DL_PEDWARN,
291                        "fixed-point constants are a GCC extension");
292           goto syntax_ok;
293         }
294       else
295         result = 0;
296     }
297
298   if (float_flag != NOT_FLOAT && radix == 8)
299     radix = 10;
300
301   if (max_digit >= radix)
302     {
303       if (radix == 2)
304         SYNTAX_ERROR2 ("invalid digit \"%c\" in binary constant", '0' + max_digit);
305       else
306         SYNTAX_ERROR2 ("invalid digit \"%c\" in octal constant", '0' + max_digit);
307     }
308
309   if (float_flag != NOT_FLOAT)
310     {
311       if (radix == 2)
312         {
313           cpp_error (pfile, CPP_DL_ERROR,
314                      "invalid prefix \"0b\" for floating constant");
315           return CPP_N_INVALID;
316         }
317
318       if (radix == 16 && CPP_PEDANTIC (pfile) && !CPP_OPTION (pfile, c99))
319         cpp_error (pfile, CPP_DL_PEDWARN,
320                    "use of C99 hexadecimal floating constant");
321
322       if (float_flag == AFTER_EXPON)
323         {
324           if (*str == '+' || *str == '-')
325             str++;
326
327           /* Exponent is decimal, even if string is a hex float.  */
328           if (!ISDIGIT (*str))
329             SYNTAX_ERROR ("exponent has no digits");
330
331           do
332             str++;
333           while (ISDIGIT (*str));
334         }
335       else if (radix == 16)
336         SYNTAX_ERROR ("hexadecimal floating constants require an exponent");
337
338       result = interpret_float_suffix (str, limit - str);
339       if (result == 0)
340         {
341           cpp_error (pfile, CPP_DL_ERROR,
342                      "invalid suffix \"%.*s\" on floating constant",
343                      (int) (limit - str), str);
344           return CPP_N_INVALID;
345         }
346
347       /* Traditional C didn't accept any floating suffixes.  */
348       if (limit != str
349           && CPP_WTRADITIONAL (pfile)
350           && ! cpp_sys_macro_p (pfile))
351         cpp_error (pfile, CPP_DL_WARNING,
352                    "traditional C rejects the \"%.*s\" suffix",
353                    (int) (limit - str), str);
354
355       /* Radix must be 10 for decimal floats.  */
356       if ((result & CPP_N_DFLOAT) && radix != 10)
357         {
358           cpp_error (pfile, CPP_DL_ERROR,
359                      "invalid suffix \"%.*s\" with hexadecimal floating constant",
360                      (int) (limit - str), str);
361           return CPP_N_INVALID;
362         }
363
364       if ((result & (CPP_N_FRACT | CPP_N_ACCUM)) && CPP_PEDANTIC (pfile))
365         cpp_error (pfile, CPP_DL_PEDWARN,
366                    "fixed-point constants are a GCC extension");
367
368       if ((result & CPP_N_DFLOAT) && CPP_PEDANTIC (pfile))
369         cpp_error (pfile, CPP_DL_PEDWARN,
370                    "decimal float constants are a GCC extension");
371
372       result |= CPP_N_FLOATING;
373     }
374   else
375     {
376       result = interpret_int_suffix (str, limit - str);
377       if (result == 0)
378         {
379           cpp_error (pfile, CPP_DL_ERROR,
380                      "invalid suffix \"%.*s\" on integer constant",
381                      (int) (limit - str), str);
382           return CPP_N_INVALID;
383         }
384
385       /* Traditional C only accepted the 'L' suffix.
386          Suppress warning about 'LL' with -Wno-long-long.  */
387       if (CPP_WTRADITIONAL (pfile) && ! cpp_sys_macro_p (pfile))
388         {
389           int u_or_i = (result & (CPP_N_UNSIGNED|CPP_N_IMAGINARY));
390           int large = (result & CPP_N_WIDTH) == CPP_N_LARGE;
391
392           if (u_or_i || (large && CPP_OPTION (pfile, warn_long_long)))
393             cpp_error (pfile, CPP_DL_WARNING,
394                        "traditional C rejects the \"%.*s\" suffix",
395                        (int) (limit - str), str);
396         }
397
398       if ((result & CPP_N_WIDTH) == CPP_N_LARGE
399           && ! CPP_OPTION (pfile, c99)
400           && CPP_OPTION (pfile, warn_long_long))
401         cpp_error (pfile, CPP_DL_PEDWARN,
402                    "use of C99 long long integer constant");
403
404       result |= CPP_N_INTEGER;
405     }
406
407  syntax_ok:
408   if ((result & CPP_N_IMAGINARY) && CPP_PEDANTIC (pfile))
409     cpp_error (pfile, CPP_DL_PEDWARN,
410                "imaginary constants are a GCC extension");
411   if (radix == 2 && CPP_PEDANTIC (pfile))
412     cpp_error (pfile, CPP_DL_PEDWARN,
413                "binary constants are a GCC extension");
414
415   if (radix == 10)
416     result |= CPP_N_DECIMAL;
417   else if (radix == 16)
418     result |= CPP_N_HEX;
419   else if (radix == 2)
420     result |= CPP_N_BINARY;
421   else
422     result |= CPP_N_OCTAL;
423
424   return result;
425
426  syntax_error:
427   return CPP_N_INVALID;
428 }
429
430 /* cpp_interpret_integer converts an integer constant into a cpp_num,
431    of precision options->precision.
432
433    We do not provide any interface for decimal->float conversion,
434    because the preprocessor doesn't need it and we don't want to
435    drag in GCC's floating point emulator.  */
436 cpp_num
437 cpp_interpret_integer (cpp_reader *pfile, const cpp_token *token,
438                        unsigned int type)
439 {
440   const uchar *p, *end;
441   cpp_num result;
442
443   result.low = 0;
444   result.high = 0;
445   result.unsignedp = !!(type & CPP_N_UNSIGNED);
446   result.overflow = false;
447
448   p = token->val.str.text;
449   end = p + token->val.str.len;
450
451   /* Common case of a single digit.  */
452   if (token->val.str.len == 1)
453     result.low = p[0] - '0';
454   else
455     {
456       cpp_num_part max;
457       size_t precision = CPP_OPTION (pfile, precision);
458       unsigned int base = 10, c = 0;
459       bool overflow = false;
460
461       if ((type & CPP_N_RADIX) == CPP_N_OCTAL)
462         {
463           base = 8;
464           p++;
465         }
466       else if ((type & CPP_N_RADIX) == CPP_N_HEX)
467         {
468           base = 16;
469           p += 2;
470         }
471       else if ((type & CPP_N_RADIX) == CPP_N_BINARY)
472         {
473           base = 2;
474           p += 2;
475         }
476
477       /* We can add a digit to numbers strictly less than this without
478          needing the precision and slowness of double integers.  */
479       max = ~(cpp_num_part) 0;
480       if (precision < PART_PRECISION)
481         max >>= PART_PRECISION - precision;
482       max = (max - base + 1) / base + 1;
483
484       for (; p < end; p++)
485         {
486           c = *p;
487
488           if (ISDIGIT (c) || (base == 16 && ISXDIGIT (c)))
489             c = hex_value (c);
490           else
491             break;
492
493           /* Strict inequality for when max is set to zero.  */
494           if (result.low < max)
495             result.low = result.low * base + c;
496           else
497             {
498               result = append_digit (result, c, base, precision);
499               overflow |= result.overflow;
500               max = 0;
501             }
502         }
503
504       if (overflow)
505         cpp_error (pfile, CPP_DL_PEDWARN,
506                    "integer constant is too large for its type");
507       /* If too big to be signed, consider it unsigned.  Only warn for
508          decimal numbers.  Traditional numbers were always signed (but
509          we still honor an explicit U suffix); but we only have
510          traditional semantics in directives.  */
511       else if (!result.unsignedp
512                && !(CPP_OPTION (pfile, traditional)
513                     && pfile->state.in_directive)
514                && !num_positive (result, precision))
515         {
516           if (base == 10)
517             cpp_error (pfile, CPP_DL_WARNING,
518                        "integer constant is so large that it is unsigned");
519           result.unsignedp = true;
520         }
521     }
522
523   return result;
524 }
525
526 /* Append DIGIT to NUM, a number of PRECISION bits being read in base BASE.  */
527 static cpp_num
528 append_digit (cpp_num num, int digit, int base, size_t precision)
529 {
530   cpp_num result;
531   unsigned int shift;
532   bool overflow;
533   cpp_num_part add_high, add_low;
534
535   /* Multiply by 2, 8 or 16.  Catching this overflow here means we don't
536      need to worry about add_high overflowing.  */
537   switch (base)
538     {
539     case 2:
540       shift = 1;
541       break;
542
543     case 16:
544       shift = 4;
545       break;
546
547     default:
548       shift = 3;
549     }
550   overflow = !!(num.high >> (PART_PRECISION - shift));
551   result.high = num.high << shift;
552   result.low = num.low << shift;
553   result.high |= num.low >> (PART_PRECISION - shift);
554   result.unsignedp = num.unsignedp;
555
556   if (base == 10)
557     {
558       add_low = num.low << 1;
559       add_high = (num.high << 1) + (num.low >> (PART_PRECISION - 1));
560     }
561   else
562     add_high = add_low = 0;
563
564   if (add_low + digit < add_low)
565     add_high++;
566   add_low += digit;
567
568   if (result.low + add_low < result.low)
569     add_high++;
570   if (result.high + add_high < result.high)
571     overflow = true;
572
573   result.low += add_low;
574   result.high += add_high;
575   result.overflow = overflow;
576
577   /* The above code catches overflow of a cpp_num type.  This catches
578      overflow of the (possibly shorter) target precision.  */
579   num.low = result.low;
580   num.high = result.high;
581   result = num_trim (result, precision);
582   if (!num_eq (result, num))
583     result.overflow = true;
584
585   return result;
586 }
587
588 /* Handle meeting "defined" in a preprocessor expression.  */
589 static cpp_num
590 parse_defined (cpp_reader *pfile)
591 {
592   cpp_num result;
593   int paren = 0;
594   cpp_hashnode *node = 0;
595   const cpp_token *token;
596   cpp_context *initial_context = pfile->context;
597
598   /* Don't expand macros.  */
599   pfile->state.prevent_expansion++;
600
601   token = cpp_get_token (pfile);
602   if (token->type == CPP_OPEN_PAREN)
603     {
604       paren = 1;
605       token = cpp_get_token (pfile);
606     }
607
608   if (token->type == CPP_NAME)
609     {
610       node = token->val.node;
611       if (paren && cpp_get_token (pfile)->type != CPP_CLOSE_PAREN)
612         {
613           cpp_error (pfile, CPP_DL_ERROR, "missing ')' after \"defined\"");
614           node = 0;
615         }
616     }
617   else
618     {
619       cpp_error (pfile, CPP_DL_ERROR,
620                  "operator \"defined\" requires an identifier");
621       if (token->flags & NAMED_OP)
622         {
623           cpp_token op;
624
625           op.flags = 0;
626           op.type = token->type;
627           cpp_error (pfile, CPP_DL_ERROR,
628                      "(\"%s\" is an alternative token for \"%s\" in C++)",
629                      cpp_token_as_text (pfile, token),
630                      cpp_token_as_text (pfile, &op));
631         }
632     }
633
634   if (node)
635     {
636       if (pfile->context != initial_context && CPP_PEDANTIC (pfile))
637         cpp_error (pfile, CPP_DL_WARNING,
638                    "this use of \"defined\" may not be portable");
639
640       _cpp_mark_macro_used (node);
641       if (!(node->flags & NODE_USED))
642         {
643           node->flags |= NODE_USED;
644           if (node->type == NT_MACRO)
645             {
646               if (pfile->cb.used_define)
647                 pfile->cb.used_define (pfile, pfile->directive_line, node);
648             }
649           else
650             {
651               if (pfile->cb.used_undef)
652                 pfile->cb.used_undef (pfile, pfile->directive_line, node);
653             }
654         }
655
656       /* A possible controlling macro of the form #if !defined ().
657          _cpp_parse_expr checks there was no other junk on the line.  */
658       pfile->mi_ind_cmacro = node;
659     }
660
661   pfile->state.prevent_expansion--;
662
663   result.unsignedp = false;
664   result.high = 0;
665   result.overflow = false;
666   result.low = node && node->type == NT_MACRO;
667   return result;
668 }
669
670 /* Convert a token into a CPP_NUMBER (an interpreted preprocessing
671    number or character constant, or the result of the "defined" or "#"
672    operators).  */
673 static cpp_num
674 eval_token (cpp_reader *pfile, const cpp_token *token)
675 {
676   cpp_num result;
677   unsigned int temp;
678   int unsignedp = 0;
679
680   result.unsignedp = false;
681   result.overflow = false;
682
683   switch (token->type)
684     {
685     case CPP_NUMBER:
686       temp = cpp_classify_number (pfile, token);
687       switch (temp & CPP_N_CATEGORY)
688         {
689         case CPP_N_FLOATING:
690           cpp_error (pfile, CPP_DL_ERROR,
691                      "floating constant in preprocessor expression");
692           break;
693         case CPP_N_INTEGER:
694           if (!(temp & CPP_N_IMAGINARY))
695             return cpp_interpret_integer (pfile, token, temp);
696           cpp_error (pfile, CPP_DL_ERROR,
697                      "imaginary number in preprocessor expression");
698           break;
699
700         case CPP_N_INVALID:
701           /* Error already issued.  */
702           break;
703         }
704       result.high = result.low = 0;
705       break;
706
707     case CPP_WCHAR:
708     case CPP_CHAR:
709     case CPP_CHAR16:
710     case CPP_CHAR32:
711       {
712         cppchar_t cc = cpp_interpret_charconst (pfile, token,
713                                                 &temp, &unsignedp);
714
715         result.high = 0;
716         result.low = cc;
717         /* Sign-extend the result if necessary.  */
718         if (!unsignedp && (cppchar_signed_t) cc < 0)
719           {
720             if (PART_PRECISION > BITS_PER_CPPCHAR_T)
721               result.low |= ~(~(cpp_num_part) 0
722                               >> (PART_PRECISION - BITS_PER_CPPCHAR_T));
723             result.high = ~(cpp_num_part) 0;
724             result = num_trim (result, CPP_OPTION (pfile, precision));
725           }
726       }
727       break;
728
729     case CPP_NAME:
730       if (token->val.node == pfile->spec_nodes.n_defined)
731         return parse_defined (pfile);
732       else if (CPP_OPTION (pfile, cplusplus)
733                && (token->val.node == pfile->spec_nodes.n_true
734                    || token->val.node == pfile->spec_nodes.n_false))
735         {
736           result.high = 0;
737           result.low = (token->val.node == pfile->spec_nodes.n_true);
738         }
739       else
740         {
741           result.high = 0;
742           result.low = 0;
743           if (CPP_OPTION (pfile, warn_undef) && !pfile->state.skip_eval)
744             cpp_error (pfile, CPP_DL_WARNING, "\"%s\" is not defined",
745                        NODE_NAME (token->val.node));
746         }
747       break;
748
749     case CPP_HASH:
750       if (!pfile->state.skipping)
751         {
752           /* A pedantic warning takes precedence over a deprecated
753              warning here.  */
754           if (CPP_PEDANTIC (pfile))
755             cpp_error (pfile, CPP_DL_PEDWARN,
756                        "assertions are a GCC extension");
757           else if (CPP_OPTION (pfile, warn_deprecated))
758             cpp_error (pfile, CPP_DL_WARNING,
759                        "assertions are a deprecated extension");
760         }
761       _cpp_test_assertion (pfile, &temp);
762       result.high = 0;
763       result.low = temp;
764       break;
765
766     default:
767       abort ();
768     }
769
770   result.unsignedp = !!unsignedp;
771   return result;
772 }
773 \f
774 /* Operator precedence and flags table.
775
776 After an operator is returned from the lexer, if it has priority less
777 than the operator on the top of the stack, we reduce the stack by one
778 operator and repeat the test.  Since equal priorities do not reduce,
779 this is naturally right-associative.
780
781 We handle left-associative operators by decrementing the priority of
782 just-lexed operators by one, but retaining the priority of operators
783 already on the stack.
784
785 The remaining cases are '(' and ')'.  We handle '(' by skipping the
786 reduction phase completely.  ')' is given lower priority than
787 everything else, including '(', effectively forcing a reduction of the
788 parenthesized expression.  If there is a matching '(', the routine
789 reduce() exits immediately.  If the normal exit route sees a ')', then
790 there cannot have been a matching '(' and an error message is output.
791
792 The parser assumes all shifted operators require a left operand unless
793 the flag NO_L_OPERAND is set.  These semantics are automatic; any
794 extra semantics need to be handled with operator-specific code.  */
795
796 /* Flags.  If CHECK_PROMOTION, we warn if the effective sign of an
797    operand changes because of integer promotions.  */
798 #define NO_L_OPERAND    (1 << 0)
799 #define LEFT_ASSOC      (1 << 1)
800 #define CHECK_PROMOTION (1 << 2)
801
802 /* Operator to priority map.  Must be in the same order as the first
803    N entries of enum cpp_ttype.  */
804 static const struct cpp_operator
805 {
806   uchar prio;
807   uchar flags;
808 } optab[] =
809 {
810   /* EQ */              {0, 0}, /* Shouldn't happen.  */
811   /* NOT */             {16, NO_L_OPERAND},
812   /* GREATER */         {12, LEFT_ASSOC | CHECK_PROMOTION},
813   /* LESS */            {12, LEFT_ASSOC | CHECK_PROMOTION},
814   /* PLUS */            {14, LEFT_ASSOC | CHECK_PROMOTION},
815   /* MINUS */           {14, LEFT_ASSOC | CHECK_PROMOTION},
816   /* MULT */            {15, LEFT_ASSOC | CHECK_PROMOTION},
817   /* DIV */             {15, LEFT_ASSOC | CHECK_PROMOTION},
818   /* MOD */             {15, LEFT_ASSOC | CHECK_PROMOTION},
819   /* AND */             {9, LEFT_ASSOC | CHECK_PROMOTION},
820   /* OR */              {7, LEFT_ASSOC | CHECK_PROMOTION},
821   /* XOR */             {8, LEFT_ASSOC | CHECK_PROMOTION},
822   /* RSHIFT */          {13, LEFT_ASSOC},
823   /* LSHIFT */          {13, LEFT_ASSOC},
824
825   /* COMPL */           {16, NO_L_OPERAND},
826   /* AND_AND */         {6, LEFT_ASSOC},
827   /* OR_OR */           {5, LEFT_ASSOC},
828   /* Note that QUERY, COLON, and COMMA must have the same precedence.
829      However, there are some special cases for these in reduce().  */
830   /* QUERY */           {4, 0},
831   /* COLON */           {4, LEFT_ASSOC | CHECK_PROMOTION},
832   /* COMMA */           {4, LEFT_ASSOC},
833   /* OPEN_PAREN */      {1, NO_L_OPERAND},
834   /* CLOSE_PAREN */     {0, 0},
835   /* EOF */             {0, 0},
836   /* EQ_EQ */           {11, LEFT_ASSOC},
837   /* NOT_EQ */          {11, LEFT_ASSOC},
838   /* GREATER_EQ */      {12, LEFT_ASSOC | CHECK_PROMOTION},
839   /* LESS_EQ */         {12, LEFT_ASSOC | CHECK_PROMOTION},
840   /* UPLUS */           {16, NO_L_OPERAND},
841   /* UMINUS */          {16, NO_L_OPERAND}
842 };
843
844 /* Parse and evaluate a C expression, reading from PFILE.
845    Returns the truth value of the expression.
846
847    The implementation is an operator precedence parser, i.e. a
848    bottom-up parser, using a stack for not-yet-reduced tokens.
849
850    The stack base is op_stack, and the current stack pointer is 'top'.
851    There is a stack element for each operator (only), and the most
852    recently pushed operator is 'top->op'.  An operand (value) is
853    stored in the 'value' field of the stack element of the operator
854    that precedes it.  */
855 bool
856 _cpp_parse_expr (cpp_reader *pfile, bool is_if)
857 {
858   struct op *top = pfile->op_stack;
859   unsigned int lex_count;
860   bool saw_leading_not, want_value = true;
861
862   pfile->state.skip_eval = 0;
863
864   /* Set up detection of #if ! defined().  */
865   pfile->mi_ind_cmacro = 0;
866   saw_leading_not = false;
867   lex_count = 0;
868
869   /* Lowest priority operator prevents further reductions.  */
870   top->op = CPP_EOF;
871
872   for (;;)
873     {
874       struct op op;
875
876       lex_count++;
877       op.token = cpp_get_token (pfile);
878       op.op = op.token->type;
879       op.loc = op.token->src_loc;
880
881       switch (op.op)
882         {
883           /* These tokens convert into values.  */
884         case CPP_NUMBER:
885         case CPP_CHAR:
886         case CPP_WCHAR:
887         case CPP_CHAR16:
888         case CPP_CHAR32:
889         case CPP_NAME:
890         case CPP_HASH:
891           if (!want_value)
892             SYNTAX_ERROR2 ("missing binary operator before token \"%s\"",
893                            cpp_token_as_text (pfile, op.token));
894           want_value = false;
895           top->value = eval_token (pfile, op.token);
896           continue;
897
898         case CPP_NOT:
899           saw_leading_not = lex_count == 1;
900           break;
901         case CPP_PLUS:
902           if (want_value)
903             op.op = CPP_UPLUS;
904           break;
905         case CPP_MINUS:
906           if (want_value)
907             op.op = CPP_UMINUS;
908           break;
909
910         default:
911           if ((int) op.op <= (int) CPP_EQ || (int) op.op >= (int) CPP_PLUS_EQ)
912             SYNTAX_ERROR2 ("token \"%s\" is not valid in preprocessor expressions",
913                            cpp_token_as_text (pfile, op.token));
914           break;
915         }
916
917       /* Check we have a value or operator as appropriate.  */
918       if (optab[op.op].flags & NO_L_OPERAND)
919         {
920           if (!want_value)
921             SYNTAX_ERROR2 ("missing binary operator before token \"%s\"",
922                            cpp_token_as_text (pfile, op.token));
923         }
924       else if (want_value)
925         {
926           /* We want a number (or expression) and haven't got one.
927              Try to emit a specific diagnostic.  */
928           if (op.op == CPP_CLOSE_PAREN && top->op == CPP_OPEN_PAREN)
929             SYNTAX_ERROR ("missing expression between '(' and ')'");
930
931           if (op.op == CPP_EOF && top->op == CPP_EOF)
932             SYNTAX_ERROR2 ("%s with no expression", is_if ? "#if" : "#elif");
933
934           if (top->op != CPP_EOF && top->op != CPP_OPEN_PAREN)
935             SYNTAX_ERROR2 ("operator '%s' has no right operand",
936                            cpp_token_as_text (pfile, top->token));
937           else if (op.op == CPP_CLOSE_PAREN || op.op == CPP_EOF)
938             /* Complain about missing paren during reduction.  */;
939           else
940             SYNTAX_ERROR2 ("operator '%s' has no left operand",
941                            cpp_token_as_text (pfile, op.token));
942         }
943
944       top = reduce (pfile, top, op.op);
945       if (!top)
946         goto syntax_error;
947
948       if (op.op == CPP_EOF)
949         break;
950
951       switch (op.op)
952         {
953         case CPP_CLOSE_PAREN:
954           continue;
955         case CPP_OR_OR:
956           if (!num_zerop (top->value))
957             pfile->state.skip_eval++;
958           break;
959         case CPP_AND_AND:
960         case CPP_QUERY:
961           if (num_zerop (top->value))
962             pfile->state.skip_eval++;
963           break;
964         case CPP_COLON:
965           if (top->op != CPP_QUERY)
966             SYNTAX_ERROR (" ':' without preceding '?'");
967           if (!num_zerop (top[-1].value)) /* Was '?' condition true?  */
968             pfile->state.skip_eval++;
969           else
970             pfile->state.skip_eval--;
971         default:
972           break;
973         }
974
975       want_value = true;
976
977       /* Check for and handle stack overflow.  */
978       if (++top == pfile->op_limit)
979         top = _cpp_expand_op_stack (pfile);
980
981       top->op = op.op;
982       top->token = op.token;
983       top->loc = op.token->src_loc;
984     }
985
986   /* The controlling macro expression is only valid if we called lex 3
987      times: <!> <defined expression> and <EOF>.  push_conditional ()
988      checks that we are at top-of-file.  */
989   if (pfile->mi_ind_cmacro && !(saw_leading_not && lex_count == 3))
990     pfile->mi_ind_cmacro = 0;
991
992   if (top != pfile->op_stack)
993     {
994       cpp_error (pfile, CPP_DL_ICE, "unbalanced stack in %s",
995                  is_if ? "#if" : "#elif");
996     syntax_error:
997       return false;  /* Return false on syntax error.  */
998     }
999
1000   return !num_zerop (top->value);
1001 }
1002
1003 /* Reduce the operator / value stack if possible, in preparation for
1004    pushing operator OP.  Returns NULL on error, otherwise the top of
1005    the stack.  */
1006 static struct op *
1007 reduce (cpp_reader *pfile, struct op *top, enum cpp_ttype op)
1008 {
1009   unsigned int prio;
1010
1011   if (top->op <= CPP_EQ || top->op > CPP_LAST_CPP_OP + 2)
1012     {
1013     bad_op:
1014       cpp_error (pfile, CPP_DL_ICE, "impossible operator '%u'", top->op);
1015       return 0;
1016     }
1017
1018   if (op == CPP_OPEN_PAREN)
1019     return top;
1020
1021   /* Decrement the priority of left-associative operators to force a
1022      reduction with operators of otherwise equal priority.  */
1023   prio = optab[op].prio - ((optab[op].flags & LEFT_ASSOC) != 0);
1024   while (prio < optab[top->op].prio)
1025     {
1026       if (CPP_OPTION (pfile, warn_num_sign_change)
1027           && optab[top->op].flags & CHECK_PROMOTION)
1028         check_promotion (pfile, top);
1029
1030       switch (top->op)
1031         {
1032         case CPP_UPLUS:
1033         case CPP_UMINUS:
1034         case CPP_NOT:
1035         case CPP_COMPL:
1036           top[-1].value = num_unary_op (pfile, top->value, top->op);
1037           top[-1].loc = top->loc;
1038           break;
1039
1040         case CPP_PLUS:
1041         case CPP_MINUS:
1042         case CPP_RSHIFT:
1043         case CPP_LSHIFT:
1044         case CPP_COMMA:
1045           top[-1].value = num_binary_op (pfile, top[-1].value,
1046                                          top->value, top->op);
1047           top[-1].loc = top->loc;
1048           break;
1049
1050         case CPP_GREATER:
1051         case CPP_LESS:
1052         case CPP_GREATER_EQ:
1053         case CPP_LESS_EQ:
1054           top[-1].value
1055             = num_inequality_op (pfile, top[-1].value, top->value, top->op);
1056           top[-1].loc = top->loc;
1057           break;
1058
1059         case CPP_EQ_EQ:
1060         case CPP_NOT_EQ:
1061           top[-1].value
1062             = num_equality_op (pfile, top[-1].value, top->value, top->op);
1063           top[-1].loc = top->loc;
1064           break;
1065
1066         case CPP_AND:
1067         case CPP_OR:
1068         case CPP_XOR:
1069           top[-1].value
1070             = num_bitwise_op (pfile, top[-1].value, top->value, top->op);
1071           top[-1].loc = top->loc;
1072           break;
1073
1074         case CPP_MULT:
1075           top[-1].value = num_mul (pfile, top[-1].value, top->value);
1076           top[-1].loc = top->loc;
1077           break;
1078
1079         case CPP_DIV:
1080         case CPP_MOD:
1081           top[-1].value = num_div_op (pfile, top[-1].value,
1082                                       top->value, top->op);
1083           top[-1].loc = top->loc;
1084           break;
1085
1086         case CPP_OR_OR:
1087           top--;
1088           if (!num_zerop (top->value))
1089             pfile->state.skip_eval--;
1090           top->value.low = (!num_zerop (top->value)
1091                             || !num_zerop (top[1].value));
1092           top->value.high = 0;
1093           top->value.unsignedp = false;
1094           top->value.overflow = false;
1095           top->loc = top[1].loc;
1096           continue;
1097
1098         case CPP_AND_AND:
1099           top--;
1100           if (num_zerop (top->value))
1101             pfile->state.skip_eval--;
1102           top->value.low = (!num_zerop (top->value)
1103                             && !num_zerop (top[1].value));
1104           top->value.high = 0;
1105           top->value.unsignedp = false;
1106           top->value.overflow = false;
1107           top->loc = top[1].loc;
1108           continue;
1109
1110         case CPP_OPEN_PAREN:
1111           if (op != CPP_CLOSE_PAREN)
1112             {
1113               cpp_error_with_line (pfile, CPP_DL_ERROR, 
1114                                    top->token->src_loc,
1115                                    0, "missing ')' in expression");
1116               return 0;
1117             }
1118           top--;
1119           top->value = top[1].value;
1120           top->loc = top[1].loc;
1121           return top;
1122
1123         case CPP_COLON:
1124           top -= 2;
1125           if (!num_zerop (top->value))
1126             {
1127               pfile->state.skip_eval--;
1128               top->value = top[1].value;
1129               top->loc = top[1].loc;
1130             }
1131           else
1132             {
1133               top->value = top[2].value;
1134               top->loc = top[2].loc;
1135             }
1136           top->value.unsignedp = (top[1].value.unsignedp
1137                                   || top[2].value.unsignedp);
1138           continue;
1139
1140         case CPP_QUERY:
1141           /* COMMA and COLON should not reduce a QUERY operator.  */
1142           if (op == CPP_COMMA || op == CPP_COLON)
1143             return top;
1144           cpp_error (pfile, CPP_DL_ERROR, "'?' without following ':'");
1145           return 0;
1146
1147         default:
1148           goto bad_op;
1149         }
1150
1151       top--;
1152       if (top->value.overflow && !pfile->state.skip_eval)
1153         cpp_error (pfile, CPP_DL_PEDWARN,
1154                    "integer overflow in preprocessor expression");
1155     }
1156
1157   if (op == CPP_CLOSE_PAREN)
1158     {
1159       cpp_error (pfile, CPP_DL_ERROR, "missing '(' in expression");
1160       return 0;
1161     }
1162
1163   return top;
1164 }
1165
1166 /* Returns the position of the old top of stack after expansion.  */
1167 struct op *
1168 _cpp_expand_op_stack (cpp_reader *pfile)
1169 {
1170   size_t old_size = (size_t) (pfile->op_limit - pfile->op_stack);
1171   size_t new_size = old_size * 2 + 20;
1172
1173   pfile->op_stack = XRESIZEVEC (struct op, pfile->op_stack, new_size);
1174   pfile->op_limit = pfile->op_stack + new_size;
1175
1176   return pfile->op_stack + old_size;
1177 }
1178
1179 /* Emits a warning if the effective sign of either operand of OP
1180    changes because of integer promotions.  */
1181 static void
1182 check_promotion (cpp_reader *pfile, const struct op *op)
1183 {
1184   if (op->value.unsignedp == op[-1].value.unsignedp)
1185     return;
1186
1187   if (op->value.unsignedp)
1188     {
1189       if (!num_positive (op[-1].value, CPP_OPTION (pfile, precision)))
1190         cpp_error_with_line (pfile, CPP_DL_WARNING, op[-1].loc, 0,
1191                              "the left operand of \"%s\" changes sign when promoted",
1192                              cpp_token_as_text (pfile, op->token));
1193     }
1194   else if (!num_positive (op->value, CPP_OPTION (pfile, precision)))
1195     cpp_error_with_line (pfile, CPP_DL_WARNING, op->loc, 0,
1196                "the right operand of \"%s\" changes sign when promoted",
1197                cpp_token_as_text (pfile, op->token));
1198 }
1199
1200 /* Clears the unused high order bits of the number pointed to by PNUM.  */
1201 static cpp_num
1202 num_trim (cpp_num num, size_t precision)
1203 {
1204   if (precision > PART_PRECISION)
1205     {
1206       precision -= PART_PRECISION;
1207       if (precision < PART_PRECISION)
1208         num.high &= ((cpp_num_part) 1 << precision) - 1;
1209     }
1210   else
1211     {
1212       if (precision < PART_PRECISION)
1213         num.low &= ((cpp_num_part) 1 << precision) - 1;
1214       num.high = 0;
1215     }
1216
1217   return num;
1218 }
1219
1220 /* True iff A (presumed signed) >= 0.  */
1221 static bool
1222 num_positive (cpp_num num, size_t precision)
1223 {
1224   if (precision > PART_PRECISION)
1225     {
1226       precision -= PART_PRECISION;
1227       return (num.high & (cpp_num_part) 1 << (precision - 1)) == 0;
1228     }
1229
1230   return (num.low & (cpp_num_part) 1 << (precision - 1)) == 0;
1231 }
1232
1233 /* Sign extend a number, with PRECISION significant bits and all
1234    others assumed clear, to fill out a cpp_num structure.  */
1235 cpp_num
1236 cpp_num_sign_extend (cpp_num num, size_t precision)
1237 {
1238   if (!num.unsignedp)
1239     {
1240       if (precision > PART_PRECISION)
1241         {
1242           precision -= PART_PRECISION;
1243           if (precision < PART_PRECISION
1244               && (num.high & (cpp_num_part) 1 << (precision - 1)))
1245             num.high |= ~(~(cpp_num_part) 0 >> (PART_PRECISION - precision));
1246         }
1247       else if (num.low & (cpp_num_part) 1 << (precision - 1))
1248         {
1249           if (precision < PART_PRECISION)
1250             num.low |= ~(~(cpp_num_part) 0 >> (PART_PRECISION - precision));
1251           num.high = ~(cpp_num_part) 0;
1252         }
1253     }
1254
1255   return num;
1256 }
1257
1258 /* Returns the negative of NUM.  */
1259 static cpp_num
1260 num_negate (cpp_num num, size_t precision)
1261 {
1262   cpp_num copy;
1263
1264   copy = num;
1265   num.high = ~num.high;
1266   num.low = ~num.low;
1267   if (++num.low == 0)
1268     num.high++;
1269   num = num_trim (num, precision);
1270   num.overflow = (!num.unsignedp && num_eq (num, copy) && !num_zerop (num));
1271
1272   return num;
1273 }
1274
1275 /* Returns true if A >= B.  */
1276 static bool
1277 num_greater_eq (cpp_num pa, cpp_num pb, size_t precision)
1278 {
1279   bool unsignedp;
1280
1281   unsignedp = pa.unsignedp || pb.unsignedp;
1282
1283   if (!unsignedp)
1284     {
1285       /* Both numbers have signed type.  If they are of different
1286        sign, the answer is the sign of A.  */
1287       unsignedp = num_positive (pa, precision);
1288
1289       if (unsignedp != num_positive (pb, precision))
1290         return unsignedp;
1291
1292       /* Otherwise we can do an unsigned comparison.  */
1293     }
1294
1295   return (pa.high > pb.high) || (pa.high == pb.high && pa.low >= pb.low);
1296 }
1297
1298 /* Returns LHS OP RHS, where OP is a bit-wise operation.  */
1299 static cpp_num
1300 num_bitwise_op (cpp_reader *pfile ATTRIBUTE_UNUSED,
1301                 cpp_num lhs, cpp_num rhs, enum cpp_ttype op)
1302 {
1303   lhs.overflow = false;
1304   lhs.unsignedp = lhs.unsignedp || rhs.unsignedp;
1305
1306   /* As excess precision is zeroed, there is no need to num_trim () as
1307      these operations cannot introduce a set bit there.  */
1308   if (op == CPP_AND)
1309     {
1310       lhs.low &= rhs.low;
1311       lhs.high &= rhs.high;
1312     }
1313   else if (op == CPP_OR)
1314     {
1315       lhs.low |= rhs.low;
1316       lhs.high |= rhs.high;
1317     }
1318   else
1319     {
1320       lhs.low ^= rhs.low;
1321       lhs.high ^= rhs.high;
1322     }
1323
1324   return lhs;
1325 }
1326
1327 /* Returns LHS OP RHS, where OP is an inequality.  */
1328 static cpp_num
1329 num_inequality_op (cpp_reader *pfile, cpp_num lhs, cpp_num rhs,
1330                    enum cpp_ttype op)
1331 {
1332   bool gte = num_greater_eq (lhs, rhs, CPP_OPTION (pfile, precision));
1333
1334   if (op == CPP_GREATER_EQ)
1335     lhs.low = gte;
1336   else if (op == CPP_LESS)
1337     lhs.low = !gte;
1338   else if (op == CPP_GREATER)
1339     lhs.low = gte && !num_eq (lhs, rhs);
1340   else /* CPP_LESS_EQ.  */
1341     lhs.low = !gte || num_eq (lhs, rhs);
1342
1343   lhs.high = 0;
1344   lhs.overflow = false;
1345   lhs.unsignedp = false;
1346   return lhs;
1347 }
1348
1349 /* Returns LHS OP RHS, where OP is == or !=.  */
1350 static cpp_num
1351 num_equality_op (cpp_reader *pfile ATTRIBUTE_UNUSED,
1352                  cpp_num lhs, cpp_num rhs, enum cpp_ttype op)
1353 {
1354   /* Work around a 3.0.4 bug; see PR 6950.  */
1355   bool eq = num_eq (lhs, rhs);
1356   if (op == CPP_NOT_EQ)
1357     eq = !eq;
1358   lhs.low = eq;
1359   lhs.high = 0;
1360   lhs.overflow = false;
1361   lhs.unsignedp = false;
1362   return lhs;
1363 }
1364
1365 /* Shift NUM, of width PRECISION, right by N bits.  */
1366 static cpp_num
1367 num_rshift (cpp_num num, size_t precision, size_t n)
1368 {
1369   cpp_num_part sign_mask;
1370   bool x = num_positive (num, precision);
1371
1372   if (num.unsignedp || x)
1373     sign_mask = 0;
1374   else
1375     sign_mask = ~(cpp_num_part) 0;
1376
1377   if (n >= precision)
1378     num.high = num.low = sign_mask;
1379   else
1380     {
1381       /* Sign-extend.  */
1382       if (precision < PART_PRECISION)
1383         num.high = sign_mask, num.low |= sign_mask << precision;
1384       else if (precision < 2 * PART_PRECISION)
1385         num.high |= sign_mask << (precision - PART_PRECISION);
1386
1387       if (n >= PART_PRECISION)
1388         {
1389           n -= PART_PRECISION;
1390           num.low = num.high;
1391           num.high = sign_mask;
1392         }
1393
1394       if (n)
1395         {
1396           num.low = (num.low >> n) | (num.high << (PART_PRECISION - n));
1397           num.high = (num.high >> n) | (sign_mask << (PART_PRECISION - n));
1398         }
1399     }
1400
1401   num = num_trim (num, precision);
1402   num.overflow = false;
1403   return num;
1404 }
1405
1406 /* Shift NUM, of width PRECISION, left by N bits.  */
1407 static cpp_num
1408 num_lshift (cpp_num num, size_t precision, size_t n)
1409 {
1410   if (n >= precision)
1411     {
1412       num.overflow = !num.unsignedp && !num_zerop (num);
1413       num.high = num.low = 0;
1414     }
1415   else
1416     {
1417       cpp_num orig, maybe_orig;
1418       size_t m = n;
1419
1420       orig = num;
1421       if (m >= PART_PRECISION)
1422         {
1423           m -= PART_PRECISION;
1424           num.high = num.low;
1425           num.low = 0;
1426         }
1427       if (m)
1428         {
1429           num.high = (num.high << m) | (num.low >> (PART_PRECISION - m));
1430           num.low <<= m;
1431         }
1432       num = num_trim (num, precision);
1433
1434       if (num.unsignedp)
1435         num.overflow = false;
1436       else
1437         {
1438           maybe_orig = num_rshift (num, precision, n);
1439           num.overflow = !num_eq (orig, maybe_orig);
1440         }
1441     }
1442
1443   return num;
1444 }
1445
1446 /* The four unary operators: +, -, ! and ~.  */
1447 static cpp_num
1448 num_unary_op (cpp_reader *pfile, cpp_num num, enum cpp_ttype op)
1449 {
1450   switch (op)
1451     {
1452     case CPP_UPLUS:
1453       if (CPP_WTRADITIONAL (pfile) && !pfile->state.skip_eval)
1454         cpp_error (pfile, CPP_DL_WARNING,
1455                    "traditional C rejects the unary plus operator");
1456       num.overflow = false;
1457       break;
1458
1459     case CPP_UMINUS:
1460       num = num_negate (num, CPP_OPTION (pfile, precision));
1461       break;
1462
1463     case CPP_COMPL:
1464       num.high = ~num.high;
1465       num.low = ~num.low;
1466       num = num_trim (num, CPP_OPTION (pfile, precision));
1467       num.overflow = false;
1468       break;
1469
1470     default: /* case CPP_NOT: */
1471       num.low = num_zerop (num);
1472       num.high = 0;
1473       num.overflow = false;
1474       num.unsignedp = false;
1475       break;
1476     }
1477
1478   return num;
1479 }
1480
1481 /* The various binary operators.  */
1482 static cpp_num
1483 num_binary_op (cpp_reader *pfile, cpp_num lhs, cpp_num rhs, enum cpp_ttype op)
1484 {
1485   cpp_num result;
1486   size_t precision = CPP_OPTION (pfile, precision);
1487   size_t n;
1488
1489   switch (op)
1490     {
1491       /* Shifts.  */
1492     case CPP_LSHIFT:
1493     case CPP_RSHIFT:
1494       if (!rhs.unsignedp && !num_positive (rhs, precision))
1495         {
1496           /* A negative shift is a positive shift the other way.  */
1497           if (op == CPP_LSHIFT)
1498             op = CPP_RSHIFT;
1499           else
1500             op = CPP_LSHIFT;
1501           rhs = num_negate (rhs, precision);
1502         }
1503       if (rhs.high)
1504         n = ~0;                 /* Maximal.  */
1505       else
1506         n = rhs.low;
1507       if (op == CPP_LSHIFT)
1508         lhs = num_lshift (lhs, precision, n);
1509       else
1510         lhs = num_rshift (lhs, precision, n);
1511       break;
1512
1513       /* Arithmetic.  */
1514     case CPP_MINUS:
1515       rhs = num_negate (rhs, precision);
1516     case CPP_PLUS:
1517       result.low = lhs.low + rhs.low;
1518       result.high = lhs.high + rhs.high;
1519       if (result.low < lhs.low)
1520         result.high++;
1521       result.unsignedp = lhs.unsignedp || rhs.unsignedp;
1522       result.overflow = false;
1523
1524       result = num_trim (result, precision);
1525       if (!result.unsignedp)
1526         {
1527           bool lhsp = num_positive (lhs, precision);
1528           result.overflow = (lhsp == num_positive (rhs, precision)
1529                              && lhsp != num_positive (result, precision));
1530         }
1531       return result;
1532
1533       /* Comma.  */
1534     default: /* case CPP_COMMA: */
1535       if (CPP_PEDANTIC (pfile) && (!CPP_OPTION (pfile, c99)
1536                                    || !pfile->state.skip_eval))
1537         cpp_error (pfile, CPP_DL_PEDWARN,
1538                    "comma operator in operand of #if");
1539       lhs = rhs;
1540       break;
1541     }
1542
1543   return lhs;
1544 }
1545
1546 /* Multiplies two unsigned cpp_num_parts to give a cpp_num.  This
1547    cannot overflow.  */
1548 static cpp_num
1549 num_part_mul (cpp_num_part lhs, cpp_num_part rhs)
1550 {
1551   cpp_num result;
1552   cpp_num_part middle[2], temp;
1553
1554   result.low = LOW_PART (lhs) * LOW_PART (rhs);
1555   result.high = HIGH_PART (lhs) * HIGH_PART (rhs);
1556
1557   middle[0] = LOW_PART (lhs) * HIGH_PART (rhs);
1558   middle[1] = HIGH_PART (lhs) * LOW_PART (rhs);
1559
1560   temp = result.low;
1561   result.low += LOW_PART (middle[0]) << (PART_PRECISION / 2);
1562   if (result.low < temp)
1563     result.high++;
1564
1565   temp = result.low;
1566   result.low += LOW_PART (middle[1]) << (PART_PRECISION / 2);
1567   if (result.low < temp)
1568     result.high++;
1569
1570   result.high += HIGH_PART (middle[0]);
1571   result.high += HIGH_PART (middle[1]);
1572   result.unsignedp = true;
1573   result.overflow = false;
1574
1575   return result;
1576 }
1577
1578 /* Multiply two preprocessing numbers.  */
1579 static cpp_num
1580 num_mul (cpp_reader *pfile, cpp_num lhs, cpp_num rhs)
1581 {
1582   cpp_num result, temp;
1583   bool unsignedp = lhs.unsignedp || rhs.unsignedp;
1584   bool overflow, negate = false;
1585   size_t precision = CPP_OPTION (pfile, precision);
1586
1587   /* Prepare for unsigned multiplication.  */
1588   if (!unsignedp)
1589     {
1590       if (!num_positive (lhs, precision))
1591         negate = !negate, lhs = num_negate (lhs, precision);
1592       if (!num_positive (rhs, precision))
1593         negate = !negate, rhs = num_negate (rhs, precision);
1594     }
1595
1596   overflow = lhs.high && rhs.high;
1597   result = num_part_mul (lhs.low, rhs.low);
1598
1599   temp = num_part_mul (lhs.high, rhs.low);
1600   result.high += temp.low;
1601   if (temp.high)
1602     overflow = true;
1603
1604   temp = num_part_mul (lhs.low, rhs.high);
1605   result.high += temp.low;
1606   if (temp.high)
1607     overflow = true;
1608
1609   temp.low = result.low, temp.high = result.high;
1610   result = num_trim (result, precision);
1611   if (!num_eq (result, temp))
1612     overflow = true;
1613
1614   if (negate)
1615     result = num_negate (result, precision);
1616
1617   if (unsignedp)
1618     result.overflow = false;
1619   else
1620     result.overflow = overflow || (num_positive (result, precision) ^ !negate
1621                                    && !num_zerop (result));
1622   result.unsignedp = unsignedp;
1623
1624   return result;
1625 }
1626
1627 /* Divide two preprocessing numbers, returning the answer or the
1628    remainder depending upon OP.  */
1629 static cpp_num
1630 num_div_op (cpp_reader *pfile, cpp_num lhs, cpp_num rhs, enum cpp_ttype op)
1631 {
1632   cpp_num result, sub;
1633   cpp_num_part mask;
1634   bool unsignedp = lhs.unsignedp || rhs.unsignedp;
1635   bool negate = false, lhs_neg = false;
1636   size_t i, precision = CPP_OPTION (pfile, precision);
1637
1638   /* Prepare for unsigned division.  */
1639   if (!unsignedp)
1640     {
1641       if (!num_positive (lhs, precision))
1642         negate = !negate, lhs_neg = true, lhs = num_negate (lhs, precision);
1643       if (!num_positive (rhs, precision))
1644         negate = !negate, rhs = num_negate (rhs, precision);
1645     }
1646
1647   /* Find the high bit.  */
1648   if (rhs.high)
1649     {
1650       i = precision - 1;
1651       mask = (cpp_num_part) 1 << (i - PART_PRECISION);
1652       for (; ; i--, mask >>= 1)
1653         if (rhs.high & mask)
1654           break;
1655     }
1656   else if (rhs.low)
1657     {
1658       if (precision > PART_PRECISION)
1659         i = precision - PART_PRECISION - 1;
1660       else
1661         i = precision - 1;
1662       mask = (cpp_num_part) 1 << i;
1663       for (; ; i--, mask >>= 1)
1664         if (rhs.low & mask)
1665           break;
1666     }
1667   else
1668     {
1669       if (!pfile->state.skip_eval)
1670         cpp_error (pfile, CPP_DL_ERROR, "division by zero in #if");
1671       return lhs;
1672     }
1673
1674   /* First nonzero bit of RHS is bit I.  Do naive division by
1675      shifting the RHS fully left, and subtracting from LHS if LHS is
1676      at least as big, and then repeating but with one less shift.
1677      This is not very efficient, but is easy to understand.  */
1678
1679   rhs.unsignedp = true;
1680   lhs.unsignedp = true;
1681   i = precision - i - 1;
1682   sub = num_lshift (rhs, precision, i);
1683
1684   result.high = result.low = 0;
1685   for (;;)
1686     {
1687       if (num_greater_eq (lhs, sub, precision))
1688         {
1689           lhs = num_binary_op (pfile, lhs, sub, CPP_MINUS);
1690           if (i >= PART_PRECISION)
1691             result.high |= (cpp_num_part) 1 << (i - PART_PRECISION);
1692           else
1693             result.low |= (cpp_num_part) 1 << i;
1694         }
1695       if (i-- == 0)
1696         break;
1697       sub.low = (sub.low >> 1) | (sub.high << (PART_PRECISION - 1));
1698       sub.high >>= 1;
1699     }
1700
1701   /* We divide so that the remainder has the sign of the LHS.  */
1702   if (op == CPP_DIV)
1703     {
1704       result.unsignedp = unsignedp;
1705       result.overflow = false;
1706       if (!unsignedp)
1707         {
1708           if (negate)
1709             result = num_negate (result, precision);
1710           result.overflow = (num_positive (result, precision) ^ !negate
1711                              && !num_zerop (result));
1712         }
1713
1714       return result;
1715     }
1716
1717   /* CPP_MOD.  */
1718   lhs.unsignedp = unsignedp;
1719   lhs.overflow = false;
1720   if (lhs_neg)
1721     lhs = num_negate (lhs, precision);
1722
1723   return lhs;
1724 }