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