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