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