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