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