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