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