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