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