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