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