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