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