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