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