]> git.sur5r.net Git - cc65/blob - src/cc65/expr.c
dc05dcfee5d9ebe610db8dd0cce0710565cd5613
[cc65] / src / cc65 / expr.c
1 /*
2  * expr.c
3  *
4  * Ullrich von Bassewitz, 21.06.1998
5  */
6
7
8
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12
13 /* common */
14 #include "check.h"
15 #include "xmalloc.h"
16
17 /* cc65 */
18 #include "asmcode.h"
19 #include "asmlabel.h"
20 #include "codegen.h"
21 #include "datatype.h"
22 #include "declare.h"
23 #include "error.h"
24 #include "funcdesc.h"
25 #include "function.h"
26 #include "global.h"
27 #include "litpool.h"
28 #include "macrotab.h"
29 #include "preproc.h"
30 #include "scanner.h"
31 #include "stdfunc.h"
32 #include "symtab.h"
33 #include "typecmp.h"
34 #include "expr.h"
35
36
37
38 /*****************************************************************************/
39 /*                                   Data                                    */
40 /*****************************************************************************/
41
42
43
44 /* Generator attributes */
45 #define GEN_NOPUSH      0x01            /* Don't push lhs */
46
47 /* Map a generator function and its attributes to a token */
48 typedef struct {
49     unsigned char Tok;                  /* Token to map to */
50     unsigned char Flags;                /* Flags for generator function */
51     void          (*Func) (unsigned, unsigned long);    /* Generator func */
52 } GenDesc;
53
54 /* Descriptors for the operations */
55 static GenDesc GenMUL    = { TOK_STAR,          GEN_NOPUSH,     g_mul };
56 static GenDesc GenDIV    = { TOK_DIV,           GEN_NOPUSH,     g_div };
57 static GenDesc GenMOD    = { TOK_MOD,           GEN_NOPUSH,     g_mod };
58 static GenDesc GenASL    = { TOK_SHL,           GEN_NOPUSH,     g_asl };
59 static GenDesc GenASR    = { TOK_SHR,           GEN_NOPUSH,     g_asr };
60 static GenDesc GenLT     = { TOK_LT,            GEN_NOPUSH,     g_lt  };
61 static GenDesc GenLE     = { TOK_LE,            GEN_NOPUSH,     g_le  };
62 static GenDesc GenGE     = { TOK_GE,            GEN_NOPUSH,     g_ge  };
63 static GenDesc GenGT     = { TOK_GT,            GEN_NOPUSH,     g_gt  };
64 static GenDesc GenEQ     = { TOK_EQ,            GEN_NOPUSH,     g_eq  };
65 static GenDesc GenNE     = { TOK_NE,            GEN_NOPUSH,     g_ne  };
66 static GenDesc GenAND    = { TOK_AND,           GEN_NOPUSH,     g_and };
67 static GenDesc GenXOR    = { TOK_XOR,           GEN_NOPUSH,     g_xor };
68 static GenDesc GenOR     = { TOK_OR,            GEN_NOPUSH,     g_or  };
69 static GenDesc GenPASGN  = { TOK_PLUS_ASSIGN,   GEN_NOPUSH,     g_add };
70 static GenDesc GenSASGN  = { TOK_MINUS_ASSIGN,  GEN_NOPUSH,     g_sub };
71 static GenDesc GenMASGN  = { TOK_MUL_ASSIGN,    GEN_NOPUSH,     g_mul };
72 static GenDesc GenDASGN  = { TOK_DIV_ASSIGN,    GEN_NOPUSH,     g_div };
73 static GenDesc GenMOASGN = { TOK_MOD_ASSIGN,    GEN_NOPUSH,     g_mod };
74 static GenDesc GenSLASGN = { TOK_SHL_ASSIGN,    GEN_NOPUSH,     g_asl };
75 static GenDesc GenSRASGN = { TOK_SHR_ASSIGN,    GEN_NOPUSH,     g_asr };
76 static GenDesc GenAASGN  = { TOK_AND_ASSIGN,    GEN_NOPUSH,     g_and };
77 static GenDesc GenXOASGN = { TOK_XOR_ASSIGN,    GEN_NOPUSH,     g_xor };
78 static GenDesc GenOASGN  = { TOK_OR_ASSIGN,     GEN_NOPUSH,     g_or  };
79
80
81
82 /*****************************************************************************/
83 /*                             Function forwards                             */
84 /*****************************************************************************/
85
86
87
88 static int hie10 (struct expent* lval);
89 /* Handle ++, --, !, unary - etc. */
90
91
92
93 /*****************************************************************************/
94 /*                             Helper functions                              */
95 /*****************************************************************************/
96
97
98
99 static unsigned GlobalModeFlags (unsigned flags)
100 /* Return the addressing mode flags for the variable with the given flags */
101 {
102     flags &= E_MCTYPE;
103     if (flags == E_TGLAB) {
104         /* External linkage */
105         return CF_EXTERNAL;
106     } else if (flags == E_TREGISTER) {
107         /* Register variable */
108         return CF_REGVAR;
109     } else {
110         /* Static */
111         return CF_STATIC;
112     }
113 }
114
115
116
117 static int IsNullPtr (struct expent* lval)
118 /* Return true if this is the NULL pointer constant */
119 {
120     return (IsClassInt (lval->e_tptr) &&        /* Is it an int? */
121             lval->e_flags == E_MCONST &&        /* Is it constant? */
122             lval->e_const == 0);                /* And is it's value zero? */
123 }
124
125
126
127 static type* promoteint (type* lhst, type* rhst)
128 /* In an expression with two ints, return the type of the result */
129 {
130     /* Rules for integer types:
131      *   - If one of the values is a long, the result is long.
132      *   - If one of the values is unsigned, the result is also unsigned.
133      *   - Otherwise the result is an int.
134      */
135     if (IsTypeLong (lhst) || IsTypeLong (rhst)) {
136         if (IsSignUnsigned (lhst) || IsSignUnsigned (rhst)) {
137             return type_ulong;
138         } else {
139             return type_long;
140         }
141     } else {
142         if (IsSignUnsigned (lhst) || IsSignUnsigned (rhst)) {
143             return type_uint;
144         } else {
145             return type_int;
146         }
147     }
148 }
149
150
151
152 static unsigned typeadjust (struct expent* lhs, struct expent* rhs, int NoPush)
153 /* Adjust the two values for a binary operation. lhs is expected on stack or
154  * to be constant, rhs is expected to be in the primary register or constant.
155  * The function will put the type of the result into lhs and return the
156  * code generator flags for the operation.
157  * If NoPush is given, it is assumed that the operation does not expect the lhs
158  * to be on stack, and that lhs is in a register instead.
159  * Beware: The function does only accept int types.
160  */
161 {
162     unsigned ltype, rtype;
163     unsigned flags;
164
165     /* Get the type strings */
166     type* lhst = lhs->e_tptr;
167     type* rhst = rhs->e_tptr;
168
169     /* Generate type adjustment code if needed */
170     ltype = TypeOf (lhst);
171     if (lhs->e_flags == E_MCONST) {
172         ltype |= CF_CONST;
173     }
174     if (NoPush) {
175         /* Value is in primary register*/
176         ltype |= CF_REG;
177     }
178     rtype = TypeOf (rhst);
179     if (rhs->e_flags == E_MCONST) {
180         rtype |= CF_CONST;
181     }
182     flags = g_typeadjust (ltype, rtype);
183
184     /* Set the type of the result */
185     lhs->e_tptr = promoteint (lhst, rhst);
186
187     /* Return the code generator flags */
188     return flags;
189 }
190
191
192
193 unsigned assignadjust (type* lhst, struct expent* rhs)
194 /* Adjust the type of the right hand expression so that it can be assigned to
195  * the type on the left hand side. This function is used for assignment and
196  * for converting parameters in a function call. It returns the code generator
197  * flags for the operation. The type string of the right hand side will be
198  * set to the type of the left hand side.
199  */
200 {
201     /* Get the type of the right hand side. Treat function types as
202      * pointer-to-function
203      */
204     type* rhst = rhs->e_tptr;
205     if (IsTypeFunc (rhst)) {
206         rhst = PointerTo (rhst);
207     }
208
209     /* After calling this function, rhs will have the type of the lhs */
210     rhs->e_tptr = lhst;
211
212     /* First, do some type checking */
213     if (IsTypeVoid (lhst) || IsTypeVoid (rhst)) {
214         /* If one of the sides are of type void, output a more apropriate
215          * error message.
216          */
217         Error ("Illegal type");
218     } else if (IsClassInt (lhst)) {
219         if (IsClassPtr (rhst)) {
220             /* Pointer -> int conversion */
221             Warning ("Converting pointer to integer without a cast");
222         } else if (!IsClassInt (rhst)) {
223             Error ("Incompatible types");
224         } else {
225             /* Adjust the int types. To avoid manipulation of TOS mark lhs
226              * as const.
227              */
228             unsigned flags = TypeOf (rhst);
229             if (rhs->e_flags & E_MCONST) {
230                 flags |= CF_CONST;
231             }
232             return g_typeadjust (TypeOf (lhst) | CF_CONST, flags);
233         }
234     } else if (IsClassPtr (lhst)) {
235         if (IsClassPtr (rhst)) {
236             /* Pointer to pointer assignment is valid, if:
237              *   - both point to the same types, or
238              *   - the rhs pointer is a void pointer, or
239              *   - the lhs pointer is a void pointer.
240              */
241             if (!IsTypeVoid (Indirect (lhst)) && !IsTypeVoid (Indirect (rhst))) {
242                 /* Compare the types */
243                 switch (TypeCmp (lhst, rhst)) {
244
245                     case TC_INCOMPATIBLE:
246                         Error ("Incompatible pointer types");
247                         break;
248
249                     case TC_QUAL_DIFF:
250                         Error ("Pointer types differ in type qualifiers");
251                         break;
252
253                     default:
254                         /* Ok */
255                         break;
256                 }
257             }
258         } else if (IsClassInt (rhst)) {
259             /* Int to pointer assignment is valid only for constant zero */
260             if ((rhs->e_flags & E_MCONST) == 0 || rhs->e_const != 0) {
261                 Warning ("Converting integer to pointer without a cast");
262             }
263         } else if (IsTypeFuncPtr (lhst) && IsTypeFunc(rhst)) {
264             /* Assignment of function to function pointer is allowed, provided
265              * that both functions have the same parameter list.
266              */
267             if (TypeCmp (Indirect (lhst), rhst) < TC_EQUAL) {
268                 Error ("Incompatible types");
269             }
270         } else {
271             Error ("Incompatible types");
272         }
273     } else {
274         Error ("Incompatible types");
275     }
276
277     /* Return an int value in all cases where the operands are not both ints */
278     return CF_INT;
279 }
280
281
282
283 void DefineData (struct expent* lval)
284 /* Output a data definition for the given expression */
285 {
286     unsigned flags = lval->e_flags;
287
288     switch (flags & E_MCTYPE) {
289
290         case E_TCONST:
291             /* Number */
292             g_defdata (TypeOf (lval->e_tptr) | CF_CONST, lval->e_const, 0);
293             break;
294
295         case E_TREGISTER:
296             /* Register variable. Taking the address is usually not
297              * allowed.
298              */
299             if (!AllowRegVarAddr) {
300                 Error ("Cannot take the address of a register variable");
301             }
302             /* FALLTHROUGH */
303
304         case E_TGLAB:
305         case E_TLLAB:
306             /* Local or global symbol */
307             g_defdata (GlobalModeFlags (flags), lval->e_name, lval->e_const);
308             break;
309
310         case E_TLIT:
311             /* a literal of some kind */
312             g_defdata (CF_STATIC, LiteralLabel, lval->e_const);
313             break;
314
315         default:
316             Internal ("Unknown constant type: %04X", flags);
317     }
318 }
319
320
321
322 static void lconst (unsigned flags, struct expent* lval)
323 /* Load primary reg with some constant value. */
324 {
325     switch (lval->e_flags & E_MCTYPE) {
326
327         case E_TLOFFS:
328             g_leasp (lval->e_const);
329             break;
330
331         case E_TCONST:
332             /* Number constant */
333             g_getimmed (flags | TypeOf (lval->e_tptr) | CF_CONST, lval->e_const, 0);
334             break;
335
336         case E_TREGISTER:
337             /* Register variable. Taking the address is usually not
338              * allowed.
339              */
340             if (!AllowRegVarAddr) {
341                 Error ("Cannot take the address of a register variable");
342             }
343             /* FALLTHROUGH */
344
345         case E_TGLAB:
346         case E_TLLAB:
347             /* Local or global symbol, load address */
348             flags |= GlobalModeFlags (lval->e_flags);
349             flags &= ~CF_CONST;
350             g_getimmed (flags, lval->e_name, lval->e_const);
351             break;
352
353         case E_TLIT:
354             /* Literal string */
355             g_getimmed (CF_STATIC, LiteralLabel, lval->e_const);
356             break;
357
358         default:
359             Internal ("Unknown constant type: %04X", lval->e_flags);
360     }
361 }
362
363
364
365 static int kcalc (int tok, long val1, long val2)
366 /* Calculate an operation with left and right operand constant. */
367 {
368     switch (tok) {
369         case TOK_EQ:
370             return (val1 == val2);
371         case TOK_NE:
372             return (val1 != val2);
373         case TOK_LT:
374             return (val1 < val2);
375         case TOK_LE:
376             return (val1 <= val2);
377         case TOK_GE:
378             return (val1 >= val2);
379         case TOK_GT:
380             return (val1 > val2);
381         case TOK_OR:
382             return (val1 | val2);
383         case TOK_XOR:
384             return (val1 ^ val2);
385         case TOK_AND:
386             return (val1 & val2);
387         case TOK_SHR:
388             return (val1 >> val2);
389         case TOK_SHL:
390             return (val1 << val2);
391         case TOK_STAR:
392             return (val1 * val2);
393         case TOK_DIV:
394             if (val2 == 0) {
395                 Error ("Division by zero");
396                 return 0x7FFFFFFF;
397             }
398             return (val1 / val2);
399         case TOK_MOD:
400             if (val2 == 0) {
401                 Error ("Modulo operation with zero");
402                 return 0;
403             }
404             return (val1 % val2);
405         default:
406             Internal ("kcalc: got token 0x%X\n", tok);
407             return 0;
408     }
409 }
410
411
412
413 static GenDesc* FindGen (int Tok, GenDesc** Table)
414 {
415     GenDesc* G;
416     while ((G = *Table) != 0) {
417         if (G->Tok == Tok) {
418             return G;
419         }
420         ++Table;
421     }
422     return 0;
423 }
424
425
426
427 static int istypeexpr (void)
428 /* Return true if some sort of variable or type is waiting (helper for cast
429  * and sizeof() in hie10).
430  */
431 {
432     SymEntry* Entry;
433
434     return curtok == TOK_LPAREN && (
435             (nxttok >= TOK_FIRSTTYPE && nxttok <= TOK_LASTTYPE) ||
436             (nxttok == TOK_CONST)                               ||
437             (nxttok  == TOK_IDENT                               &&
438             (Entry = FindSym (NextTok.Ident)) != 0              &&
439             IsTypeDef (Entry))
440            );
441 }
442
443
444
445 static void PushAddr (struct expent* lval)
446 /* If the expression contains an address that was somehow evaluated,
447  * push this address on the stack. This is a helper function for all
448  * sorts of implicit or explicit assignment functions where the lvalue
449  * must be saved if it's not constant, before evaluating the rhs.
450  */
451 {
452     /* Get the address on stack if needed */
453     if (lval->e_flags != E_MREG && (lval->e_flags & E_MEXPR)) {
454         /* Push the address (always a pointer) */
455         g_push (CF_PTR, 0);
456     }
457 }
458
459
460
461 /*****************************************************************************/
462 /*                                   code                                    */
463 /*****************************************************************************/
464
465
466
467 void exprhs (unsigned flags, int k, struct expent *lval)
468 /* Put the result of an expression into the primary register */
469 {
470     int f;
471
472     f = lval->e_flags;
473     if (k) {
474         /* Dereferenced lvalue */
475         flags |= TypeOf (lval->e_tptr);
476         if (lval->e_test & E_FORCETEST) {
477             flags |= CF_TEST;
478             lval->e_test &= ~E_FORCETEST;
479         }
480         if (f & E_MGLOBAL) {    /* ref to globalvar */
481             /* Generate code */
482             flags |= GlobalModeFlags (f);
483             g_getstatic (flags, lval->e_name, lval->e_const);
484         } else if (f & E_MLOCAL) {
485             /* ref to localvar */
486             g_getlocal (flags, lval->e_const);
487         } else if (f & E_MCONST) {
488             /* ref to absolute address */
489             g_getstatic (flags | CF_ABSOLUTE, lval->e_const, 0);
490         } else if (f == E_MEOFFS) {
491             g_getind (flags, lval->e_const);
492         } else if (f != E_MREG) {
493             g_getind (flags, 0);
494         }
495     } else if (f == E_MEOFFS) {
496         /* reference not storable */
497         flags |= TypeOf (lval->e_tptr);
498         g_inc (flags | CF_CONST, lval->e_const);
499     } else if ((f & E_MEXPR) == 0) {
500         /* Constant of some sort, load it into the primary */
501         lconst (flags, lval);
502     }
503     if (lval->e_test & E_FORCETEST) {   /* we testing this value? */
504         /* debug... */
505         AddCodeHint ("forcetest");
506         flags |= TypeOf (lval->e_tptr);
507         g_test (flags);                 /* yes, force a test */
508         lval->e_test &= ~E_FORCETEST;
509     }
510 }
511
512
513 static void callfunction (struct expent* lval)
514 /* Perform a function call.  Called from hie11, this routine will
515  * either call the named function, or if the supplied ptr is zero,
516  * will call the contents of P.
517  */
518 {
519     struct expent lval2;
520     FuncDesc*     Func;         /* Function descriptor */
521     int           Ellipsis;     /* True if we have an open param list */
522     SymEntry*     Param;        /* Current formal parameter */
523     unsigned      ParamCount;   /* Actual parameter count */
524     unsigned      ParamSize;    /* Number of parameter bytes */
525     unsigned      Flags;
526     unsigned      CFlags;
527     CodeMark      Mark;
528
529
530     /* Get a pointer to the function descriptor from the type string */
531     Func = GetFuncDesc (lval->e_tptr);
532
533     /* Initialize vars to keep gcc silent */
534     Param = 0;
535     Mark  = 0;
536
537     /* Check if this is a function pointer. If so, save it. If not, check for
538      * special known library functions that may be inlined.
539      */
540     if (lval->e_flags & E_MEXPR) {
541         /* Function pointer is in primary register, save it */
542         Mark = GetCodePos ();
543         g_save (CF_PTR);
544     } else if (InlineStdFuncs && IsStdFunc ((const char*) lval->e_name)) {
545         /* Inline this function */
546         HandleStdFunc (lval);
547         return;
548     }
549
550     /* Parse the actual parameter list */
551     ParamSize  = 0;
552     ParamCount = 0;
553     Ellipsis   = 0;
554     while (curtok != TOK_RPAREN) {
555
556         /* Add a hint for the optimizer */
557         AddCodeHint ("param:start");
558
559         /* Count arguments */
560         ++ParamCount;
561
562         /* Fetch the pointer to the next argument, check for too many args */
563         if (ParamCount <= Func->ParamCount) {
564             /* Beware: If there are parameters with identical names, they
565              * cannot go into the same symbol table, which means that in this
566              * case of errorneous input, the number of nodes in the symbol
567              * table and ParamCount are NOT equal. We have to handle this case
568              * below to avoid segmentation violations. Since we know that this
569              * problem can only occur if there is more than one parameter,
570              * we will just use the last one.
571              */
572             if (ParamCount == 1) {
573                 /* First argument */
574                 Param = Func->SymTab->SymHead;
575             } else if (Param->NextSym != 0) {
576                 /* Next argument */
577                 Param = Param->NextSym;
578                 CHECK ((Param->Flags & SC_PARAM) != 0);
579             }
580         } else if (!Ellipsis) {
581             /* Too many arguments. Do we have an open param list? */
582             if ((Func->Flags & FD_ELLIPSIS) == 0) {
583                 /* End of param list reached, no ellipsis */
584                 Error ("Too many arguments in function call");
585             }
586             /* Assume an ellipsis even in case of errors to avoid an error
587              * message for each other argument.
588              */
589             Ellipsis = 1;
590         }
591
592         /* Do some optimization: If we have a constant value to push,
593          * use a special function that may optimize.
594          */
595         CFlags = CF_NONE;
596         if (!Ellipsis && SizeOf (Param->Type) == 1) {
597             CFlags = CF_FORCECHAR;
598         }
599         Flags = 0;
600         if (evalexpr (CFlags, hie1, &lval2) == 0) {
601             /* A constant value */
602             Flags |= CF_CONST;
603         }
604
605         /* If we don't have an argument spec, accept anything, otherwise
606          * convert the actual argument to the type needed.
607          */
608         if (!Ellipsis) {
609             /* Promote the argument if needed */
610             assignadjust (Param->Type, &lval2);
611
612             /* If we have a prototype, chars may be pushed as chars */
613             Flags |= CF_FORCECHAR;
614         }
615
616         /* Use the type of the argument for the push */
617         Flags |= TypeOf (lval2.e_tptr);
618
619         /* If this is a fastcall function, don't push the last argument */
620         if (ParamCount == Func->ParamCount && (Func->Flags & FD_FASTCALL) != 0) {
621             /* Just load the argument into the primary. This is only needed if
622              * we have a constant argument, otherwise the value is already in
623              * the primary.
624              */
625             if (Flags & CF_CONST) {
626                 exprhs (CF_FORCECHAR, 0, &lval2);
627             }
628         } else {
629             /* Push the argument, count the argument size */
630             g_push (Flags, lval2.e_const);
631             ParamSize += sizeofarg (Flags);
632         }
633
634         /* Add an optimizer hint */
635         AddCodeHint ("param:end");
636
637         /* Check for end of argument list */
638         if (curtok != TOK_COMMA) {
639             break;
640         }
641         NextToken ();
642     }
643
644     /* We need the closing bracket here */
645     ConsumeRParen ();
646
647     /* Check if we had enough parameters */
648     if (ParamCount < Func->ParamCount) {
649         Error ("Too few arguments in function call");
650     }
651
652     /* */
653     if (lval->e_flags & E_MEXPR) {
654         /* Function called via pointer: Restore it and call function */
655         if (ParamSize != 0) {
656             g_restore (CF_PTR);
657         } else {
658             /* We had no parameters - remove save code */
659             RemoveCode (Mark);
660         }
661         g_callind (TypeOf (lval->e_tptr), ParamSize);
662     } else {
663         g_call (TypeOf (lval->e_tptr), (char*) lval->e_name, ParamSize);
664     }
665 }
666
667
668
669 void doasm (void)
670 /* This function parses ASM statements. The syntax of the ASM directive
671  * looks like the one defined for C++ (C has no ASM directive), that is,
672  * a string literal in parenthesis.
673  */
674 {
675     /* Skip the ASM */
676     NextToken ();
677
678     /* Need left parenthesis */
679     ConsumeLParen ();
680
681     /* String literal */
682     if (curtok != TOK_SCONST) {
683         Error ("String literal expected");
684     } else {
685         /* Write the string directly into the output, followed by a newline */
686         AddCodeLine (GetLiteral (curval));
687
688         /* Reset the string pointer, effectivly clearing the string from the
689          * string table. Since we're working with one token lookahead, this
690          * will fail if the next token is also a string token, but that's a
691          * syntax error anyway, because we expect a right paren.
692          */
693         ResetLiteralOffs (curval);
694     }
695
696     /* Skip the string token */
697     NextToken ();
698
699     /* Closing paren needed */
700     ConsumeRParen ();
701 }
702
703
704
705 static int primary (struct expent* lval)
706 /* This is the lowest level of the expression parser. */
707 {
708     int k;
709
710     /* not a test at all, yet */
711     lval->e_test = 0;
712
713     /* Character and integer constants. */
714     if (curtok == TOK_ICONST || curtok == TOK_CCONST) {
715         lval->e_flags = E_MCONST | E_TCONST;
716         lval->e_tptr  = curtype;
717         lval->e_const = curval;
718         NextToken ();
719         return 0;
720     }
721
722     /* Process parenthesized subexpression by calling the whole parser
723      * recursively.
724      */
725     if (curtok == TOK_LPAREN) {
726         NextToken ();
727         memset (lval, 0, sizeof (*lval));       /* Remove any attributes */
728         k = hie0 (lval);
729         ConsumeRParen ();
730         return k;
731     }
732
733     /* All others may only be used if the expression evaluation is not called
734      * recursively by the preprocessor.
735      */
736     if (Preprocessing) {
737         /* Illegal expression in PP mode */
738         Error ("Preprocessor expression expected");
739         lval->e_flags = E_MCONST;
740         lval->e_tptr = type_int;
741         return 0;
742     }
743
744     /* Identifier? */
745     if (curtok == TOK_IDENT) {
746
747         SymEntry* Sym;
748         ident Ident;
749
750         /* Get a pointer to the symbol table entry */
751         Sym = FindSym (CurTok.Ident);
752
753         /* Is the symbol known? */
754         if (Sym) {
755
756             /* We found the symbol - skip the name token */
757             NextToken ();
758
759             /* The expression type is the symbol type */
760             lval->e_tptr = Sym->Type;
761
762             /* Check for illegal symbol types */
763             CHECK ((Sym->Flags & SC_LABEL) != SC_LABEL);
764             if (Sym->Flags & SC_TYPE) {
765                 /* Cannot use type symbols */
766                 Error ("Variable identifier expected");
767                 /* Assume an int type to make lval valid */
768                 lval->e_flags = E_MLOCAL | E_TLOFFS;
769                 lval->e_tptr = type_int;
770                 lval->e_const = 0;
771                 return 0;
772             }
773
774             /* Check for legal symbol types */
775             if ((Sym->Flags & SC_ENUM) == SC_ENUM) {
776                 lval->e_flags = E_MCONST;
777                 lval->e_const = Sym->V.EnumVal;
778                 return 0;
779             } else if ((Sym->Flags & SC_FUNC) == SC_FUNC) {
780                 /* Function */
781                 lval->e_flags = E_MGLOBAL | E_MCONST | E_TGLAB;
782                 lval->e_name = (unsigned long) Sym->Name;
783                 lval->e_const = 0;
784             } else if ((Sym->Flags & SC_AUTO) == SC_AUTO) {
785                 /* Local variable */
786                 lval->e_flags = E_MLOCAL | E_TLOFFS;
787                 lval->e_const = Sym->V.Offs;
788             } else if ((Sym->Flags & SC_STATIC) == SC_STATIC) {
789                 /* Static variable */
790                 if (Sym->Flags & (SC_EXTERN | SC_STORAGE)) {
791                     lval->e_flags = E_MGLOBAL | E_MCONST | E_TGLAB;
792                     lval->e_name = (unsigned long) Sym->Name;
793                 } else {
794                     lval->e_flags = E_MGLOBAL | E_MCONST | E_TLLAB;
795                     lval->e_name = Sym->V.Label;
796                 }
797                 lval->e_const = 0;
798             } else if ((Sym->Flags & SC_REGISTER) == SC_REGISTER) {
799                 /* Register variable, zero page based */
800                 lval->e_flags = E_MGLOBAL | E_MCONST | E_TREGISTER;
801                 lval->e_name  = Sym->V.Offs;
802                 lval->e_const = 0;
803             } else {
804                 /* Local static variable */
805                 lval->e_flags = E_MGLOBAL | E_MCONST | E_TLLAB;
806                 lval->e_name  = Sym->V.Offs;
807                 lval->e_const = 0;
808             }
809
810             /* The symbol is referenced now */
811             Sym->Flags |= SC_REF;
812             if (IsTypeFunc (lval->e_tptr) || IsTypeArray (lval->e_tptr)) {
813                 return 0;
814             }
815             return 1;
816         }
817
818         /* We did not find the symbol. Remember the name, then skip it */
819         strcpy (Ident, CurTok.Ident);
820         NextToken ();
821
822         /* IDENT is either an auto-declared function or an undefined variable. */
823         if (curtok == TOK_LPAREN) {
824             /* Declare a function returning int. For that purpose, prepare a
825              * function signature for a function having an empty param list
826              * and returning int.
827              */
828             Warning ("Function call without a prototype");
829             Sym = AddGlobalSym (Ident, GetImplicitFuncType(), SC_EXTERN | SC_REF | SC_FUNC);
830             lval->e_tptr  = Sym->Type;
831             lval->e_flags = E_MGLOBAL | E_MCONST | E_TGLAB;
832             lval->e_name  = (unsigned long) Sym->Name;
833             lval->e_const = 0;
834             return 0;
835
836         } else {
837
838             /* Undeclared Variable */
839             Sym = AddLocalSym (Ident, type_int, SC_AUTO | SC_REF, 0);
840             lval->e_flags = E_MLOCAL | E_TLOFFS;
841             lval->e_tptr = type_int;
842             lval->e_const = 0;
843             Error ("Undefined symbol: `%s'", Ident);
844             return 1;
845
846         }
847     }
848
849     /* String literal? */
850     if (curtok == TOK_SCONST) {
851         lval->e_flags = E_MCONST | E_TLIT;
852         lval->e_const = curval;
853         lval->e_tptr  = GetCharArrayType (strlen (GetLiteral (curval)));
854         NextToken ();
855         return 0;
856     }
857
858     /* ASM statement? */
859     if (curtok == TOK_ASM) {
860         doasm ();
861         lval->e_tptr  = type_void;
862         lval->e_flags = E_MEXPR;
863         lval->e_const = 0;
864         return 0;
865     }
866
867     /* __AX__ and __EAX__ pseudo values? */
868     if (curtok == TOK_AX || curtok == TOK_EAX) {
869         lval->e_tptr  = (curtok == TOK_AX)? type_uint : type_ulong;
870         lval->e_flags = E_MREG;
871         lval->e_test &= ~E_CC;
872         lval->e_const = 0;
873         NextToken ();
874         return 1;               /* May be used as lvalue */
875     }
876
877     /* Illegal primary. */
878     Error ("Expression expected");
879     lval->e_flags = E_MCONST;
880     lval->e_tptr = type_int;
881     return 0;
882 }
883
884
885
886 static int arrayref (int k, struct expent* lval)
887 /* Handle an array reference */
888 {
889     unsigned lflags;
890     unsigned rflags;
891     int ConstBaseAddr;
892     int ConstSubAddr;
893     int l;
894     struct expent lval2;
895     CodeMark Mark1;
896     CodeMark Mark2;
897     type* tptr1;
898     type* tptr2;
899
900
901     /* Skip the bracket */
902     NextToken ();
903
904     /* Get the type of left side */
905     tptr1 = lval->e_tptr;
906
907     /* We can apply a special treatment for arrays that have a const base
908      * address. This is true for most arrays and will produce a lot better
909      * code. Check if this is a const base address.
910      */
911     lflags = lval->e_flags & ~E_MCTYPE;
912     ConstBaseAddr = (lflags == E_MCONST)       || /* Constant numeric address */
913                      (lflags & E_MGLOBAL) != 0 || /* Static array, or ... */
914                      lflags == E_MLOCAL;          /* Local array */
915
916     /* If we have a constant base, we delay the address fetch */
917     Mark1 = GetCodePos ();
918     Mark2 = 0;          /* Silence gcc */
919     if (!ConstBaseAddr) {
920         /* Get a pointer to the array into the primary */
921         exprhs (CF_NONE, k, lval);
922
923         /* Get the array pointer on stack. Do not push more than 16
924          * bit, even if this value is greater, since we cannot handle
925          * other than 16bit stuff when doing indexing.
926          */
927         Mark2 = GetCodePos ();
928         g_push (CF_PTR, 0);
929     }
930
931     /* TOS now contains ptr to array elements. Get the subscript. */
932     l = hie0 (&lval2);
933     if (l == 0 && lval2.e_flags == E_MCONST) {
934
935         /* The array subscript is a constant - remove value from stack */
936         if (!ConstBaseAddr) {
937             RemoveCode (Mark2);
938             pop (CF_PTR);
939         } else {
940             /* Get an array pointer into the primary */
941             exprhs (CF_NONE, k, lval);
942         }
943
944         if (IsClassPtr (tptr1)) {
945
946             /* Scale the subscript value according to element size */
947             lval2.e_const *= PSizeOf (tptr1);
948
949             /* Remove code for lhs load */
950             RemoveCode (Mark1);
951
952             /* Handle constant base array on stack. Be sure NOT to
953              * handle pointers the same way, this won't work.
954              */
955             if (IsTypeArray (tptr1) &&
956                 ((lval->e_flags & ~E_MCTYPE) == E_MCONST ||
957                 (lval->e_flags & ~E_MCTYPE) == E_MLOCAL ||
958                 (lval->e_flags & E_MGLOBAL) != 0 ||
959                 (lval->e_flags == E_MEOFFS))) {
960                 lval->e_const += lval2.e_const;
961
962             } else {
963                 /* Pointer - load into primary and remember offset */
964                 if ((lval->e_flags & E_MEXPR) == 0 || k != 0) {
965                     exprhs (CF_NONE, k, lval);
966                 }
967                 lval->e_const = lval2.e_const;
968                 lval->e_flags = E_MEOFFS;
969             }
970
971             /* Result is of element type */
972             lval->e_tptr = Indirect (tptr1);
973
974             /* Done */
975             goto end_array;
976
977         } else if (IsClassPtr (tptr2 = lval2.e_tptr)) {
978             /* Subscript is pointer, get element type */
979             lval2.e_tptr = Indirect (tptr2);
980
981             /* Scale the rhs value in the primary register */
982             g_scale (TypeOf (tptr1), SizeOf (lval2.e_tptr));
983             /* */
984             lval->e_tptr = lval2.e_tptr;
985         } else {
986             Error ("Cannot subscript");
987         }
988
989         /* Add the subscript. Since arrays are indexed by integers,
990          * we will ignore the true type of the subscript here and
991          * use always an int.
992          */
993         g_inc (CF_INT | CF_CONST, lval2.e_const);
994
995     } else {
996
997         /* Array subscript is not constant. Load it into the primary */
998         Mark2 = GetCodePos ();
999         exprhs (CF_NONE, l, &lval2);
1000
1001         tptr2 = lval2.e_tptr;
1002         if (IsClassPtr (tptr1)) {
1003
1004             /* Get the element type */
1005             lval->e_tptr = Indirect (tptr1);
1006
1007             /* Indexing is based on int's, so we will just use the integer
1008              * portion of the index (which is in (e)ax, so there's no further
1009              * action required).
1010              */
1011             g_scale (CF_INT, SizeOf (lval->e_tptr));
1012
1013         } else if (IsClassPtr (tptr2)) {
1014
1015             /* Get the element type */
1016             lval2.e_tptr = Indirect (tptr2);
1017
1018             /* Get the int value on top. If we go here, we're sure,
1019              * both values are 16 bit (the first one was truncated
1020              * if necessary and the second one is a pointer).
1021              * Note: If ConstBaseAddr is true, we don't have a value on
1022              * stack, so to "swap" both, just push the subscript.
1023              */
1024             if (ConstBaseAddr) {
1025                 g_push (CF_INT, 0);
1026                 exprhs (CF_NONE, k, lval);
1027                 ConstBaseAddr = 0;
1028             } else {
1029                 g_swap (CF_INT);
1030             }
1031
1032             /* Scale it */
1033             g_scale (TypeOf (tptr1), SizeOf (lval2.e_tptr));
1034             lval->e_tptr = lval2.e_tptr;
1035         } else {
1036             Error ("Cannot subscript");
1037         }
1038
1039         /* The offset is now in the primary register. It didn't have a
1040          * constant base address for the lhs, the lhs address is already
1041          * on stack, and we must add the offset. If the base address was
1042          * constant, we call special functions to add the address to the
1043          * offset value.
1044          */
1045         if (!ConstBaseAddr) {
1046             /* Add the subscript. Both values are int sized. */
1047             g_add (CF_INT, 0);
1048         } else {
1049
1050             /* If the subscript has itself a constant address, it is often
1051              * a better idea to reverse again the order of the evaluation.
1052              * This will generate better code if the subscript is a byte
1053              * sized variable. But beware: This is only possible if the
1054              * subscript was not scaled, that is, if this was a byte array
1055              * or pointer.
1056              */
1057             rflags = lval2.e_flags & ~E_MCTYPE;
1058             ConstSubAddr = (rflags == E_MCONST)       || /* Constant numeric address */
1059                             (rflags & E_MGLOBAL) != 0 || /* Static array, or ... */
1060                             rflags == E_MLOCAL;          /* Local array */
1061
1062             if (ConstSubAddr && SizeOf (lval->e_tptr) == 1) {
1063
1064                 type* SavedType;
1065
1066                 /* Reverse the order of evaluation */
1067                 unsigned flags = (SizeOf (lval2.e_tptr) == 1)? CF_CHAR : CF_INT;
1068                 RemoveCode (Mark2);
1069
1070                 /* Get a pointer to the array into the primary. We have changed
1071                  * e_tptr above but we need the original type to load the
1072                  * address, so restore it temporarily.
1073                  */
1074                 SavedType = lval->e_tptr;
1075                 lval->e_tptr = tptr1;
1076                 exprhs (CF_NONE, k, lval);
1077                 lval->e_tptr = SavedType;
1078
1079                 /* Add the variable */
1080                 if (rflags == E_MLOCAL) {
1081                     g_addlocal (flags, lval2.e_const);
1082                 } else {
1083                     flags |= GlobalModeFlags (lval2.e_flags);
1084                     g_addstatic (flags, lval2.e_name, lval2.e_const);
1085                 }
1086             } else {
1087                 if (lflags == E_MCONST) {
1088                     /* Constant numeric address. Just add it */
1089                     g_inc (CF_INT | CF_UNSIGNED, lval->e_const);
1090                 } else if (lflags == E_MLOCAL) {
1091                     /* Base address is a local variable address */
1092                     if (IsTypeArray (tptr1)) {
1093                         g_addaddr_local (CF_INT, lval->e_const);
1094                     } else {
1095                         g_addlocal (CF_PTR, lval->e_const);
1096                     }
1097                 } else {
1098                     /* Base address is a static variable address */
1099                     unsigned flags = CF_INT;
1100                     flags |= GlobalModeFlags (lval->e_flags);
1101                     if (IsTypeArray (tptr1)) {
1102                         g_addaddr_static (flags, lval->e_name, lval->e_const);
1103                     } else {
1104                         g_addstatic (flags, lval->e_name, lval->e_const);
1105                     }
1106                 }
1107             }
1108         }
1109     }
1110     lval->e_flags = E_MEXPR;
1111 end_array:
1112     ConsumeRBrack ();
1113     return !IsTypeArray (lval->e_tptr);
1114
1115 }
1116
1117
1118
1119 static int structref (int k, struct expent* lval)
1120 /* Process struct field after . or ->. */
1121 {
1122     ident Ident;
1123     SymEntry* Field;
1124     int flags;
1125
1126     /* Skip the token and check for an identifier */
1127     NextToken ();
1128     if (curtok != TOK_IDENT) {
1129         Error ("Identifier expected");
1130         lval->e_tptr = type_int;
1131         return 0;
1132     }
1133
1134     /* Get the symbol table entry and check for a struct field */
1135     strcpy (Ident, CurTok.Ident);
1136     NextToken ();
1137     Field = FindStructField (lval->e_tptr, Ident);
1138     if (Field == 0) {
1139         Error ("Struct/union has no field named `%s'", Ident);
1140         lval->e_tptr = type_int;
1141         return 0;
1142     }
1143
1144     /* If we have constant input data, the result is also constant */
1145     flags = lval->e_flags & ~E_MCTYPE;
1146     if (flags == E_MCONST ||
1147         (k == 0 && (flags == E_MLOCAL ||
1148                     (flags & E_MGLOBAL) != 0 ||
1149                     lval->e_flags  == E_MEOFFS))) {
1150         lval->e_const += Field->V.Offs;
1151     } else {
1152         if ((flags & E_MEXPR) == 0 || k != 0) {
1153             exprhs (CF_NONE, k, lval);
1154         }
1155         lval->e_const = Field->V.Offs;
1156         lval->e_flags = E_MEOFFS;
1157     }
1158     lval->e_tptr = Field->Type;
1159     return !IsTypeArray (Field->Type);
1160 }
1161
1162
1163
1164 static int hie11 (struct expent *lval)
1165 /* Handle compound types (structs and arrays) */
1166 {
1167     int k;
1168     type* tptr;
1169
1170
1171     k = primary (lval);
1172     if (curtok < TOK_LBRACK || curtok > TOK_PTR_REF) {
1173         /* Not for us */
1174         return k;
1175     }
1176
1177     while (1) {
1178
1179         if (curtok == TOK_LBRACK) {
1180
1181             /* Array reference */
1182             k = arrayref (k, lval);
1183
1184         } else if (curtok == TOK_LPAREN) {
1185
1186             /* Function call. Skip the opening parenthesis */
1187             NextToken ();
1188             tptr = lval->e_tptr;
1189             if (IsTypeFunc (tptr) || IsTypeFuncPtr (tptr)) {
1190                 if (IsTypeFuncPtr (tptr)) {
1191                     /* Pointer to function. Handle transparently */
1192                     exprhs (CF_NONE, k, lval);  /* Function pointer to A/X */
1193                     ++lval->e_tptr;             /* Skip T_PTR */
1194                     lval->e_flags |= E_MEXPR;
1195                 }
1196                 callfunction (lval);
1197                 lval->e_flags = E_MEXPR;
1198                 lval->e_tptr += DECODE_SIZE + 1;        /* Set to result */
1199             } else {
1200                 Error ("Illegal function call");
1201             }
1202             k = 0;
1203
1204         } else if (curtok == TOK_DOT) {
1205
1206             if (!IsClassStruct (lval->e_tptr)) {
1207                 Error ("Struct expected");
1208             }
1209             k = structref (0, lval);
1210
1211         } else if (curtok == TOK_PTR_REF) {
1212
1213             tptr = lval->e_tptr;
1214             if (tptr[0] != T_PTR || (tptr[1] & T_STRUCT) == 0) {
1215                 Error ("Struct pointer expected");
1216             }
1217             k = structref (k, lval);
1218
1219         } else {
1220             return k;
1221         }
1222     }
1223 }
1224
1225
1226
1227 static void store (struct expent* lval)
1228 /* Store primary reg into this reference */
1229 {
1230     int f;
1231     unsigned flags;
1232
1233     f = lval->e_flags;
1234     flags = TypeOf (lval->e_tptr);
1235     if (f & E_MGLOBAL) {
1236         flags |= GlobalModeFlags (f);
1237         if (lval->e_test) {
1238             /* Just testing */
1239             flags |= CF_TEST;
1240         }
1241
1242         /* Generate code */
1243         g_putstatic (flags, lval->e_name, lval->e_const);
1244
1245     } else if (f & E_MLOCAL) {
1246         g_putlocal (flags, lval->e_const);
1247     } else if (f == E_MEOFFS) {
1248         g_putind (flags, lval->e_const);
1249     } else if (f != E_MREG) {
1250         if (f & E_MEXPR) {
1251             g_putind (flags, 0);
1252         } else {
1253             /* Store into absolute address */
1254             g_putstatic (flags | CF_ABSOLUTE, lval->e_const, 0);
1255         }
1256     }
1257
1258     /* Assume that each one of the stores will invalidate CC */
1259     lval->e_test &= ~E_CC;
1260 }
1261
1262
1263
1264 static void pre_incdec (struct expent* lval, void (*inc) (unsigned, unsigned long))
1265 /* Handle --i and ++i */
1266 {
1267     int k;
1268     unsigned flags;
1269     unsigned long val;
1270
1271     NextToken ();
1272     if ((k = hie10 (lval)) == 0) {
1273         Error ("Invalid lvalue");
1274         return;
1275     }
1276
1277     /* Get the data type */
1278     flags = TypeOf (lval->e_tptr) | CF_FORCECHAR | CF_CONST;
1279
1280     /* Get the increment value in bytes */
1281     val = (lval->e_tptr [0] == T_PTR)? PSizeOf (lval->e_tptr) : 1;
1282
1283     /* We're currently only able to handle some adressing modes */
1284     if ((lval->e_flags & E_MGLOBAL) == 0 &&     /* Global address? */
1285         (lval->e_flags & E_MLOCAL) == 0  &&     /* Local address? */
1286         (lval->e_flags & E_MCONST) == 0  &&     /* Constant address? */
1287         (lval->e_flags & E_MEXPR) == 0) {       /* Address in a/x? */
1288
1289         /* Use generic code. Push the address if needed */
1290         PushAddr (lval);
1291
1292         /* Fetch the value */
1293         exprhs (CF_NONE, k, lval);
1294
1295         /* Increment value in primary */
1296         inc (flags, val);
1297
1298         /* Store the result back */
1299         store (lval);
1300
1301     } else {
1302
1303         /* Special code for some addressing modes - use the special += ops */
1304         if (lval->e_flags & E_MGLOBAL) {
1305             flags |= GlobalModeFlags (lval->e_flags);
1306             if (inc == g_inc) {
1307                 g_addeqstatic (flags, lval->e_name, lval->e_const, val);
1308             } else {
1309                 g_subeqstatic (flags, lval->e_name, lval->e_const, val);
1310             }
1311         } else if (lval->e_flags & E_MLOCAL) {
1312             /* ref to localvar */
1313             if (inc == g_inc) {
1314                 g_addeqlocal (flags, lval->e_const, val);
1315             } else {
1316                 g_subeqlocal (flags, lval->e_const, val);
1317             }
1318         } else if (lval->e_flags & E_MCONST) {
1319             /* ref to absolute address */
1320             flags |= CF_ABSOLUTE;
1321             if (inc == g_inc) {
1322                 g_addeqstatic (flags, lval->e_const, 0, val);
1323             } else {
1324                 g_subeqstatic (flags, lval->e_const, 0, val);
1325             }
1326         } else if (lval->e_flags & E_MEXPR) {
1327             /* Address in a/x, check if we have an offset */
1328             unsigned Offs = (lval->e_flags == E_MEOFFS)? lval->e_const : 0;
1329             if (inc == g_inc) {
1330                 g_addeqind (flags, Offs, val);
1331             } else {
1332                 g_subeqind (flags, Offs, val);
1333             }
1334         } else {
1335             Internal ("Invalid addressing mode");
1336         }
1337
1338     }
1339
1340     /* Result is an expression */
1341     lval->e_flags = E_MEXPR;
1342 }
1343
1344
1345
1346 static void post_incdec (struct expent *lval, int k, void (*inc) (unsigned, unsigned long))
1347 /* Handle i-- and i++ */
1348 {
1349     unsigned flags;
1350
1351     NextToken ();
1352     if (k == 0) {
1353         Error ("Invalid lvalue");
1354         return;
1355     }
1356
1357     /* Get the data type */
1358     flags = TypeOf (lval->e_tptr);
1359
1360     /* Push the address if needed */
1361     PushAddr (lval);
1362
1363     /* Fetch the value and save it (since it's the result of the expression) */
1364     exprhs (CF_NONE, 1, lval);
1365     g_save (flags | CF_FORCECHAR);
1366
1367     /* If we have a pointer expression, increment by the size of the type */
1368     if (lval->e_tptr[0] == T_PTR) {
1369         inc (flags | CF_CONST | CF_FORCECHAR, SizeOf (lval->e_tptr + 1));
1370     } else {
1371         inc (flags | CF_CONST | CF_FORCECHAR, 1);
1372     }
1373
1374     /* Store the result back */
1375     store (lval);
1376
1377     /* Restore the original value */
1378     g_restore (flags | CF_FORCECHAR);
1379     lval->e_flags = E_MEXPR;
1380 }
1381
1382
1383
1384 static void unaryop (int tok, struct expent* lval)
1385 /* Handle unary -/+ and ~ */
1386 {
1387     int k;
1388     unsigned flags;
1389
1390     NextToken ();
1391     k = hie10 (lval);
1392     if (k == 0 && lval->e_flags & E_MCONST) {
1393         /* Value is constant */
1394         switch (tok) {
1395             case TOK_MINUS: lval->e_const =     -lval->e_const; break;
1396             case TOK_PLUS:                                      break;
1397             case TOK_COMP:  lval->e_const = ~lval->e_const;     break;
1398             default:        Internal ("Unexpected token: %d", tok);
1399         }
1400     } else {
1401         /* Value is not constant */
1402         exprhs (CF_NONE, k, lval);
1403
1404         /* Get the type of the expression */
1405         flags = TypeOf (lval->e_tptr);
1406
1407         /* Handle the operation */
1408         switch (tok) {
1409             case TOK_MINUS: g_neg (flags);  break;
1410             case TOK_PLUS:                  break;
1411             case TOK_COMP:  g_com (flags);  break;
1412             default:    Internal ("Unexpected token: %d", tok);
1413         }
1414         lval->e_flags = E_MEXPR;
1415     }
1416 }
1417
1418
1419
1420 static int typecast (struct expent* lval)
1421 /* Handle an explicit cast */
1422 {
1423     int k;
1424     type Type[MAXTYPELEN];
1425
1426     /* Skip the left paren */
1427     NextToken ();
1428
1429     /* Read the type */
1430     ParseType (Type);
1431
1432     /* Closing paren */
1433     ConsumeRParen ();
1434
1435     /* Read the expression we have to cast */
1436     k = hie10 (lval);
1437
1438     /* If the expression is a function, treat it as pointer-to-function */
1439     if (IsTypeFunc (lval->e_tptr)) {
1440         lval->e_tptr = PointerTo (lval->e_tptr);
1441     }
1442
1443     /* Check for a constant on the right side */
1444     if (k == 0 && lval->e_flags == E_MCONST) {
1445
1446         /* A cast of a constant to something else. If the new type is an int,
1447          * be sure to handle the size extension correctly. If the new type is
1448          * not an int, the cast is implementation specific anyway, so leave
1449          * the value alone.
1450          */
1451         if (IsClassInt (Type)) {
1452
1453             /* Get the current and new size of the value */
1454             unsigned OldSize = SizeOf (lval->e_tptr);
1455             unsigned NewSize = SizeOf (Type);
1456             unsigned OldBits = OldSize * 8;
1457             unsigned NewBits = NewSize * 8;
1458
1459             /* Check if the new datatype will have a smaller range */
1460             if (NewSize < OldSize) {
1461
1462                 /* Cut the value to the new size */
1463                 lval->e_const &= (0xFFFFFFFFUL >> (32 - NewBits));
1464
1465                 /* If the new value is signed, sign extend the value */
1466                 if (!IsSignUnsigned (Type)) {
1467                     lval->e_const |= ((~0L) << NewBits);
1468                 }
1469
1470             } else if (NewSize > OldSize) {
1471
1472                 /* Sign extend the value if needed */
1473                 if (!IsSignUnsigned (Type) && !IsSignUnsigned (lval->e_tptr)) {
1474                     if (lval->e_const & (0x01UL << (OldBits-1))) {
1475                         lval->e_const |= ((~0L) << OldBits);
1476                     }
1477                 }
1478             }
1479         }
1480
1481     } else {
1482
1483         /* Not a constant. Be sure to ignore casts to void */
1484         if (!IsTypeVoid (Type)) {
1485
1486             /* If the size does not change, leave the value alone. Otherwise,
1487              * we have to load the value into the primary and generate code to
1488              * cast the value in the primary register.
1489              */
1490             if (SizeOf (Type) != SizeOf (lval->e_tptr)) {
1491
1492                 /* Load the value into the primary */
1493                 exprhs (CF_NONE, k, lval);
1494
1495                 /* Mark the lhs as const to avoid a manipulation of TOS */
1496                 g_typecast (TypeOf (Type) | CF_CONST, TypeOf (lval->e_tptr));
1497
1498                 /* Value is now in primary */
1499                 lval->e_flags = E_MEXPR;
1500                 k = 0;
1501             }
1502         }
1503     }
1504
1505     /* In any case, use the new type */
1506     lval->e_tptr = TypeDup (Type);
1507
1508     /* Done */
1509     return k;
1510 }
1511
1512
1513
1514 static int hie10 (struct expent* lval)
1515 /* Handle ++, --, !, unary - etc. */
1516 {
1517     int k;
1518     type* t;
1519
1520     switch (curtok) {
1521
1522         case TOK_INC:
1523             pre_incdec (lval, g_inc);
1524             return 0;
1525
1526         case TOK_DEC:
1527             pre_incdec (lval, g_dec);
1528             return 0;
1529
1530         case TOK_PLUS:
1531         case TOK_MINUS:
1532         case TOK_COMP:
1533             unaryop (curtok, lval);
1534             return 0;
1535
1536         case TOK_BOOL_NOT:
1537             NextToken ();
1538             if (evalexpr (CF_NONE, hie10, lval) == 0) {
1539                 /* Constant expression */
1540                 lval->e_const = !lval->e_const;
1541             } else {
1542                 g_bneg (TypeOf (lval->e_tptr));
1543                 lval->e_test |= E_CC;                   /* bneg will set cc */
1544                 lval->e_flags = E_MEXPR;                /* say it's an expr */
1545             }
1546             return 0;                           /* expr not storable */
1547
1548         case TOK_STAR:
1549             NextToken ();
1550             if (evalexpr (CF_NONE, hie10, lval) != 0) {
1551                 /* Expression is not const, indirect value loaded into primary */
1552                 lval->e_flags = E_MEXPR;
1553                 lval->e_const = 0;              /* Offset is zero now */
1554             }
1555             t = lval->e_tptr;
1556             if (IsClassPtr (t)) {
1557                 lval->e_tptr = Indirect (t);
1558             } else {
1559                 Error ("Illegal indirection");
1560             }
1561             return 1;
1562
1563         case TOK_AND:
1564             NextToken ();
1565             k = hie10 (lval);
1566             /* The & operator may be applied to any lvalue, and it may be
1567              * applied to functions, even if they're no lvalues.
1568              */
1569             if (k == 0 && !IsTypeFunc (lval->e_tptr)) {
1570                 /* Allow the & operator with an array */
1571                 if (!IsTypeArray (lval->e_tptr)) {
1572                     Error ("Illegal address");
1573                 }
1574             } else {
1575                 t = TypeAlloc (TypeLen (lval->e_tptr) + 2);
1576                 t [0] = T_PTR;
1577                 TypeCpy (t + 1, lval->e_tptr);
1578                 lval->e_tptr = t;
1579             }
1580             return 0;
1581
1582         case TOK_SIZEOF:
1583             NextToken ();
1584             if (istypeexpr ()) {
1585                 type Type[MAXTYPELEN];
1586                 NextToken ();
1587                 lval->e_const = SizeOf (ParseType (Type));
1588                 ConsumeRParen ();
1589             } else {
1590                 /* Remember the output queue pointer */
1591                 CodeMark Mark = GetCodePos ();
1592                 hie10 (lval);
1593                 lval->e_const = SizeOf (lval->e_tptr);
1594                 /* Remove any generated code */
1595                 RemoveCode (Mark);
1596             }
1597             lval->e_flags = E_MCONST | E_TCONST;
1598             lval->e_tptr = type_uint;
1599             lval->e_test &= ~E_CC;
1600             return 0;
1601
1602         default:
1603             if (istypeexpr ()) {
1604                 /* A cast */
1605                 return typecast (lval);
1606             }
1607     }
1608
1609     k = hie11 (lval);
1610     switch (curtok) {
1611         case TOK_INC:
1612             post_incdec (lval, k, g_inc);
1613             return 0;
1614
1615         case TOK_DEC:
1616             post_incdec (lval, k, g_dec);
1617             return 0;
1618
1619         default:
1620             return k;
1621     }
1622 }
1623
1624
1625
1626 static int hie_internal (GenDesc** ops,         /* List of generators */
1627                          struct expent* lval,   /* parent expr's lval */
1628                          int (*hienext) (struct expent*),
1629                          int* UsedGen)          /* next higher level */
1630 /* Helper function */
1631 {
1632     int k;
1633     struct expent lval2;
1634     CodeMark Mark1;
1635     CodeMark Mark2;
1636     GenDesc* Gen;
1637     token_t tok;                        /* The operator token */
1638     unsigned ltype, type;
1639     int rconst;                         /* Operand is a constant */
1640
1641
1642     k = hienext (lval);
1643
1644     *UsedGen = 0;
1645     while ((Gen = FindGen (curtok, ops)) != 0) {
1646
1647         /* Tell the caller that we handled it's ops */
1648         *UsedGen = 1;
1649
1650         /* All operators that call this function expect an int on the lhs */
1651         if (!IsClassInt (lval->e_tptr)) {
1652             Error ("Integer expression expected");
1653         }
1654
1655         /* Remember the operator token, then skip it */
1656         tok = curtok;
1657         NextToken ();
1658
1659         /* Get the lhs on stack */
1660         Mark1 = GetCodePos ();
1661         ltype = TypeOf (lval->e_tptr);
1662         if (k == 0 && lval->e_flags == E_MCONST) {
1663             /* Constant value */
1664             Mark2 = GetCodePos ();
1665             g_push (ltype | CF_CONST, lval->e_const);
1666         } else {
1667             /* Value not constant */
1668             exprhs (CF_NONE, k, lval);
1669             Mark2 = GetCodePos ();
1670             g_push (ltype, 0);
1671         }
1672
1673         /* Get the right hand side */
1674         rconst = (evalexpr (CF_NONE, hienext, &lval2) == 0);
1675
1676         /* Check the type of the rhs */
1677         if (!IsClassInt (lval2.e_tptr)) {
1678             Error ("Integer expression expected");
1679         }
1680
1681         /* Check for const operands */
1682         if (k == 0 && lval->e_flags == E_MCONST && rconst) {
1683
1684             /* Both operands are constant, remove the generated code */
1685             RemoveCode (Mark1);
1686             pop (ltype);
1687
1688             /* Evaluate the result */
1689             lval->e_const = kcalc (tok, lval->e_const, lval2.e_const);
1690
1691             /* Get the type of the result */
1692             lval->e_tptr = promoteint (lval->e_tptr, lval2.e_tptr);
1693
1694         } else {
1695
1696             /* If the right hand side is constant, and the generator function
1697              * expects the lhs in the primary, remove the push of the primary
1698              * now.
1699              */
1700             unsigned rtype = TypeOf (lval2.e_tptr);
1701             type = 0;
1702             if (rconst) {
1703                 /* Second value is constant - check for div */
1704                 type |= CF_CONST;
1705                 rtype |= CF_CONST;
1706                 if (tok == TOK_DIV && lval2.e_const == 0) {
1707                     Error ("Division by zero");
1708                 } else if (tok == TOK_MOD && lval2.e_const == 0) {
1709                     Error ("Modulo operation with zero");
1710                 }
1711                 if ((Gen->Flags & GEN_NOPUSH) != 0) {
1712                     RemoveCode (Mark2);
1713                     pop (ltype);
1714                     ltype |= CF_REG;    /* Value is in register */
1715                 }
1716             }
1717
1718             /* Determine the type of the operation result. */
1719             type |= g_typeadjust (ltype, rtype);
1720             lval->e_tptr = promoteint (lval->e_tptr, lval2.e_tptr);
1721
1722             /* Generate code */
1723             Gen->Func (type, lval2.e_const);
1724             lval->e_flags = E_MEXPR;
1725         }
1726
1727         /* We have a rvalue now */
1728         k = 0;
1729     }
1730
1731     return k;
1732 }
1733
1734
1735
1736 static int hie_compare (GenDesc** ops,          /* List of generators */
1737                         struct expent* lval,    /* parent expr's lval */
1738                         int (*hienext) (struct expent*))
1739 /* Helper function for the compare operators */
1740 {
1741     int k;
1742     struct expent lval2;
1743     CodeMark Mark1;
1744     CodeMark Mark2;
1745     GenDesc* Gen;
1746     token_t tok;                        /* The operator token */
1747     unsigned ltype;
1748     int rconst;                         /* Operand is a constant */
1749
1750
1751     k = hienext (lval);
1752
1753     while ((Gen = FindGen (curtok, ops)) != 0) {
1754
1755         /* Remember the operator token, then skip it */
1756         tok = curtok;
1757         NextToken ();
1758
1759         /* Get the lhs on stack */
1760         Mark1 = GetCodePos ();
1761         ltype = TypeOf (lval->e_tptr);
1762         if (k == 0 && lval->e_flags == E_MCONST) {
1763             /* Constant value */
1764             Mark2 = GetCodePos ();
1765             g_push (ltype | CF_CONST, lval->e_const);
1766         } else {
1767             /* Value not constant */
1768             exprhs (CF_NONE, k, lval);
1769             Mark2 = GetCodePos ();
1770             g_push (ltype, 0);
1771         }
1772
1773         /* Get the right hand side */
1774         rconst = (evalexpr (CF_NONE, hienext, &lval2) == 0);
1775
1776         /* Make sure, the types are compatible */
1777         if (IsClassInt (lval->e_tptr)) {
1778             if (!IsClassInt (lval2.e_tptr) && !(IsClassPtr(lval2.e_tptr) && IsNullPtr(lval))) {
1779                 Error ("Incompatible types");
1780             }
1781         } else if (IsClassPtr (lval->e_tptr)) {
1782             if (IsClassPtr (lval2.e_tptr)) {
1783                 /* Both pointers are allowed in comparison if they point to
1784                  * the same type, or if one of them is a void pointer.
1785                  */
1786                 type* left  = Indirect (lval->e_tptr);
1787                 type* right = Indirect (lval2.e_tptr);
1788                 if (TypeCmp (left, right) < TC_EQUAL && *left != T_VOID && *right != T_VOID) {
1789                     /* Incomatible pointers */
1790                     Error ("Incompatible types");
1791                 }
1792             } else if (!IsNullPtr (&lval2)) {
1793                 Error ("Incompatible types");
1794             }
1795         }
1796
1797         /* Check for const operands */
1798         if (k == 0 && lval->e_flags == E_MCONST && rconst) {
1799
1800             /* Both operands are constant, remove the generated code */
1801             RemoveCode (Mark1);
1802             pop (ltype);
1803
1804             /* Evaluate the result */
1805             lval->e_const = kcalc (tok, lval->e_const, lval2.e_const);
1806
1807         } else {
1808
1809             /* If the right hand side is constant, and the generator function
1810              * expects the lhs in the primary, remove the push of the primary
1811              * now.
1812              */
1813             unsigned flags = 0;
1814             if (rconst) {
1815                 flags |= CF_CONST;
1816                 if ((Gen->Flags & GEN_NOPUSH) != 0) {
1817                     RemoveCode (Mark2);
1818                     pop (ltype);
1819                     ltype |= CF_REG;    /* Value is in register */
1820                 }
1821             }
1822
1823             /* Determine the type of the operation result. If the left
1824              * operand is of type char and the right is a constant, or
1825              * if both operands are of type char, we will encode the
1826              * operation as char operation. Otherwise the default
1827              * promotions are used.
1828              */
1829             if (IsTypeChar (lval->e_tptr) && (IsTypeChar (lval2.e_tptr) || rconst)) {
1830                 flags |= CF_CHAR;
1831                 if (IsSignUnsigned (lval->e_tptr) || IsSignUnsigned (lval2.e_tptr)) {
1832                     flags |= CF_UNSIGNED;
1833                 }
1834                 if (rconst) {
1835                     flags |= CF_FORCECHAR;
1836                 }
1837             } else {
1838                 unsigned rtype = TypeOf (lval2.e_tptr) | (flags & CF_CONST);
1839                 flags |= g_typeadjust (ltype, rtype);
1840             }
1841
1842             /* Generate code */
1843             Gen->Func (flags, lval2.e_const);
1844             lval->e_flags = E_MEXPR;
1845         }
1846
1847         /* Result type is always int */
1848         lval->e_tptr = type_int;
1849
1850         /* We have a rvalue now, condition codes are set */
1851         k = 0;
1852         lval->e_test |= E_CC;
1853     }
1854
1855     return k;
1856 }
1857
1858
1859
1860 static int hie9 (struct expent *lval)
1861 /* Process * and / operators. */
1862 {
1863     static GenDesc* hie9_ops [] = {
1864         &GenMUL, &GenDIV, &GenMOD, 0
1865     };
1866     int UsedGen;
1867
1868     return hie_internal (hie9_ops, lval, hie10, &UsedGen);
1869 }
1870
1871
1872
1873 static void parseadd (int k, struct expent* lval)
1874 /* Parse an expression with the binary plus operator. lval contains the
1875  * unprocessed left hand side of the expression and will contain the
1876  * result of the expression on return.
1877  */
1878 {
1879     struct expent lval2;
1880     unsigned flags;             /* Operation flags */
1881     CodeMark Mark;              /* Remember code position */
1882     type* lhst;                 /* Type of left hand side */
1883     type* rhst;                 /* Type of right hand side */
1884
1885
1886     /* Skip the PLUS token */
1887     NextToken ();
1888
1889     /* Get the left hand side type, initialize operation flags */
1890     lhst = lval->e_tptr;
1891     flags = 0;
1892
1893     /* Check for constness on both sides */
1894     if (k == 0 && lval->e_flags == E_MCONST) {
1895
1896         /* The left hand side is a constant. Good. Get rhs */
1897         if (evalexpr (CF_NONE, hie9, &lval2) == 0) {
1898
1899             /* Right hand side is also constant. Get the rhs type */
1900             rhst = lval2.e_tptr;
1901
1902             /* Both expressions are constants. Check for pointer arithmetic */
1903             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
1904                 /* Left is pointer, right is int, must scale rhs */
1905                 lval->e_const = lval->e_const + lval2.e_const * PSizeOf (lhst);
1906                 /* Result type is a pointer */
1907             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
1908                 /* Left is int, right is pointer, must scale lhs */
1909                 lval->e_const = lval->e_const * PSizeOf (rhst) + lval2.e_const;
1910                 /* Result type is a pointer */
1911                 lval->e_tptr = lval2.e_tptr;
1912             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
1913                 /* Integer addition */
1914                 lval->e_const += lval2.e_const;
1915                 typeadjust (lval, &lval2, 1);
1916             } else {
1917                 /* OOPS */
1918                 Error ("Invalid operands for binary operator `+'");
1919             }
1920
1921             /* Result is constant, condition codes not set */
1922             lval->e_test = E_MCONST;
1923
1924         } else {
1925
1926             /* lhs is constant, rhs is not. Get the rhs type. */
1927             rhst = lval2.e_tptr;
1928
1929             /* Check for pointer arithmetic */
1930             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
1931                 /* Left is pointer, right is int, must scale rhs */
1932                 g_scale (CF_INT, PSizeOf (lhst));
1933                 /* Operate on pointers, result type is a pointer */
1934                 flags = CF_PTR;
1935             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
1936                 /* Left is int, right is pointer, must scale lhs */
1937                 lval->e_const *= PSizeOf (rhst);
1938                 /* Operate on pointers, result type is a pointer */
1939                 flags = CF_PTR;
1940                 lval->e_tptr = lval2.e_tptr;
1941             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
1942                 /* Integer addition */
1943                 flags = typeadjust (lval, &lval2, 1);
1944             } else {
1945                 /* OOPS */
1946                 Error ("Invalid operands for binary operator `+'");
1947             }
1948
1949             /* Generate code for the add */
1950             g_inc (flags | CF_CONST, lval->e_const);
1951
1952             /* Result is in primary register */
1953             lval->e_flags = E_MEXPR;
1954             lval->e_test &= ~E_CC;
1955
1956         }
1957
1958     } else {
1959
1960         /* Left hand side is not constant. Get the value onto the stack. */
1961         exprhs (CF_NONE, k, lval);              /* --> primary register */
1962         Mark = GetCodePos ();
1963         g_push (TypeOf (lval->e_tptr), 0);      /* --> stack */
1964
1965         /* Evaluate the rhs */
1966         if (evalexpr (CF_NONE, hie9, &lval2) == 0) {
1967
1968             /* Right hand side is a constant. Get the rhs type */
1969             rhst = lval2.e_tptr;
1970
1971             /* Remove pushed value from stack */
1972             RemoveCode (Mark);
1973             pop (TypeOf (lval->e_tptr));
1974
1975             /* Check for pointer arithmetic */
1976             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
1977                 /* Left is pointer, right is int, must scale rhs */
1978                 lval2.e_const *= PSizeOf (lhst);
1979                 /* Operate on pointers, result type is a pointer */
1980                 flags = CF_PTR;
1981             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
1982                 /* Left is int, right is pointer, must scale lhs (ptr only) */
1983                 g_scale (CF_INT | CF_CONST, PSizeOf (rhst));
1984                 /* Operate on pointers, result type is a pointer */
1985                 flags = CF_PTR;
1986                 lval->e_tptr = lval2.e_tptr;
1987             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
1988                 /* Integer addition */
1989                 flags = typeadjust (lval, &lval2, 1);
1990             } else {
1991                 /* OOPS */
1992                 Error ("Invalid operands for binary operator `+'");
1993             }
1994
1995             /* Generate code for the add */
1996             g_inc (flags | CF_CONST, lval2.e_const);
1997
1998             /* Result is in primary register */
1999             lval->e_flags = E_MEXPR;
2000             lval->e_test &= ~E_CC;
2001
2002         } else {
2003
2004             /* lhs and rhs are not constant. Get the rhs type. */
2005             rhst = lval2.e_tptr;
2006
2007             /* Check for pointer arithmetic */
2008             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2009                 /* Left is pointer, right is int, must scale rhs */
2010                 g_scale (CF_INT, PSizeOf (lhst));
2011                 /* Operate on pointers, result type is a pointer */
2012                 flags = CF_PTR;
2013             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2014                 /* Left is int, right is pointer, must scale lhs */
2015                 g_tosint (TypeOf (rhst));       /* Make sure, TOS is int */
2016                 g_swap (CF_INT);                /* Swap TOS and primary */
2017                 g_scale (CF_INT, PSizeOf (rhst));
2018                 /* Operate on pointers, result type is a pointer */
2019                 flags = CF_PTR;
2020                 lval->e_tptr = lval2.e_tptr;
2021             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2022                 /* Integer addition */
2023                 flags = typeadjust (lval, &lval2, 0);
2024             } else {
2025                 /* OOPS */
2026                 Error ("Invalid operands for binary operator `+'");
2027             }
2028
2029             /* Generate code for the add */
2030             g_add (flags, 0);
2031
2032             /* Result is in primary register */
2033             lval->e_flags = E_MEXPR;
2034             lval->e_test &= ~E_CC;
2035
2036         }
2037
2038     }
2039 }
2040
2041
2042
2043 static void parsesub (int k, struct expent* lval)
2044 /* Parse an expression with the binary minus operator. lval contains the
2045  * unprocessed left hand side of the expression and will contain the
2046  * result of the expression on return.
2047  */
2048 {
2049     struct expent lval2;
2050     unsigned flags;             /* Operation flags */
2051     type* lhst;                 /* Type of left hand side */
2052     type* rhst;                 /* Type of right hand side */
2053     CodeMark Mark1;             /* Save position of output queue */
2054     CodeMark Mark2;             /* Another position in the queue */
2055     int rscale;                 /* Scale factor for the result */
2056
2057
2058     /* Skip the MINUS token */
2059     NextToken ();
2060
2061     /* Get the left hand side type, initialize operation flags */
2062     lhst = lval->e_tptr;
2063     flags = 0;
2064     rscale = 1;                 /* Scale by 1, that is, don't scale */
2065
2066     /* Remember the output queue position, then bring the value onto the stack */
2067     Mark1 = GetCodePos ();
2068     exprhs (CF_NONE, k, lval);  /* --> primary register */
2069     Mark2 = GetCodePos ();
2070     g_push (TypeOf (lhst), 0);  /* --> stack */
2071
2072     /* Parse the right hand side */
2073     if (evalexpr (CF_NONE, hie9, &lval2) == 0) {
2074
2075         /* The right hand side is constant. Get the rhs type. */
2076         rhst = lval2.e_tptr;
2077
2078         /* Check left hand side */
2079         if (k == 0 && lval->e_flags & E_MCONST) {
2080
2081             /* Both sides are constant, remove generated code */
2082             RemoveCode (Mark1);
2083             pop (TypeOf (lhst));        /* Clean up the stack */
2084
2085             /* Check for pointer arithmetic */
2086             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2087                 /* Left is pointer, right is int, must scale rhs */
2088                 lval->e_const -= lval2.e_const * PSizeOf (lhst);
2089                 /* Operate on pointers, result type is a pointer */
2090             } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2091                 /* Left is pointer, right is pointer, must scale result */
2092                 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_EQUAL) {
2093                     Error ("Incompatible pointer types");
2094                 } else {
2095                     lval->e_const = (lval->e_const - lval2.e_const) / PSizeOf (lhst);
2096                 }
2097                 /* Operate on pointers, result type is an integer */
2098                 lval->e_tptr = type_int;
2099             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2100                 /* Integer subtraction */
2101                 typeadjust (lval, &lval2, 1);
2102                 lval->e_const -= lval2.e_const;
2103             } else {
2104                 /* OOPS */
2105                 Error ("Invalid operands for binary operator `-'");
2106             }
2107
2108             /* Result is constant, condition codes not set */
2109             lval->e_flags = E_MCONST;
2110             lval->e_test &= ~E_CC;
2111
2112         } else {
2113
2114             /* Left hand side is not constant, right hand side is.
2115              * Remove pushed value from stack.
2116              */
2117             RemoveCode (Mark2);
2118             pop (TypeOf (lhst));
2119
2120             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2121                 /* Left is pointer, right is int, must scale rhs */
2122                 lval2.e_const *= PSizeOf (lhst);
2123                 /* Operate on pointers, result type is a pointer */
2124                 flags = CF_PTR;
2125             } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2126                 /* Left is pointer, right is pointer, must scale result */
2127                 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_EQUAL) {
2128                     Error ("Incompatible pointer types");
2129                 } else {
2130                     rscale = PSizeOf (lhst);
2131                 }
2132                 /* Operate on pointers, result type is an integer */
2133                 flags = CF_PTR;
2134                 lval->e_tptr = type_int;
2135             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2136                 /* Integer subtraction */
2137                 flags = typeadjust (lval, &lval2, 1);
2138             } else {
2139                 /* OOPS */
2140                 Error ("Invalid operands for binary operator `-'");
2141             }
2142
2143             /* Do the subtraction */
2144             g_dec (flags | CF_CONST, lval2.e_const);
2145
2146             /* If this was a pointer subtraction, we must scale the result */
2147             if (rscale != 1) {
2148                 g_scale (flags, -rscale);
2149             }
2150
2151             /* Result is in primary register */
2152             lval->e_flags = E_MEXPR;
2153             lval->e_test &= ~E_CC;
2154
2155         }
2156
2157     } else {
2158
2159         /* Right hand side is not constant. Get the rhs type. */
2160         rhst = lval2.e_tptr;
2161
2162         /* Check for pointer arithmetic */
2163         if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2164             /* Left is pointer, right is int, must scale rhs */
2165             g_scale (CF_INT, PSizeOf (lhst));
2166             /* Operate on pointers, result type is a pointer */
2167             flags = CF_PTR;
2168         } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2169             /* Left is pointer, right is pointer, must scale result */
2170             if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_EQUAL) {
2171                 Error ("Incompatible pointer types");
2172             } else {
2173                 rscale = PSizeOf (lhst);
2174             }
2175             /* Operate on pointers, result type is an integer */
2176             flags = CF_PTR;
2177             lval->e_tptr = type_int;
2178         } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2179             /* Integer subtraction. If the left hand side descriptor says that
2180              * the lhs is const, we have to remove this mark, since this is no
2181              * longer true, lhs is on stack instead.
2182              */
2183             if (lval->e_flags == E_MCONST) {
2184                 lval->e_flags = E_MEXPR;
2185             }
2186             /* Adjust operand types */
2187             flags = typeadjust (lval, &lval2, 0);
2188         } else {
2189             /* OOPS */
2190             Error ("Invalid operands for binary operator `-'");
2191         }
2192
2193         /* Generate code for the sub (the & is a hack here) */
2194         g_sub (flags & ~CF_CONST, 0);
2195
2196         /* If this was a pointer subtraction, we must scale the result */
2197         if (rscale != 1) {
2198             g_scale (flags, -rscale);
2199         }
2200
2201         /* Result is in primary register */
2202         lval->e_flags = E_MEXPR;
2203         lval->e_test &= ~E_CC;
2204     }
2205 }
2206
2207
2208
2209 static int hie8 (struct expent* lval)
2210 /* Process + and - binary operators. */
2211 {
2212     int k = hie9 (lval);
2213     while (curtok == TOK_PLUS || curtok == TOK_MINUS) {
2214
2215         if (curtok == TOK_PLUS) {
2216             parseadd (k, lval);
2217         } else {
2218             parsesub (k, lval);
2219         }
2220         k = 0;
2221     }
2222     return k;
2223 }
2224
2225
2226
2227
2228 static int hie7 (struct expent *lval)
2229 /* Parse << and >>. */
2230 {
2231     static GenDesc* hie7_ops [] = {
2232         &GenASL, &GenASR, 0
2233     };
2234     int UsedGen;
2235
2236     return hie_internal (hie7_ops, lval, hie8, &UsedGen);
2237 }
2238
2239
2240
2241 static int hie6 (struct expent *lval)
2242 /* process greater-than type comparators */
2243 {
2244     static GenDesc* hie6_ops [] = {
2245         &GenLT, &GenLE, &GenGE, &GenGT, 0
2246     };
2247     return hie_compare (hie6_ops, lval, hie7);
2248 }
2249
2250
2251
2252 static int hie5 (struct expent *lval)
2253 {
2254     static GenDesc* hie5_ops[] = {
2255         &GenEQ, &GenNE, 0
2256     };
2257     return hie_compare (hie5_ops, lval, hie6);
2258 }
2259
2260
2261
2262 static int hie4 (struct expent* lval)
2263 /* Handle & (bitwise and) */
2264 {
2265     static GenDesc* hie4_ops [] = {
2266         &GenAND, 0
2267     };
2268     int UsedGen;
2269
2270     return hie_internal (hie4_ops, lval, hie5, &UsedGen);
2271 }
2272
2273
2274
2275 static int hie3 (struct expent *lval)
2276 /* Handle ^ (bitwise exclusive or) */
2277 {
2278     static GenDesc* hie3_ops [] = {
2279         &GenXOR, 0
2280     };
2281     int UsedGen;
2282
2283     return hie_internal (hie3_ops, lval, hie4, &UsedGen);
2284 }
2285
2286
2287
2288 static int hie2 (struct expent *lval)
2289 /* Handle | (bitwise or) */
2290 {
2291     static GenDesc* hie2_ops [] = {
2292         &GenOR, 0
2293     };
2294     int UsedGen;
2295
2296     return hie_internal (hie2_ops, lval, hie3, &UsedGen);
2297 }
2298
2299
2300
2301 static int hieAnd (struct expent* lval, unsigned TrueLab, int* BoolOp)
2302 /* Process "exp && exp" */
2303 {
2304     int k;
2305     int lab;
2306     struct expent lval2;
2307
2308     k = hie2 (lval);
2309     if (curtok == TOK_BOOL_AND) {
2310
2311         /* Tell our caller that we're evaluating a boolean */
2312         *BoolOp = 1;
2313
2314         /* Get a label that we will use for false expressions */
2315         lab = GetLabel ();
2316
2317         /* If the expr hasn't set condition codes, set the force-test flag */
2318         if ((lval->e_test & E_CC) == 0) {
2319             lval->e_test |= E_FORCETEST;
2320         }
2321
2322         /* Load the value */
2323         exprhs (CF_FORCECHAR, k, lval);
2324
2325         /* Generate the jump */
2326         g_falsejump (CF_NONE, lab);
2327
2328         /* Parse more boolean and's */
2329         while (curtok == TOK_BOOL_AND) {
2330
2331             /* Skip the && */
2332             NextToken ();
2333
2334             /* Get rhs */
2335             k = hie2 (&lval2);
2336             if ((lval2.e_test & E_CC) == 0) {
2337                 lval2.e_test |= E_FORCETEST;
2338             }
2339             exprhs (CF_FORCECHAR, k, &lval2);
2340
2341             /* Do short circuit evaluation */
2342             if (curtok == TOK_BOOL_AND) {
2343                 g_falsejump (CF_NONE, lab);
2344             } else {
2345                 /* Last expression - will evaluate to true */
2346                 g_truejump (CF_NONE, TrueLab);
2347             }
2348         }
2349
2350         /* Define the false jump label here */
2351         g_defloclabel (lab);
2352
2353         /* Define the label */
2354         lval->e_flags = E_MEXPR;
2355         lval->e_test |= E_CC;   /* Condition codes are set */
2356         k = 0;
2357     }
2358     return k;
2359 }
2360
2361
2362
2363 static int hieOr (struct expent *lval)
2364 /* Process "exp || exp". */
2365 {
2366     int k;
2367     struct expent lval2;
2368     int BoolOp = 0;             /* Did we have a boolean op? */
2369     int AndOp;                  /* Did we have a && operation? */
2370     unsigned TrueLab;           /* Jump to this label if true */
2371     unsigned DoneLab;
2372
2373     /* Get a label */
2374     TrueLab = GetLabel ();
2375
2376     /* Call the next level parser */
2377     k = hieAnd (lval, TrueLab, &BoolOp);
2378
2379     /* Any boolean or's? */
2380     if (curtok == TOK_BOOL_OR) {
2381
2382         /* If the expr hasn't set condition codes, set the force-test flag */
2383         if ((lval->e_test & E_CC) == 0) {
2384             lval->e_test |= E_FORCETEST;
2385         }
2386
2387         /* Get first expr */
2388         exprhs (CF_FORCECHAR, k, lval);
2389
2390         /* For each expression jump to TrueLab if true. Beware: If we
2391          * had && operators, the jump is already in place!
2392          */
2393         if (!BoolOp) {
2394             g_truejump (CF_NONE, TrueLab);
2395         }
2396
2397         /* Remember that we had a boolean op */
2398         BoolOp = 1;
2399
2400         /* while there's more expr */
2401         while (curtok == TOK_BOOL_OR) {
2402
2403             /* skip the || */
2404             NextToken ();
2405
2406             /* Get a subexpr */
2407             AndOp = 0;
2408             k = hieAnd (&lval2, TrueLab, &AndOp);
2409             if ((lval2.e_test & E_CC) == 0) {
2410                 lval2.e_test |= E_FORCETEST;
2411             }
2412             exprhs (CF_FORCECHAR, k, &lval2);
2413
2414             /* If there is more to come, add shortcut boolean eval.
2415              * Beware: If we had && operators, the jump is already
2416              * in place!
2417              */
2418 #if     0
2419 /* Seems this sometimes generates wrong code */
2420             if (curtok == TOK_BOOL_OR && !AndOp) {
2421                 g_truejump (CF_NONE, TrueLab);
2422             }
2423 #else
2424             g_truejump (CF_NONE, TrueLab);
2425 #endif
2426         }
2427         lval->e_flags = E_MEXPR;
2428         lval->e_test |= E_CC;                   /* Condition codes are set */
2429         k = 0;
2430     }
2431
2432     /* If we really had boolean ops, generate the end sequence */
2433     if (BoolOp) {
2434         DoneLab = GetLabel ();
2435         g_getimmed (CF_INT | CF_CONST, 0, 0);   /* Load FALSE */
2436         g_falsejump (CF_NONE, DoneLab);
2437         g_defloclabel (TrueLab);
2438         g_getimmed (CF_INT | CF_CONST, 1, 0);   /* Load TRUE */
2439         g_defloclabel (DoneLab);
2440     }
2441     return k;
2442 }
2443
2444
2445
2446 static int hieQuest (struct expent *lval)
2447 /* Parse "lvalue ? exp : exp" */
2448 {
2449     int k;
2450     int labf;
2451     int labt;
2452     struct expent lval2;        /* Expression 2 */
2453     struct expent lval3;        /* Expression 3 */
2454     type* type2;                /* Type of expression 2 */
2455     type* type3;                /* Type of expression 3 */
2456     type* rtype;                /* Type of result */
2457     CodeMark Mark1;             /* Save position in output code */
2458     CodeMark Mark2;             /* Save position in output code */
2459
2460
2461
2462     k = hieOr (lval);
2463     if (curtok == TOK_QUEST) {
2464         NextToken ();
2465         if ((lval->e_test & E_CC) == 0) {
2466             /* Condition codes not set, force a test */
2467             lval->e_test |= E_FORCETEST;
2468         }
2469         exprhs (CF_NONE, k, lval);
2470         labf = GetLabel ();
2471         g_falsejump (CF_NONE, labf);
2472
2473         /* Parse second and third expression */
2474         expression1 (&lval2);
2475         labt = GetLabel ();
2476         ConsumeColon ();
2477         g_jump (labt);
2478         g_defloclabel (labf);
2479         expression1 (&lval3);
2480
2481         /* Check if any conversions are needed, if so, do them.
2482          * Conversion rules for ?: expression are:
2483          *   - if both expressions are int expressions, default promotion
2484          *     rules for ints apply.
2485          *   - if both expressions are pointers of the same type, the
2486          *     result of the expression is of this type.
2487          *   - if one of the expressions is a pointer and the other is
2488          *     a zero constant, the resulting type is that of the pointer
2489          *     type.
2490          *   - all other cases are flagged by an error.
2491          */
2492         type2 = lval2.e_tptr;
2493         type3 = lval3.e_tptr;
2494         if (IsClassInt (type2) && IsClassInt (type3)) {
2495
2496             /* Get common type */
2497             rtype = promoteint (type2, type3);
2498
2499             /* Convert the third expression to this type if needed */
2500             g_typecast (TypeOf (rtype), TypeOf (type3));
2501
2502             /* Setup a new label so that the expr3 code will jump around
2503              * the type cast code for expr2.
2504              */
2505             labf = GetLabel ();         /* Get new label */
2506             Mark1 = GetCodePos ();      /* Remember current position */
2507             g_jump (labf);              /* Jump around code */
2508
2509             /* The jump for expr2 goes here */
2510             g_defloclabel (labt);
2511
2512             /* Create the typecast code for expr2 */
2513             Mark2 = GetCodePos ();      /* Remember position */
2514             g_typecast (TypeOf (rtype), TypeOf (type2));
2515
2516             /* If the typecast did not produce code, remove the jump,
2517              * otherwise output the label.
2518              */
2519             if (GetCodePos() == Mark2) {
2520                 RemoveCode (Mark1);     /* Remove code */
2521             } else {
2522                 /* We have typecast code, output label */
2523                 g_defloclabel (labf);
2524                 labt = 0;               /* Mark other label as invalid */
2525             }
2526
2527         } else if (IsClassPtr (type2) && IsClassPtr (type3)) {
2528             /* Must point to same type */
2529             if (TypeCmp (Indirect (type2), Indirect (type3)) < TC_EQUAL) {
2530                 Error ("Incompatible pointer types");
2531             }
2532             /* Result has the common type */
2533             rtype = lval2.e_tptr;
2534         } else if (IsClassPtr (type2) && IsNullPtr (&lval3)) {
2535             /* Result type is pointer, no cast needed */
2536             rtype = lval2.e_tptr;
2537         } else if (IsNullPtr (&lval2) && IsClassPtr (type3)) {
2538             /* Result type is pointer, no cast needed */
2539             rtype = lval3.e_tptr;
2540         } else {
2541             Error ("Incompatible types");
2542             rtype = lval2.e_tptr;               /* Doesn't matter here */
2543         }
2544
2545         /* If we don't have the label defined until now, do it */
2546         if (labt) {
2547             g_defloclabel (labt);
2548         }
2549
2550         /* Setup the target expression */
2551         lval->e_flags = E_MEXPR;
2552         lval->e_tptr = rtype;
2553         k = 0;
2554     }
2555     return k;
2556 }
2557
2558
2559
2560 static void opeq (GenDesc* Gen, struct expent *lval, int k)
2561 /* Process "op=" operators. */
2562 {
2563     struct expent lval2;
2564     unsigned flags;
2565     CodeMark Mark;
2566     int MustScale;
2567
2568     NextToken ();
2569     if (k == 0) {
2570         Error ("Invalid lvalue in assignment");
2571         return;
2572     }
2573
2574     /* Determine the type of the lhs */
2575     flags = TypeOf (lval->e_tptr);
2576     MustScale = (Gen->Func == g_add || Gen->Func == g_sub) &&
2577                 lval->e_tptr [0] == T_PTR;
2578
2579     /* Get the lhs address on stack (if needed) */
2580     PushAddr (lval);
2581
2582     /* Fetch the lhs into the primary register if needed */
2583     exprhs (CF_NONE, k, lval);
2584
2585     /* Bring the lhs on stack */
2586     Mark = GetCodePos ();
2587     g_push (flags, 0);
2588
2589     /* Evaluate the rhs */
2590     if (evalexpr (CF_NONE, hie1, &lval2) == 0) {
2591         /* The resulting value is a constant. If the generator has the NOPUSH
2592          * flag set, don't push the lhs.
2593          */
2594         if (Gen->Flags & GEN_NOPUSH) {
2595             RemoveCode (Mark);
2596             pop (flags);
2597         }
2598         if (MustScale) {
2599             /* lhs is a pointer, scale rhs */
2600             lval2.e_const *= SizeOf (lval->e_tptr+1);
2601         }
2602
2603         /* If the lhs is character sized, the operation may be later done
2604          * with characters.
2605          */
2606         if (SizeOf (lval->e_tptr) == 1) {
2607             flags |= CF_FORCECHAR;
2608         }
2609
2610         /* Special handling for add and sub - some sort of a hack, but short code */
2611         if (Gen->Func == g_add) {
2612             g_inc (flags | CF_CONST, lval2.e_const);
2613         } else if (Gen->Func == g_sub) {
2614             g_dec (flags | CF_CONST, lval2.e_const);
2615         } else {
2616             Gen->Func (flags | CF_CONST, lval2.e_const);
2617         }
2618     } else {
2619         /* rhs is not constant and already in the primary register */
2620         if (MustScale) {
2621             /* lhs is a pointer, scale rhs */
2622             g_scale (TypeOf (lval2.e_tptr), SizeOf (lval->e_tptr+1));
2623         }
2624
2625         /* If the lhs is character sized, the operation may be later done
2626          * with characters.
2627          */
2628         if (SizeOf (lval->e_tptr) == 1) {
2629             flags |= CF_FORCECHAR;
2630         }
2631
2632         /* Adjust the types of the operands if needed */
2633         Gen->Func (g_typeadjust (flags, TypeOf (lval2.e_tptr)), 0);
2634     }
2635     store (lval);
2636     lval->e_flags = E_MEXPR;
2637 }
2638
2639
2640
2641 static void addsubeq (GenDesc* Gen, struct expent *lval, int k)
2642 /* Process the += and -= operators */
2643 {
2644     struct expent lval2;
2645     unsigned flags;
2646     int MustScale;
2647
2648
2649     if (k == 0) {
2650         Error ("Invalid lvalue in assignment");
2651         return;
2652     }
2653
2654
2655     /* We're currently only able to handle some adressing modes */
2656     if ((lval->e_flags & E_MGLOBAL) == 0 &&     /* Global address? */
2657         (lval->e_flags & E_MLOCAL) == 0  &&     /* Local address? */
2658         (lval->e_flags & E_MCONST) == 0) {      /* Constant address? */
2659         /* Use generic routine */
2660         opeq (Gen, lval, k);
2661         return;
2662     }
2663
2664     /* Skip the operator */
2665     NextToken ();
2666
2667     /* Check if we have a pointer expression and must scale rhs */
2668     MustScale = (lval->e_tptr [0] == T_PTR);
2669
2670     /* Determine the code generator flags */
2671     flags = TypeOf (lval->e_tptr) | CF_FORCECHAR;
2672
2673     /* Evaluate the rhs */
2674     if (evalexpr (CF_NONE, hie1, &lval2) == 0) {
2675         /* The resulting value is a constant. */
2676         if (MustScale) {
2677             /* lhs is a pointer, scale rhs */
2678             lval2.e_const *= SizeOf (lval->e_tptr+1);
2679         }
2680         flags |= CF_CONST;
2681     } else {
2682         /* rhs is not constant and already in the primary register */
2683         if (MustScale) {
2684             /* lhs is a pointer, scale rhs */
2685             g_scale (TypeOf (lval2.e_tptr), SizeOf (lval->e_tptr+1));
2686         }
2687     }
2688
2689     /* Adjust the rhs to the lhs */
2690     g_typeadjust (flags, TypeOf (lval2.e_tptr));
2691
2692     /* Output apropriate code */
2693     if (lval->e_flags & E_MGLOBAL) {
2694         /* Static variable */
2695         flags |= GlobalModeFlags (lval->e_flags);
2696         if (Gen->Tok == TOK_PLUS_ASSIGN) {
2697             g_addeqstatic (flags, lval->e_name, lval->e_const, lval2.e_const);
2698         } else {
2699             g_subeqstatic (flags, lval->e_name, lval->e_const, lval2.e_const);
2700         }
2701     } else if (lval->e_flags & E_MLOCAL) {
2702         /* ref to localvar */
2703         if (Gen->Tok == TOK_PLUS_ASSIGN) {
2704             g_addeqlocal (flags, lval->e_const, lval2.e_const);
2705         } else {
2706             g_subeqlocal (flags, lval->e_const, lval2.e_const);
2707         }
2708     } else if (lval->e_flags & E_MCONST) {
2709         /* ref to absolute address */
2710         flags |= CF_ABSOLUTE;
2711         if (Gen->Tok == TOK_PLUS_ASSIGN) {
2712             g_addeqstatic (flags, lval->e_const, 0, lval2.e_const);
2713         } else {
2714             g_subeqstatic (flags, lval->e_const, 0, lval2.e_const);
2715         }
2716     } else if (lval->e_flags & E_MEXPR) {
2717         /* Address in a/x. */
2718         if (Gen->Tok == TOK_PLUS_ASSIGN) {
2719             g_addeqind (flags, lval->e_const, lval2.e_const);
2720         } else {
2721             g_subeqind (flags, lval->e_const, lval2.e_const);
2722         }
2723     } else {
2724         Internal ("Invalid addressing mode");
2725     }
2726
2727     /* Expression is in the primary now */
2728     lval->e_flags = E_MEXPR;
2729 }
2730
2731
2732
2733 static void Assignment (struct expent* lval)
2734 /* Parse an assignment */
2735 {
2736     int k;
2737     struct expent lval2;
2738     unsigned flags;
2739     type* ltype = lval->e_tptr;
2740
2741     /* Check for assignment to const */
2742     if (IsQualConst (ltype)) {
2743         Error ("Assignment to const");
2744     }
2745
2746     /* cc65 does not have full support for handling structs by value. Since
2747      * assigning structs is one of the more useful operations from this
2748      * familiy, allow it here.
2749      */
2750     if (IsClassStruct (ltype)) {
2751
2752         /* Bring the address of the lhs into the primary and push it */
2753         exprhs (0, 0, lval);
2754         g_push (CF_PTR | CF_UNSIGNED, 0);
2755
2756         /* Get the expression on the right of the '=' into the primary */
2757         k = hie1 (&lval2);
2758         if (k) {
2759             /* Get the address */
2760             exprhs (0, 0, &lval2);
2761         } else {
2762             /* We need an lvalue */
2763             Error ("Invalid lvalue in assignment");
2764         }
2765
2766         /* Push the address (or whatever is in ax in case of errors) */
2767         g_push (CF_PTR | CF_UNSIGNED, 0);
2768
2769         /* Check for equality of the structs */
2770         if (TypeCmp (ltype, lval2.e_tptr) < TC_EQUAL) {
2771             Error ("Incompatible types");
2772         }
2773
2774         /* Load the size of the struct into the primary */
2775         g_getimmed (CF_INT | CF_UNSIGNED | CF_CONST, SizeOf (ltype), 0);
2776
2777         /* Call the memcpy function */
2778         g_call (CF_FIXARGC, "memcpy", 4);
2779
2780     } else {
2781
2782         /* Get the address on stack if needed */
2783         PushAddr (lval);
2784
2785         /* No struct, setup flags for the load */
2786         flags = SizeOf (ltype) == 1? CF_FORCECHAR : CF_NONE;
2787
2788         /* Get the expression on the right of the '=' into the primary */
2789         if (evalexpr (flags, hie1, &lval2) == 0) {
2790             /* Constant expression. Adjust the types */
2791             assignadjust (ltype, &lval2);
2792             /* Put the value into the primary register */
2793             lconst (flags, &lval2);
2794         } else {
2795             /* Expression is not constant and already in the primary */
2796             assignadjust (ltype, &lval2);
2797         }
2798
2799         /* Generate a store instruction */
2800         store (lval);
2801
2802     }
2803
2804     /* Value is still in primary */
2805     lval->e_flags = E_MEXPR;
2806 }
2807
2808
2809
2810 int hie1 (struct expent* lval)
2811 /* Parse first level of expression hierarchy. */
2812 {
2813     int k;
2814
2815     k = hieQuest (lval);
2816     switch (curtok) {
2817
2818         case TOK_RPAREN:
2819         case TOK_SEMI:
2820             return k;
2821
2822         case TOK_ASSIGN:
2823             NextToken ();
2824             if (k == 0) {
2825                 Error ("Invalid lvalue in assignment");
2826             } else {
2827                 Assignment (lval);
2828             }
2829             break;
2830
2831         case TOK_PLUS_ASSIGN:
2832             addsubeq (&GenPASGN, lval, k);
2833             break;
2834
2835         case TOK_MINUS_ASSIGN:
2836             addsubeq (&GenSASGN, lval, k);
2837             break;
2838
2839         case TOK_MUL_ASSIGN:
2840             opeq (&GenMASGN, lval, k);
2841             break;
2842
2843         case TOK_DIV_ASSIGN:
2844             opeq (&GenDASGN, lval, k);
2845             break;
2846
2847         case TOK_MOD_ASSIGN:
2848             opeq (&GenMOASGN, lval, k);
2849             break;
2850
2851         case TOK_SHL_ASSIGN:
2852             opeq (&GenSLASGN, lval, k);
2853             break;
2854
2855         case TOK_SHR_ASSIGN:
2856             opeq (&GenSRASGN, lval, k);
2857             break;
2858
2859         case TOK_AND_ASSIGN:
2860             opeq (&GenAASGN, lval, k);
2861             break;
2862
2863         case TOK_XOR_ASSIGN:
2864             opeq (&GenXOASGN, lval, k);
2865             break;
2866
2867         case TOK_OR_ASSIGN:
2868             opeq (&GenOASGN, lval, k);
2869             break;
2870
2871         default:
2872             return k;
2873     }
2874     return 0;
2875 }
2876
2877
2878
2879 int hie0 (struct expent *lval)
2880 /* Parse comma operator. */
2881 {
2882     int k;
2883
2884     k = hie1 (lval);
2885     while (curtok == TOK_COMMA) {
2886         NextToken ();
2887         k = hie1 (lval);
2888     }
2889     return k;
2890 }
2891
2892
2893
2894 int evalexpr (unsigned flags, int (*f) (struct expent*), struct expent* lval)
2895 /* Will evaluate an expression via the given function. If the result is a
2896  * constant, 0 is returned and the value is put in the lval struct. If the
2897  * result is not constant, exprhs is called to bring the value into the
2898  * primary register and 1 is returned.
2899  */
2900 {
2901     int k;
2902
2903     /* Evaluate */
2904     k = f (lval);
2905     if (k == 0 && lval->e_flags == E_MCONST) {
2906         /* Constant expression */
2907         return 0;
2908     } else {
2909         /* Not constant, load into the primary */
2910         exprhs (flags, k, lval);
2911         return 1;
2912     }
2913 }
2914
2915
2916
2917 int expr (int (*func) (), struct expent *lval)
2918 /* Expression parser; func is either hie0 or hie1. */
2919 {
2920     int k;
2921     int savsp;
2922
2923     savsp = oursp;
2924
2925     k = (*func) (lval);
2926
2927     /* Do some checks if code generation is still constistent */
2928     if (savsp != oursp) {
2929         if (Debug) {
2930             fprintf (stderr, "oursp != savesp (%d != %d)\n", oursp, savsp);
2931         } else {
2932             Internal ("oursp != savsp (%d != %d)", oursp, savsp);
2933         }
2934     }
2935     return k;
2936 }
2937
2938
2939
2940 void expression1 (struct expent* lval)
2941 /* Evaluate an expression on level 1 (no comma operator) and put it into
2942  * the primary register
2943  */
2944 {
2945     memset (lval, 0, sizeof (*lval));
2946     exprhs (CF_NONE, expr (hie1, lval), lval);
2947 }
2948
2949
2950
2951 void expression (struct expent* lval)
2952 /* Evaluate an expression and put it into the primary register */
2953 {
2954     memset (lval, 0, sizeof (*lval));
2955     exprhs (CF_NONE, expr (hie0, lval), lval);
2956 }
2957
2958
2959
2960 void constexpr (struct expent* lval)
2961 /* Get a constant value */
2962 {
2963     memset (lval, 0, sizeof (*lval));
2964     if (expr (hie1, lval) != 0 || (lval->e_flags & E_MCONST) == 0) {
2965         Error ("Constant expression expected");
2966         /* To avoid any compiler errors, make the expression a valid const */
2967         lval->e_flags = E_MCONST;
2968         lval->e_tptr = type_int;
2969         lval->e_const = 0;
2970     }
2971 }
2972
2973
2974
2975 void intexpr (struct expent* lval)
2976 /* Get an integer expression */
2977 {
2978     expression (lval);
2979     if (!IsClassInt (lval->e_tptr)) {
2980         Error ("Integer expression expected");
2981         /* To avoid any compiler errors, make the expression a valid int */
2982         lval->e_flags = E_MCONST;
2983         lval->e_tptr = type_int;
2984         lval->e_const = 0;
2985     }
2986 }
2987
2988
2989
2990 void boolexpr (struct expent* lval)
2991 /* Get a boolean expression */
2992 {
2993     /* Read an expression */
2994     expression (lval);
2995
2996     /* If it's an integer, it's ok. If it's not an integer, but a pointer,
2997      * the pointer used in a boolean context is also ok
2998      */
2999     if (!IsClassInt (lval->e_tptr) && !IsClassPtr (lval->e_tptr)) {
3000         Error ("Boolean expression expected");
3001         /* To avoid any compiler errors, make the expression a valid int */
3002         lval->e_flags = E_MCONST;
3003         lval->e_tptr = type_int;
3004         lval->e_const = 0;
3005     }
3006 }
3007
3008
3009
3010 void test (unsigned label, int cond)
3011 /* Generate code to perform test and jump if false. */
3012 {
3013     int k;
3014     struct expent lval;
3015
3016     /* Eat the parenthesis */
3017     ConsumeLParen ();
3018
3019     /* Prepare the expression, setup labels */
3020     memset (&lval, 0, sizeof (lval));
3021
3022     /* Generate code to eval the expr */
3023     k = expr (hie0, &lval);
3024     if (k == 0 && lval.e_flags == E_MCONST) {
3025         /* Constant rvalue */
3026         if (cond == 0 && lval.e_const == 0) {
3027             g_jump (label);
3028             Warning ("Unreachable code");
3029         } else if (cond && lval.e_const) {
3030             g_jump (label);
3031         }
3032         ConsumeRParen ();
3033         return;
3034     }
3035
3036     /* If the expr hasn't set condition codes, set the force-test flag */
3037     if ((lval.e_test & E_CC) == 0) {
3038         lval.e_test |= E_FORCETEST;
3039     }
3040
3041     /* Load the value into the primary register */
3042     exprhs (CF_FORCECHAR, k, &lval);
3043
3044     /* Check for the closing brace */
3045     ConsumeRParen ();
3046
3047     /* Generate the jump */
3048     if (cond) {
3049         g_truejump (CF_NONE, label);
3050     } else {
3051         /* Special case (putting this here is a small hack - but hey, the
3052          * compiler itself is one big hack...): If a semicolon follows, we
3053          * don't have a statement and may omit the jump.
3054          */
3055         if (curtok != TOK_SEMI) {
3056             g_falsejump (CF_NONE, label);
3057         }
3058     }
3059 }
3060
3061
3062
3063