]> git.sur5r.net Git - cc65/blob - src/cc65/expr.c
Create one literal pool per function, so that literal pool data is removed
[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 && SymHasAttr (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  = GetLiteralPoolLabel ();
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         /* Make the expression an integer at address zero */
1101         ED_MakeConstAbs (Expr, 0, type_int);
1102         return;
1103     }
1104
1105     /* Get the symbol table entry and check for a struct field */
1106     strcpy (Ident, CurTok.Ident);
1107     NextToken ();
1108     Field = FindStructField (Expr->Type, Ident);
1109     if (Field == 0) {
1110         Error ("Struct/union has no field named `%s'", Ident);
1111         /* Make the expression an integer at address zero */
1112         ED_MakeConstAbs (Expr, 0, type_int);
1113         return;
1114     }
1115
1116     /* If we have a struct pointer that is an lvalue and not already in the
1117      * primary, load it now.
1118      */
1119     if (ED_IsLVal (Expr) && IsTypePtr (Expr->Type)) {
1120
1121         /* Load into the primary */
1122         LoadExpr (CF_NONE, Expr);
1123
1124         /* Make it an lvalue expression */
1125         ED_MakeLValExpr (Expr);
1126     }
1127
1128     /* Set the struct field offset */
1129     Expr->IVal += Field->V.Offs;
1130
1131     /* The type is the type of the field plus any qualifiers from the struct */
1132     if (IsClassStruct (Expr->Type)) {
1133         Q = GetQualifier (Expr->Type);
1134     } else {
1135         Q = GetQualifier (Indirect (Expr->Type));
1136     }
1137     if (GetQualifier (Field->Type) == (GetQualifier (Field->Type) | Q)) {
1138         Expr->Type = Field->Type;
1139     } else {
1140         Expr->Type = TypeDup (Field->Type);
1141         Expr->Type->C |= Q;
1142     }
1143
1144     /* An struct member is actually a variable. So the rules for variables
1145      * with respect to the reference type apply: If it's an array, it is
1146      * a rvalue, otherwise it's an lvalue. (A function would also be a rvalue,
1147      * but a struct field cannot be a function).
1148      */
1149     if (IsTypeArray (Expr->Type)) {
1150         ED_MakeRVal (Expr);
1151     } else {
1152         ED_MakeLVal (Expr);
1153     }
1154
1155     /* Make the expression a bit field if necessary */
1156     if (SymIsBitField (Field)) {
1157         ED_MakeBitField (Expr, Field->V.B.BitOffs, Field->V.B.BitWidth);
1158     }
1159 }
1160
1161
1162
1163 static void hie11 (ExprDesc *Expr)
1164 /* Handle compound types (structs and arrays) */
1165 {
1166     /* Name value used in invalid function calls */
1167     static const char IllegalFunc[] = "illegal_function_call";
1168
1169     /* Evaluate the lhs */
1170     Primary (Expr);
1171
1172     /* Check for a rhs */
1173     while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN ||
1174            CurTok.Tok == TOK_DOT    || CurTok.Tok == TOK_PTR_REF) {
1175
1176         switch (CurTok.Tok) {
1177
1178             case TOK_LBRACK:
1179                 /* Array reference */
1180                 ArrayRef (Expr);
1181                 break;
1182
1183             case TOK_LPAREN:
1184                 /* Function call. */
1185                 if (!IsTypeFunc (Expr->Type) && !IsTypeFuncPtr (Expr->Type)) {
1186                     /* Not a function */
1187                     Error ("Illegal function call");
1188                     /* Force the type to be a implicitly defined function, one
1189                      * returning an int and taking any number of arguments.
1190                      * Since we don't have a name, invent one.
1191                      */
1192                     ED_MakeConstAbs (Expr, 0, GetImplicitFuncType ());
1193                     Expr->Name = (long) IllegalFunc;
1194                 }
1195                 /* Call the function */
1196                 FunctionCall (Expr);
1197                 break;
1198
1199             case TOK_DOT:
1200                 if (!IsClassStruct (Expr->Type)) {
1201                     Error ("Struct expected");
1202                 }
1203                 StructRef (Expr);
1204                 break;
1205
1206             case TOK_PTR_REF:
1207                 /* If we have an array, convert it to pointer to first element */
1208                 if (IsTypeArray (Expr->Type)) {
1209                     Expr->Type = ArrayToPtr (Expr->Type);
1210                 }
1211                 if (!IsClassPtr (Expr->Type) || !IsClassStruct (Indirect (Expr->Type))) {
1212                     Error ("Struct pointer expected");
1213                 }
1214                 StructRef (Expr);
1215                 break;
1216
1217             default:
1218                 Internal ("Invalid token in hie11: %d", CurTok.Tok);
1219
1220         }
1221     }
1222 }
1223
1224
1225
1226 void Store (ExprDesc* Expr, const Type* StoreType)
1227 /* Store the primary register into the location denoted by Expr. If StoreType
1228  * is given, use this type when storing instead of Expr->Type. If StoreType
1229  * is NULL, use Expr->Type instead.
1230  */
1231 {
1232     unsigned Flags;
1233
1234     /* If StoreType was not given, use Expr->Type instead */
1235     if (StoreType == 0) {
1236         StoreType = Expr->Type;
1237     }
1238
1239     /* Prepare the code generator flags */
1240     Flags = TypeOf (StoreType) | GlobalModeFlags (Expr);
1241
1242     /* Do the store depending on the location */
1243     switch (ED_GetLoc (Expr)) {
1244
1245         case E_LOC_ABS:
1246             /* Absolute: numeric address or const */
1247             g_putstatic (Flags, Expr->IVal, 0);
1248             break;
1249
1250         case E_LOC_GLOBAL:
1251             /* Global variable */
1252             g_putstatic (Flags, Expr->Name, Expr->IVal);
1253             break;
1254
1255         case E_LOC_STATIC:
1256         case E_LOC_LITERAL:
1257             /* Static variable or literal in the literal pool */
1258             g_putstatic (Flags, Expr->Name, Expr->IVal);
1259             break;
1260
1261         case E_LOC_REGISTER:
1262             /* Register variable */
1263             g_putstatic (Flags, Expr->Name, Expr->IVal);
1264             break;
1265
1266         case E_LOC_STACK:
1267             /* Value on the stack */
1268             g_putlocal (Flags, Expr->IVal, 0);
1269             break;
1270
1271         case E_LOC_PRIMARY:
1272             /* The primary register (value is already there) */
1273             break;
1274
1275         case E_LOC_EXPR:
1276             /* An expression in the primary register */
1277             g_putind (Flags, Expr->IVal);
1278             break;
1279
1280         default:
1281             Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
1282     }
1283
1284     /* Assume that each one of the stores will invalidate CC */
1285     ED_MarkAsUntested (Expr);
1286 }
1287
1288
1289
1290 static void PreInc (ExprDesc* Expr)
1291 /* Handle the preincrement operators */
1292 {
1293     unsigned Flags;
1294     unsigned long Val;
1295
1296     /* Skip the operator token */
1297     NextToken ();
1298
1299     /* Evaluate the expression and check that it is an lvalue */
1300     hie10 (Expr);
1301     if (!ED_IsLVal (Expr)) {
1302         Error ("Invalid lvalue");
1303         return;
1304     }
1305
1306     /* We cannot modify const values */
1307     if (IsQualConst (Expr->Type)) {
1308         Error ("Increment of read-only variable");
1309     }
1310
1311     /* Get the data type */
1312     Flags = TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR | CF_CONST;
1313
1314     /* Get the increment value in bytes */
1315     Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1316
1317     /* Check the location of the data */
1318     switch (ED_GetLoc (Expr)) {
1319
1320         case E_LOC_ABS:
1321             /* Absolute: numeric address or const */
1322             g_addeqstatic (Flags, Expr->IVal, 0, Val);
1323             break;
1324
1325         case E_LOC_GLOBAL:
1326             /* Global variable */
1327             g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1328             break;
1329
1330         case E_LOC_STATIC:
1331         case E_LOC_LITERAL:
1332             /* Static variable or literal in the literal pool */
1333             g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1334             break;
1335
1336         case E_LOC_REGISTER:
1337             /* Register variable */
1338             g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1339             break;
1340
1341         case E_LOC_STACK:
1342             /* Value on the stack */
1343             g_addeqlocal (Flags, Expr->IVal, Val);
1344             break;
1345
1346         case E_LOC_PRIMARY:
1347             /* The primary register */
1348             g_inc (Flags, Val);
1349             break;
1350
1351         case E_LOC_EXPR:
1352             /* An expression in the primary register */
1353             g_addeqind (Flags, Expr->IVal, Val);
1354             break;
1355
1356         default:
1357             Internal ("Invalid location in PreInc(): 0x%04X", ED_GetLoc (Expr));
1358     }
1359
1360     /* Result is an expression, no reference */
1361     ED_MakeRValExpr (Expr);
1362 }
1363
1364
1365
1366 static void PreDec (ExprDesc* Expr)
1367 /* Handle the predecrement operators */
1368 {
1369     unsigned Flags;
1370     unsigned long Val;
1371
1372     /* Skip the operator token */
1373     NextToken ();
1374
1375     /* Evaluate the expression and check that it is an lvalue */
1376     hie10 (Expr);
1377     if (!ED_IsLVal (Expr)) {
1378         Error ("Invalid lvalue");
1379         return;
1380     }
1381
1382     /* We cannot modify const values */
1383     if (IsQualConst (Expr->Type)) {
1384         Error ("Decrement of read-only variable");
1385     }
1386
1387     /* Get the data type */
1388     Flags = TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR | CF_CONST;
1389
1390     /* Get the increment value in bytes */
1391     Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1392
1393     /* Check the location of the data */
1394     switch (ED_GetLoc (Expr)) {
1395
1396         case E_LOC_ABS:
1397             /* Absolute: numeric address or const */
1398             g_subeqstatic (Flags, Expr->IVal, 0, Val);
1399             break;
1400
1401         case E_LOC_GLOBAL:
1402             /* Global variable */
1403             g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1404             break;
1405
1406         case E_LOC_STATIC:
1407         case E_LOC_LITERAL:
1408             /* Static variable or literal in the literal pool */
1409             g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1410             break;
1411
1412         case E_LOC_REGISTER:
1413             /* Register variable */
1414             g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1415             break;
1416
1417         case E_LOC_STACK:
1418             /* Value on the stack */
1419             g_subeqlocal (Flags, Expr->IVal, Val);
1420             break;
1421
1422         case E_LOC_PRIMARY:
1423             /* The primary register */
1424             g_inc (Flags, Val);
1425             break;
1426
1427         case E_LOC_EXPR:
1428             /* An expression in the primary register */
1429             g_subeqind (Flags, Expr->IVal, Val);
1430             break;
1431
1432         default:
1433             Internal ("Invalid location in PreDec(): 0x%04X", ED_GetLoc (Expr));
1434     }
1435
1436     /* Result is an expression, no reference */
1437     ED_MakeRValExpr (Expr);
1438 }
1439
1440
1441
1442 static void PostInc (ExprDesc* Expr)
1443 /* Handle the postincrement operator */
1444 {
1445     unsigned Flags;
1446
1447     NextToken ();
1448
1449     /* The expression to increment must be an lvalue */
1450     if (!ED_IsLVal (Expr)) {
1451         Error ("Invalid lvalue");
1452         return;
1453     }
1454
1455     /* We cannot modify const values */
1456     if (IsQualConst (Expr->Type)) {
1457         Error ("Increment of read-only variable");
1458     }
1459
1460     /* Get the data type */
1461     Flags = TypeOf (Expr->Type);
1462
1463     /* Push the address if needed */
1464     PushAddr (Expr);
1465
1466     /* Fetch the value and save it (since it's the result of the expression) */
1467     LoadExpr (CF_NONE, Expr);
1468     g_save (Flags | CF_FORCECHAR);
1469
1470     /* If we have a pointer expression, increment by the size of the type */
1471     if (IsTypePtr (Expr->Type)) {
1472         g_inc (Flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (Expr->Type + 1));
1473     } else {
1474         g_inc (Flags | CF_CONST | CF_FORCECHAR, 1);
1475     }
1476
1477     /* Store the result back */
1478     Store (Expr, 0);
1479
1480     /* Restore the original value in the primary register */
1481     g_restore (Flags | CF_FORCECHAR);
1482
1483     /* The result is always an expression, no reference */
1484     ED_MakeRValExpr (Expr);
1485 }
1486
1487
1488
1489 static void PostDec (ExprDesc* Expr)
1490 /* Handle the postdecrement operator */
1491 {
1492     unsigned Flags;
1493
1494     NextToken ();
1495
1496     /* The expression to increment must be an lvalue */
1497     if (!ED_IsLVal (Expr)) {
1498         Error ("Invalid lvalue");
1499         return;
1500     }
1501
1502     /* We cannot modify const values */
1503     if (IsQualConst (Expr->Type)) {
1504         Error ("Decrement of read-only variable");
1505     }
1506
1507     /* Get the data type */
1508     Flags = TypeOf (Expr->Type);
1509
1510     /* Push the address if needed */
1511     PushAddr (Expr);
1512
1513     /* Fetch the value and save it (since it's the result of the expression) */
1514     LoadExpr (CF_NONE, Expr);
1515     g_save (Flags | CF_FORCECHAR);
1516
1517     /* If we have a pointer expression, increment by the size of the type */
1518     if (IsTypePtr (Expr->Type)) {
1519         g_dec (Flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (Expr->Type + 1));
1520     } else {
1521         g_dec (Flags | CF_CONST | CF_FORCECHAR, 1);
1522     }
1523
1524     /* Store the result back */
1525     Store (Expr, 0);
1526
1527     /* Restore the original value in the primary register */
1528     g_restore (Flags | CF_FORCECHAR);
1529
1530     /* The result is always an expression, no reference */
1531     ED_MakeRValExpr (Expr);
1532 }
1533
1534
1535
1536 static void UnaryOp (ExprDesc* Expr)
1537 /* Handle unary -/+ and ~ */
1538 {
1539     unsigned Flags;
1540
1541     /* Remember the operator token and skip it */
1542     token_t Tok = CurTok.Tok;
1543     NextToken ();
1544
1545     /* Get the expression */
1546     hie10 (Expr);
1547
1548     /* We can only handle integer types */
1549     if (!IsClassInt (Expr->Type)) {
1550         Error ("Argument must have integer type");
1551         ED_MakeConstAbsInt (Expr, 1);
1552     }
1553
1554     /* Check for a constant expression */
1555     if (ED_IsConstAbs (Expr)) {
1556         /* Value is constant */
1557         switch (Tok) {
1558             case TOK_MINUS: Expr->IVal = -Expr->IVal;   break;
1559             case TOK_PLUS:                              break;
1560             case TOK_COMP:  Expr->IVal = ~Expr->IVal;   break;
1561             default:        Internal ("Unexpected token: %d", Tok);
1562         }
1563     } else {
1564         /* Value is not constant */
1565         LoadExpr (CF_NONE, Expr);
1566
1567         /* Get the type of the expression */
1568         Flags = TypeOf (Expr->Type);
1569
1570         /* Handle the operation */
1571         switch (Tok) {
1572             case TOK_MINUS: g_neg (Flags);  break;
1573             case TOK_PLUS:                  break;
1574             case TOK_COMP:  g_com (Flags);  break;
1575             default:        Internal ("Unexpected token: %d", Tok);
1576         }
1577
1578         /* The result is a rvalue in the primary */
1579         ED_MakeRValExpr (Expr);
1580     }
1581 }
1582
1583
1584
1585 void hie10 (ExprDesc* Expr)
1586 /* Handle ++, --, !, unary - etc. */
1587 {
1588     unsigned long Size;
1589
1590     switch (CurTok.Tok) {
1591
1592         case TOK_INC:
1593             PreInc (Expr);
1594             break;
1595
1596         case TOK_DEC:
1597             PreDec (Expr);
1598             break;
1599
1600         case TOK_PLUS:
1601         case TOK_MINUS:
1602         case TOK_COMP:
1603             UnaryOp (Expr);
1604             break;
1605
1606         case TOK_BOOL_NOT:
1607             NextToken ();
1608             if (evalexpr (CF_NONE, hie10, Expr) == 0) {
1609                 /* Constant expression */
1610                 Expr->IVal = !Expr->IVal;
1611             } else {
1612                 g_bneg (TypeOf (Expr->Type));
1613                 ED_MakeRValExpr (Expr);
1614                 ED_TestDone (Expr);             /* bneg will set cc */
1615             }
1616             break;
1617
1618         case TOK_STAR:
1619             NextToken ();
1620             ExprWithCheck (hie10, Expr);
1621             if (ED_IsLVal (Expr) || !(ED_IsLocConst (Expr) || ED_IsLocStack (Expr))) {
1622                 /* Not a const, load it into the primary and make it a
1623                  * calculated value.
1624                  */
1625                 LoadExpr (CF_NONE, Expr);
1626                 ED_MakeRValExpr (Expr);
1627             }
1628             /* If the expression is already a pointer to function, the
1629              * additional dereferencing operator must be ignored. A function
1630              * itself is represented as "pointer to function", so any number
1631              * of dereference operators is legal, since the result will
1632              * always be converted to "pointer to function".
1633              */
1634             if (IsTypeFuncPtr (Expr->Type) || IsTypeFunc (Expr->Type)) {
1635                 /* Expression not storable */
1636                 ED_MakeRVal (Expr);
1637             } else {
1638                 if (IsClassPtr (Expr->Type)) {
1639                     Expr->Type = Indirect (Expr->Type);
1640                 } else {
1641                     Error ("Illegal indirection");
1642                 }
1643                 /* The * operator yields an lvalue */
1644                 ED_MakeLVal (Expr);
1645             }
1646             break;
1647
1648         case TOK_AND:
1649             NextToken ();
1650             ExprWithCheck (hie10, Expr);
1651             /* The & operator may be applied to any lvalue, and it may be
1652              * applied to functions, even if they're no lvalues.
1653              */
1654             if (ED_IsRVal (Expr) && !IsTypeFunc (Expr->Type) && !IsTypeArray (Expr->Type)) {
1655                 Error ("Illegal address");
1656             } else {
1657                 if (ED_IsBitField (Expr)) {
1658                     Error ("Cannot take address of bit-field");
1659                     /* Do it anyway, just to avoid further warnings */
1660                     Expr->Flags &= ~E_BITFIELD;
1661                 }
1662                 Expr->Type = PointerTo (Expr->Type);
1663                 /* The & operator yields an rvalue */
1664                 ED_MakeRVal (Expr);
1665             }
1666             break;
1667
1668         case TOK_SIZEOF:
1669             NextToken ();
1670             if (TypeSpecAhead ()) {
1671                 Type T[MAXTYPELEN];
1672                 NextToken ();
1673                 Size = CheckedSizeOf (ParseType (T));
1674                 ConsumeRParen ();
1675             } else {
1676                 /* Remember the output queue pointer */
1677                 CodeMark Mark;
1678                 GetCodePos (&Mark);
1679                 hie10 (Expr);
1680                 Size = CheckedSizeOf (Expr->Type);
1681                 /* Remove any generated code */
1682                 RemoveCode (&Mark);
1683             }
1684             ED_MakeConstAbs (Expr, Size, type_size_t);
1685             ED_MarkAsUntested (Expr);
1686             break;
1687
1688         default:
1689             if (TypeSpecAhead ()) {
1690
1691                 /* A typecast */
1692                 TypeCast (Expr);
1693
1694             } else {
1695
1696                 /* An expression */
1697                 hie11 (Expr);
1698
1699                 /* Handle post increment */
1700                 switch (CurTok.Tok) {
1701                     case TOK_INC:   PostInc (Expr); break;
1702                     case TOK_DEC:   PostDec (Expr); break;
1703                     default:                        break;
1704                 }
1705
1706             }
1707             break;
1708     }
1709 }
1710
1711
1712
1713 static void hie_internal (const GenDesc* Ops,   /* List of generators */
1714                           ExprDesc* Expr,
1715                           void (*hienext) (ExprDesc*),
1716                           int* UsedGen)
1717 /* Helper function */
1718 {
1719     ExprDesc Expr2;
1720     CodeMark Mark1;
1721     CodeMark Mark2;
1722     const GenDesc* Gen;
1723     token_t Tok;                        /* The operator token */
1724     unsigned ltype, type;
1725     int rconst;                         /* Operand is a constant */
1726
1727
1728     hienext (Expr);
1729
1730     *UsedGen = 0;
1731     while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
1732
1733         /* Tell the caller that we handled it's ops */
1734         *UsedGen = 1;
1735
1736         /* All operators that call this function expect an int on the lhs */
1737         if (!IsClassInt (Expr->Type)) {
1738             Error ("Integer expression expected");
1739             /* To avoid further errors, make Expr a valid int expression */
1740             ED_MakeConstAbsInt (Expr, 1);
1741         }
1742
1743         /* Remember the operator token, then skip it */
1744         Tok = CurTok.Tok;
1745         NextToken ();
1746
1747         /* Get the lhs on stack */
1748         GetCodePos (&Mark1);
1749         ltype = TypeOf (Expr->Type);
1750         if (ED_IsConstAbs (Expr)) {
1751             /* Constant value */
1752             GetCodePos (&Mark2);
1753             g_push (ltype | CF_CONST, Expr->IVal);
1754         } else {
1755             /* Value not constant */
1756             LoadExpr (CF_NONE, Expr);
1757             GetCodePos (&Mark2);
1758             g_push (ltype, 0);
1759         }
1760
1761         /* Get the right hand side */
1762         MarkedExprWithCheck (hienext, &Expr2);
1763
1764         /* Check for a constant expression */
1765         rconst = (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2));
1766         if (!rconst) {
1767             /* Not constant, load into the primary */
1768             LoadExpr (CF_NONE, &Expr2);
1769         }
1770
1771         /* Check the type of the rhs */
1772         if (!IsClassInt (Expr2.Type)) {
1773             Error ("Integer expression expected");
1774         }
1775
1776         /* Check for const operands */
1777         if (ED_IsConstAbs (Expr) && rconst) {
1778
1779             /* Both operands are constant, remove the generated code */
1780             RemoveCode (&Mark1);
1781
1782             /* Get the type of the result */
1783             Expr->Type = promoteint (Expr->Type, Expr2.Type);
1784
1785             /* Handle the op differently for signed and unsigned types */
1786             if (IsSignSigned (Expr->Type)) {
1787
1788                 /* Evaluate the result for signed operands */
1789                 signed long Val1 = Expr->IVal;
1790                 signed long Val2 = Expr2.IVal;
1791                 switch (Tok) {
1792                     case TOK_OR:
1793                         Expr->IVal = (Val1 | Val2);
1794                         break;
1795                     case TOK_XOR:
1796                         Expr->IVal = (Val1 ^ Val2);
1797                         break;
1798                     case TOK_AND:
1799                         Expr->IVal = (Val1 & Val2);
1800                         break;
1801                     case TOK_STAR:
1802                         Expr->IVal = (Val1 * Val2);
1803                         break;
1804                     case TOK_DIV:
1805                         if (Val2 == 0) {
1806                             Error ("Division by zero");
1807                             Expr->IVal = 0x7FFFFFFF;
1808                         } else {
1809                             Expr->IVal = (Val1 / Val2);
1810                         }
1811                         break;
1812                     case TOK_MOD:
1813                         if (Val2 == 0) {
1814                             Error ("Modulo operation with zero");
1815                             Expr->IVal = 0;
1816                         } else {
1817                             Expr->IVal = (Val1 % Val2);
1818                         }
1819                         break;
1820                     default:
1821                         Internal ("hie_internal: got token 0x%X\n", Tok);
1822                 }
1823             } else {
1824
1825                 /* Evaluate the result for unsigned operands */
1826                 unsigned long Val1 = Expr->IVal;
1827                 unsigned long Val2 = Expr2.IVal;
1828                 switch (Tok) {
1829                     case TOK_OR:
1830                         Expr->IVal = (Val1 | Val2);
1831                         break;
1832                     case TOK_XOR:
1833                         Expr->IVal = (Val1 ^ Val2);
1834                         break;
1835                     case TOK_AND:
1836                         Expr->IVal = (Val1 & Val2);
1837                         break;
1838                     case TOK_STAR:
1839                         Expr->IVal = (Val1 * Val2);
1840                         break;
1841                     case TOK_DIV:
1842                         if (Val2 == 0) {
1843                             Error ("Division by zero");
1844                             Expr->IVal = 0xFFFFFFFF;
1845                         } else {
1846                             Expr->IVal = (Val1 / Val2);
1847                         }
1848                         break;
1849                     case TOK_MOD:
1850                         if (Val2 == 0) {
1851                             Error ("Modulo operation with zero");
1852                             Expr->IVal = 0;
1853                         } else {
1854                             Expr->IVal = (Val1 % Val2);
1855                         }
1856                         break;
1857                     default:
1858                         Internal ("hie_internal: got token 0x%X\n", Tok);
1859                 }
1860             }
1861
1862         } else {
1863
1864             /* If the right hand side is constant, and the generator function
1865              * expects the lhs in the primary, remove the push of the primary
1866              * now.
1867              */
1868             unsigned rtype = TypeOf (Expr2.Type);
1869             type = 0;
1870             if (rconst) {
1871                 /* Second value is constant - check for div */
1872                 type |= CF_CONST;
1873                 rtype |= CF_CONST;
1874                 if (Tok == TOK_DIV && Expr2.IVal == 0) {
1875                     Error ("Division by zero");
1876                 } else if (Tok == TOK_MOD && Expr2.IVal == 0) {
1877                     Error ("Modulo operation with zero");
1878                 }
1879                 if ((Gen->Flags & GEN_NOPUSH) != 0) {
1880                     RemoveCode (&Mark2);
1881                     ltype |= CF_REG;    /* Value is in register */
1882                 }
1883             }
1884
1885             /* Determine the type of the operation result. */
1886             type |= g_typeadjust (ltype, rtype);
1887             Expr->Type = promoteint (Expr->Type, Expr2.Type);
1888
1889             /* Generate code */
1890             Gen->Func (type, Expr2.IVal);
1891
1892             /* We have a rvalue in the primary now */
1893             ED_MakeRValExpr (Expr);
1894         }
1895     }
1896 }
1897
1898
1899
1900 static void hie_compare (const GenDesc* Ops,    /* List of generators */
1901                          ExprDesc* Expr,
1902                          void (*hienext) (ExprDesc*))
1903 /* Helper function for the compare operators */
1904 {
1905     ExprDesc Expr2;
1906     CodeMark Mark1;
1907     CodeMark Mark2;
1908     const GenDesc* Gen;
1909     token_t Tok;                        /* The operator token */
1910     unsigned ltype;
1911     int rconst;                         /* Operand is a constant */
1912
1913
1914     hienext (Expr);
1915
1916     while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
1917
1918         /* Remember the operator token, then skip it */
1919         Tok = CurTok.Tok;
1920         NextToken ();
1921
1922         /* Get the lhs on stack */
1923         GetCodePos (&Mark1);
1924         ltype = TypeOf (Expr->Type);
1925         if (ED_IsConstAbs (Expr)) {
1926             /* Constant value */
1927             GetCodePos (&Mark2);
1928             g_push (ltype | CF_CONST, Expr->IVal);
1929         } else {
1930             /* Value not constant */
1931             LoadExpr (CF_NONE, Expr);
1932             GetCodePos (&Mark2);
1933             g_push (ltype, 0);
1934         }
1935
1936         /* Get the right hand side */
1937         MarkedExprWithCheck (hienext, &Expr2);
1938
1939         /* Check for a constant expression */
1940         rconst = (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2));
1941         if (!rconst) {
1942             /* Not constant, load into the primary */
1943             LoadExpr (CF_NONE, &Expr2);
1944         }
1945
1946         /* Make sure, the types are compatible */
1947         if (IsClassInt (Expr->Type)) {
1948             if (!IsClassInt (Expr2.Type) && !(IsClassPtr(Expr2.Type) && ED_IsNullPtr(Expr))) {
1949                 Error ("Incompatible types");
1950             }
1951         } else if (IsClassPtr (Expr->Type)) {
1952             if (IsClassPtr (Expr2.Type)) {
1953                 /* Both pointers are allowed in comparison if they point to
1954                  * the same type, or if one of them is a void pointer.
1955                  */
1956                 Type* left  = Indirect (Expr->Type);
1957                 Type* right = Indirect (Expr2.Type);
1958                 if (TypeCmp (left, right) < TC_EQUAL && left->C != T_VOID && right->C != T_VOID) {
1959                     /* Incomatible pointers */
1960                     Error ("Incompatible types");
1961                 }
1962             } else if (!ED_IsNullPtr (&Expr2)) {
1963                 Error ("Incompatible types");
1964             }
1965         }
1966
1967         /* Check for const operands */
1968         if (ED_IsConstAbs (Expr) && rconst) {
1969
1970             /* If the result is constant, this is suspicious when not in
1971              * preprocessor mode.
1972              */
1973             if (!Preprocessing) {
1974                 Warning ("Result of comparison is constant");
1975             }
1976
1977             /* Both operands are constant, remove the generated code */
1978             RemoveCode (&Mark1);
1979
1980             /* Determine if this is a signed or unsigned compare */
1981             if (IsClassInt (Expr->Type) && IsSignSigned (Expr->Type) &&
1982                 IsClassInt (Expr2.Type) && IsSignSigned (Expr2.Type)) {
1983
1984                 /* Evaluate the result for signed operands */
1985                 signed long Val1 = Expr->IVal;
1986                 signed long Val2 = Expr2.IVal;
1987                 switch (Tok) {
1988                     case TOK_EQ: Expr->IVal = (Val1 == Val2);   break;
1989                     case TOK_NE: Expr->IVal = (Val1 != Val2);   break;
1990                     case TOK_LT: Expr->IVal = (Val1 < Val2);    break;
1991                     case TOK_LE: Expr->IVal = (Val1 <= Val2);   break;
1992                     case TOK_GE: Expr->IVal = (Val1 >= Val2);   break;
1993                     case TOK_GT: Expr->IVal = (Val1 > Val2);    break;
1994                     default:     Internal ("hie_compare: got token 0x%X\n", Tok);
1995                 }
1996
1997             } else {
1998
1999                 /* Evaluate the result for unsigned operands */
2000                 unsigned long Val1 = Expr->IVal;
2001                 unsigned long Val2 = Expr2.IVal;
2002                 switch (Tok) {
2003                     case TOK_EQ: Expr->IVal = (Val1 == Val2);   break;
2004                     case TOK_NE: Expr->IVal = (Val1 != Val2);   break;
2005                     case TOK_LT: Expr->IVal = (Val1 < Val2);    break;
2006                     case TOK_LE: Expr->IVal = (Val1 <= Val2);   break;
2007                     case TOK_GE: Expr->IVal = (Val1 >= Val2);   break;
2008                     case TOK_GT: Expr->IVal = (Val1 > Val2);    break;
2009                     default:     Internal ("hie_compare: got token 0x%X\n", Tok);
2010                 }
2011             }
2012
2013         } else {
2014
2015             /* If the right hand side is constant, and the generator function
2016              * expects the lhs in the primary, remove the push of the primary
2017              * now.
2018              */
2019             unsigned flags = 0;
2020             if (rconst) {
2021                 flags |= CF_CONST;
2022                 if ((Gen->Flags & GEN_NOPUSH) != 0) {
2023                     RemoveCode (&Mark2);
2024                     ltype |= CF_REG;    /* Value is in register */
2025                 }
2026             }
2027
2028             /* Determine the type of the operation result. If the left
2029              * operand is of type char and the right is a constant, or
2030              * if both operands are of type char, we will encode the
2031              * operation as char operation. Otherwise the default
2032              * promotions are used.
2033              */
2034             if (IsTypeChar (Expr->Type) && (IsTypeChar (Expr2.Type) || rconst)) {
2035                 flags |= CF_CHAR;
2036                 if (IsSignUnsigned (Expr->Type) || IsSignUnsigned (Expr2.Type)) {
2037                     flags |= CF_UNSIGNED;
2038                 }
2039                 if (rconst) {
2040                     flags |= CF_FORCECHAR;
2041                 }
2042             } else {
2043                 unsigned rtype = TypeOf (Expr2.Type) | (flags & CF_CONST);
2044                 flags |= g_typeadjust (ltype, rtype);
2045             }
2046
2047             /* Generate code */
2048             Gen->Func (flags, Expr2.IVal);
2049
2050             /* The result is an rvalue in the primary */
2051             ED_MakeRValExpr (Expr);
2052         }
2053
2054         /* Result type is always int */
2055         Expr->Type = type_int;
2056
2057         /* Condition codes are set */
2058         ED_TestDone (Expr);
2059     }
2060 }
2061
2062
2063
2064 static void hie9 (ExprDesc *Expr)
2065 /* Process * and / operators. */
2066 {
2067     static const GenDesc hie9_ops[] = {
2068         { TOK_STAR,     GEN_NOPUSH,     g_mul   },
2069         { TOK_DIV,      GEN_NOPUSH,     g_div   },
2070         { TOK_MOD,      GEN_NOPUSH,     g_mod   },
2071         { TOK_INVALID,  0,              0       }
2072     };
2073     int UsedGen;
2074
2075     hie_internal (hie9_ops, Expr, hie10, &UsedGen);
2076 }
2077
2078
2079
2080 static void parseadd (ExprDesc* Expr)
2081 /* Parse an expression with the binary plus operator. Expr contains the
2082  * unprocessed left hand side of the expression and will contain the
2083  * result of the expression on return.
2084  */
2085 {
2086     ExprDesc Expr2;
2087     unsigned flags;             /* Operation flags */
2088     CodeMark Mark;              /* Remember code position */
2089     Type* lhst;                 /* Type of left hand side */
2090     Type* rhst;                 /* Type of right hand side */
2091
2092
2093     /* Skip the PLUS token */
2094     NextToken ();
2095
2096     /* Get the left hand side type, initialize operation flags */
2097     lhst = Expr->Type;
2098     flags = 0;
2099
2100     /* Check for constness on both sides */
2101     if (ED_IsConst (Expr)) {
2102
2103         /* The left hand side is a constant of some sort. Good. Get rhs */
2104         hie9 (&Expr2);
2105         if (ED_IsConstAbs (&Expr2)) {
2106
2107             /* Right hand side is a constant numeric value. Get the rhs type */
2108             rhst = Expr2.Type;
2109
2110             /* Both expressions are constants. Check for pointer arithmetic */
2111             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2112                 /* Left is pointer, right is int, must scale rhs */
2113                 Expr->IVal += Expr2.IVal * CheckedPSizeOf (lhst);
2114                 /* Result type is a pointer */
2115             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2116                 /* Left is int, right is pointer, must scale lhs */
2117                 Expr->IVal = Expr->IVal * CheckedPSizeOf (rhst) + Expr2.IVal;
2118                 /* Result type is a pointer */
2119                 Expr->Type = Expr2.Type;
2120             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2121                 /* Integer addition */
2122                 Expr->IVal += Expr2.IVal;
2123                 typeadjust (Expr, &Expr2, 1);
2124             } else {
2125                 /* OOPS */
2126                 Error ("Invalid operands for binary operator `+'");
2127             }
2128
2129         } else {
2130
2131             /* lhs is a constant and rhs is not constant. Load rhs into
2132              * the primary.
2133              */
2134             LoadExpr (CF_NONE, &Expr2);
2135
2136             /* Beware: The check above (for lhs) lets not only pass numeric
2137              * constants, but also constant addresses (labels), maybe even
2138              * with an offset. We have to check for that here.
2139              */
2140
2141             /* First, get the rhs type. */
2142             rhst = Expr2.Type;
2143
2144             /* Setup flags */
2145             if (ED_IsLocAbs (Expr)) {
2146                 /* A numerical constant */
2147                 flags |= CF_CONST;
2148             } else {
2149                 /* Constant address label */
2150                 flags |= GlobalModeFlags (Expr) | CF_CONSTADDR;
2151             }
2152
2153             /* Check for pointer arithmetic */
2154             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2155                 /* Left is pointer, right is int, must scale rhs */
2156                 g_scale (CF_INT, CheckedPSizeOf (lhst));
2157                 /* Operate on pointers, result type is a pointer */
2158                 flags |= CF_PTR;
2159                 /* Generate the code for the add */
2160                 if (ED_GetLoc (Expr) == E_LOC_ABS) {
2161                     /* Numeric constant */
2162                     g_inc (flags, Expr->IVal);
2163                 } else {
2164                     /* Constant address */
2165                     g_addaddr_static (flags, Expr->Name, Expr->IVal);
2166                 }
2167             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2168
2169                 /* Left is int, right is pointer, must scale lhs. */
2170                 unsigned ScaleFactor = CheckedPSizeOf (rhst);
2171
2172                 /* Operate on pointers, result type is a pointer */
2173                 flags |= CF_PTR;
2174                 Expr->Type = Expr2.Type;
2175
2176                 /* Since we do already have rhs in the primary, if lhs is
2177                  * not a numeric constant, and the scale factor is not one
2178                  * (no scaling), we must take the long way over the stack.
2179                  */
2180                 if (ED_IsLocAbs (Expr)) {
2181                     /* Numeric constant, scale lhs */
2182                     Expr->IVal *= ScaleFactor;
2183                     /* Generate the code for the add */
2184                     g_inc (flags, Expr->IVal);
2185                 } else if (ScaleFactor == 1) {
2186                     /* Constant address but no need to scale */
2187                     g_addaddr_static (flags, Expr->Name, Expr->IVal);
2188                 } else {
2189                     /* Constant address that must be scaled */
2190                     g_push (TypeOf (Expr2.Type), 0);    /* rhs --> stack */
2191                     g_getimmed (flags, Expr->Name, Expr->IVal);
2192                     g_scale (CF_PTR, ScaleFactor);
2193                     g_add (CF_PTR, 0);
2194                 }
2195             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2196                 /* Integer addition */
2197                 flags |= typeadjust (Expr, &Expr2, 1);
2198                 /* Generate the code for the add */
2199                 if (ED_IsLocAbs (Expr)) {
2200                     /* Numeric constant */
2201                     g_inc (flags, Expr->IVal);
2202                 } else {
2203                     /* Constant address */
2204                     g_addaddr_static (flags, Expr->Name, Expr->IVal);
2205                 }
2206             } else {
2207                 /* OOPS */
2208                 Error ("Invalid operands for binary operator `+'");
2209                 flags = CF_INT;
2210             }
2211
2212             /* Result is a rvalue in primary register */
2213             ED_MakeRValExpr (Expr);
2214         }
2215
2216     } else {
2217
2218         /* Left hand side is not constant. Get the value onto the stack. */
2219         LoadExpr (CF_NONE, Expr);              /* --> primary register */
2220         GetCodePos (&Mark);
2221         g_push (TypeOf (Expr->Type), 0);        /* --> stack */
2222
2223         /* Evaluate the rhs */
2224         MarkedExprWithCheck (hie9, &Expr2);
2225
2226         /* Check for a constant rhs expression */
2227         if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) {
2228
2229             /* Right hand side is a constant. Get the rhs type */
2230             rhst = Expr2.Type;
2231
2232             /* Remove pushed value from stack */
2233             RemoveCode (&Mark);
2234
2235             /* Check for pointer arithmetic */
2236             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2237                 /* Left is pointer, right is int, must scale rhs */
2238                 Expr2.IVal *= CheckedPSizeOf (lhst);
2239                 /* Operate on pointers, result type is a pointer */
2240                 flags = CF_PTR;
2241             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2242                 /* Left is int, right is pointer, must scale lhs (ptr only) */
2243                 g_scale (CF_INT | CF_CONST, CheckedPSizeOf (rhst));
2244                 /* Operate on pointers, result type is a pointer */
2245                 flags = CF_PTR;
2246                 Expr->Type = Expr2.Type;
2247             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2248                 /* Integer addition */
2249                 flags = typeadjust (Expr, &Expr2, 1);
2250             } else {
2251                 /* OOPS */
2252                 Error ("Invalid operands for binary operator `+'");
2253                 flags = CF_INT;
2254             }
2255
2256             /* Generate code for the add */
2257             g_inc (flags | CF_CONST, Expr2.IVal);
2258
2259         } else {
2260
2261             /* Not constant, load into the primary */
2262             LoadExpr (CF_NONE, &Expr2);
2263
2264             /* lhs and rhs are not constant. Get the rhs type. */
2265             rhst = Expr2.Type;
2266
2267             /* Check for pointer arithmetic */
2268             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2269                 /* Left is pointer, right is int, must scale rhs */
2270                 g_scale (CF_INT, CheckedPSizeOf (lhst));
2271                 /* Operate on pointers, result type is a pointer */
2272                 flags = CF_PTR;
2273             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2274                 /* Left is int, right is pointer, must scale lhs */
2275                 g_tosint (TypeOf (rhst));       /* Make sure, TOS is int */
2276                 g_swap (CF_INT);                /* Swap TOS and primary */
2277                 g_scale (CF_INT, CheckedPSizeOf (rhst));
2278                 /* Operate on pointers, result type is a pointer */
2279                 flags = CF_PTR;
2280                 Expr->Type = Expr2.Type;
2281             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2282                 /* Integer addition. Note: Result is never constant.
2283                  * Problem here is that typeadjust does not know if the
2284                  * variable is an rvalue or lvalue, so if both operands
2285                  * are dereferenced constant numeric addresses, typeadjust
2286                  * thinks the operation works on constants. Removing
2287                  * CF_CONST here means handling the symptoms, however, the
2288                  * whole parser is such a mess that I fear to break anything
2289                  * when trying to apply another solution.
2290                  */
2291                 flags = typeadjust (Expr, &Expr2, 0) & ~CF_CONST;
2292             } else {
2293                 /* OOPS */
2294                 Error ("Invalid operands for binary operator `+'");
2295                 flags = CF_INT;
2296             }
2297
2298             /* Generate code for the add */
2299             g_add (flags, 0);
2300
2301         }
2302
2303         /* Result is a rvalue in primary register */
2304         ED_MakeRValExpr (Expr);
2305     }
2306
2307     /* Condition codes not set */
2308     ED_MarkAsUntested (Expr);
2309
2310 }
2311
2312
2313
2314 static void parsesub (ExprDesc* Expr)
2315 /* Parse an expression with the binary minus operator. Expr contains the
2316  * unprocessed left hand side of the expression and will contain the
2317  * result of the expression on return.
2318  */
2319 {
2320     ExprDesc Expr2;
2321     unsigned flags;             /* Operation flags */
2322     Type* lhst;                 /* Type of left hand side */
2323     Type* rhst;                 /* Type of right hand side */
2324     CodeMark Mark1;             /* Save position of output queue */
2325     CodeMark Mark2;             /* Another position in the queue */
2326     int rscale;                 /* Scale factor for the result */
2327
2328
2329     /* Skip the MINUS token */
2330     NextToken ();
2331
2332     /* Get the left hand side type, initialize operation flags */
2333     lhst = Expr->Type;
2334     rscale = 1;                 /* Scale by 1, that is, don't scale */
2335
2336     /* Remember the output queue position, then bring the value onto the stack */
2337     GetCodePos (&Mark1);
2338     LoadExpr (CF_NONE, Expr);  /* --> primary register */
2339     GetCodePos (&Mark2);
2340     g_push (TypeOf (lhst), 0);  /* --> stack */
2341
2342     /* Parse the right hand side */
2343     MarkedExprWithCheck (hie9, &Expr2);
2344
2345     /* Check for a constant rhs expression */
2346     if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) {
2347
2348         /* The right hand side is constant. Get the rhs type. */
2349         rhst = Expr2.Type;
2350
2351         /* Check left hand side */
2352         if (ED_IsConstAbs (Expr)) {
2353
2354             /* Both sides are constant, remove generated code */
2355             RemoveCode (&Mark1);
2356
2357             /* Check for pointer arithmetic */
2358             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2359                 /* Left is pointer, right is int, must scale rhs */
2360                 Expr->IVal -= Expr2.IVal * CheckedPSizeOf (lhst);
2361                 /* Operate on pointers, result type is a pointer */
2362             } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2363                 /* Left is pointer, right is pointer, must scale result */
2364                 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2365                     Error ("Incompatible pointer types");
2366                 } else {
2367                     Expr->IVal = (Expr->IVal - Expr2.IVal) /
2368                                       CheckedPSizeOf (lhst);
2369                 }
2370                 /* Operate on pointers, result type is an integer */
2371                 Expr->Type = type_int;
2372             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2373                 /* Integer subtraction */
2374                 typeadjust (Expr, &Expr2, 1);
2375                 Expr->IVal -= Expr2.IVal;
2376             } else {
2377                 /* OOPS */
2378                 Error ("Invalid operands for binary operator `-'");
2379             }
2380
2381             /* Result is constant, condition codes not set */
2382             ED_MarkAsUntested (Expr);
2383
2384         } else {
2385
2386             /* Left hand side is not constant, right hand side is.
2387              * Remove pushed value from stack.
2388              */
2389             RemoveCode (&Mark2);
2390
2391             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2392                 /* Left is pointer, right is int, must scale rhs */
2393                 Expr2.IVal *= CheckedPSizeOf (lhst);
2394                 /* Operate on pointers, result type is a pointer */
2395                 flags = CF_PTR;
2396             } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2397                 /* Left is pointer, right is pointer, must scale result */
2398                 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2399                     Error ("Incompatible pointer types");
2400                 } else {
2401                     rscale = CheckedPSizeOf (lhst);
2402                 }
2403                 /* Operate on pointers, result type is an integer */
2404                 flags = CF_PTR;
2405                 Expr->Type = type_int;
2406             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2407                 /* Integer subtraction */
2408                 flags = typeadjust (Expr, &Expr2, 1);
2409             } else {
2410                 /* OOPS */
2411                 Error ("Invalid operands for binary operator `-'");
2412                 flags = CF_INT;
2413             }
2414
2415             /* Do the subtraction */
2416             g_dec (flags | CF_CONST, Expr2.IVal);
2417
2418             /* If this was a pointer subtraction, we must scale the result */
2419             if (rscale != 1) {
2420                 g_scale (flags, -rscale);
2421             }
2422
2423             /* Result is a rvalue in the primary register */
2424             ED_MakeRValExpr (Expr);
2425             ED_MarkAsUntested (Expr);
2426
2427         }
2428
2429     } else {
2430
2431         /* Not constant, load into the primary */
2432         LoadExpr (CF_NONE, &Expr2);
2433
2434         /* Right hand side is not constant. Get the rhs type. */
2435         rhst = Expr2.Type;
2436
2437         /* Check for pointer arithmetic */
2438         if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2439             /* Left is pointer, right is int, must scale rhs */
2440             g_scale (CF_INT, CheckedPSizeOf (lhst));
2441             /* Operate on pointers, result type is a pointer */
2442             flags = CF_PTR;
2443         } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2444             /* Left is pointer, right is pointer, must scale result */
2445             if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2446                 Error ("Incompatible pointer types");
2447             } else {
2448                 rscale = CheckedPSizeOf (lhst);
2449             }
2450             /* Operate on pointers, result type is an integer */
2451             flags = CF_PTR;
2452             Expr->Type = type_int;
2453         } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2454             /* Integer subtraction. If the left hand side descriptor says that
2455              * the lhs is const, we have to remove this mark, since this is no
2456              * longer true, lhs is on stack instead.
2457              */
2458             if (ED_IsLocAbs (Expr)) {
2459                 ED_MakeRValExpr (Expr);
2460             }
2461             /* Adjust operand types */
2462             flags = typeadjust (Expr, &Expr2, 0);
2463         } else {
2464             /* OOPS */
2465             Error ("Invalid operands for binary operator `-'");
2466             flags = CF_INT;
2467         }
2468
2469         /* Generate code for the sub (the & is a hack here) */
2470         g_sub (flags & ~CF_CONST, 0);
2471
2472         /* If this was a pointer subtraction, we must scale the result */
2473         if (rscale != 1) {
2474             g_scale (flags, -rscale);
2475         }
2476
2477         /* Result is a rvalue in the primary register */
2478         ED_MakeRValExpr (Expr);
2479         ED_MarkAsUntested (Expr);
2480     }
2481 }
2482
2483
2484
2485 void hie8 (ExprDesc* Expr)
2486 /* Process + and - binary operators. */
2487 {
2488     hie9 (Expr);
2489     while (CurTok.Tok == TOK_PLUS || CurTok.Tok == TOK_MINUS) {
2490         if (CurTok.Tok == TOK_PLUS) {
2491             parseadd (Expr);
2492         } else {
2493             parsesub (Expr);
2494         }
2495     }
2496 }
2497
2498
2499
2500 static void hie6 (ExprDesc* Expr)
2501 /* Handle greater-than type comparators */
2502 {
2503     static const GenDesc hie6_ops [] = {
2504         { TOK_LT,       GEN_NOPUSH,     g_lt    },
2505         { TOK_LE,       GEN_NOPUSH,     g_le    },
2506         { TOK_GE,       GEN_NOPUSH,     g_ge    },
2507         { TOK_GT,       GEN_NOPUSH,     g_gt    },
2508         { TOK_INVALID,  0,              0       }
2509     };
2510     hie_compare (hie6_ops, Expr, ShiftExpr);
2511 }
2512
2513
2514
2515 static void hie5 (ExprDesc* Expr)
2516 /* Handle == and != */
2517 {
2518     static const GenDesc hie5_ops[] = {
2519         { TOK_EQ,       GEN_NOPUSH,     g_eq    },
2520         { TOK_NE,       GEN_NOPUSH,     g_ne    },
2521         { TOK_INVALID,  0,              0       }
2522     };
2523     hie_compare (hie5_ops, Expr, hie6);
2524 }
2525
2526
2527
2528 static void hie4 (ExprDesc* Expr)
2529 /* Handle & (bitwise and) */
2530 {
2531     static const GenDesc hie4_ops[] = {
2532         { TOK_AND,      GEN_NOPUSH,     g_and   },
2533         { TOK_INVALID,  0,              0       }
2534     };
2535     int UsedGen;
2536
2537     hie_internal (hie4_ops, Expr, hie5, &UsedGen);
2538 }
2539
2540
2541
2542 static void hie3 (ExprDesc* Expr)
2543 /* Handle ^ (bitwise exclusive or) */
2544 {
2545     static const GenDesc hie3_ops[] = {
2546         { TOK_XOR,      GEN_NOPUSH,     g_xor   },
2547         { TOK_INVALID,  0,              0       }
2548     };
2549     int UsedGen;
2550
2551     hie_internal (hie3_ops, Expr, hie4, &UsedGen);
2552 }
2553
2554
2555
2556 static void hie2 (ExprDesc* Expr)
2557 /* Handle | (bitwise or) */
2558 {
2559     static const GenDesc hie2_ops[] = {
2560         { TOK_OR,       GEN_NOPUSH,     g_or    },
2561         { TOK_INVALID,  0,              0       }
2562     };
2563     int UsedGen;
2564
2565     hie_internal (hie2_ops, Expr, hie3, &UsedGen);
2566 }
2567
2568
2569
2570 static void hieAndPP (ExprDesc* Expr)
2571 /* Process "exp && exp" in preprocessor mode (that is, when the parser is
2572  * called recursively from the preprocessor.
2573  */
2574 {
2575     ExprDesc Expr2;
2576
2577     ConstAbsIntExpr (hie2, Expr);
2578     while (CurTok.Tok == TOK_BOOL_AND) {
2579
2580         /* Skip the && */
2581         NextToken ();
2582
2583         /* Get rhs */
2584         ConstAbsIntExpr (hie2, &Expr2);
2585
2586         /* Combine the two */
2587         Expr->IVal = (Expr->IVal && Expr2.IVal);
2588     }
2589 }
2590
2591
2592
2593 static void hieOrPP (ExprDesc *Expr)
2594 /* Process "exp || exp" in preprocessor mode (that is, when the parser is
2595  * called recursively from the preprocessor.
2596  */
2597 {
2598     ExprDesc Expr2;
2599
2600     ConstAbsIntExpr (hieAndPP, Expr);
2601     while (CurTok.Tok == TOK_BOOL_OR) {
2602
2603         /* Skip the && */
2604         NextToken ();
2605
2606         /* Get rhs */
2607         ConstAbsIntExpr (hieAndPP, &Expr2);
2608
2609         /* Combine the two */
2610         Expr->IVal = (Expr->IVal || Expr2.IVal);
2611     }
2612 }
2613
2614
2615
2616 static void hieAnd (ExprDesc* Expr, unsigned TrueLab, int* BoolOp)
2617 /* Process "exp && exp" */
2618 {
2619     int FalseLab;
2620     ExprDesc Expr2;
2621
2622     hie2 (Expr);
2623     if (CurTok.Tok == TOK_BOOL_AND) {
2624
2625         /* Tell our caller that we're evaluating a boolean */
2626         *BoolOp = 1;
2627
2628         /* Get a label that we will use for false expressions */
2629         FalseLab = GetLocalLabel ();
2630
2631         /* If the expr hasn't set condition codes, set the force-test flag */
2632         if (!ED_IsTested (Expr)) {
2633             ED_MarkForTest (Expr);
2634         }
2635
2636         /* Load the value */
2637         LoadExpr (CF_FORCECHAR, Expr);
2638
2639         /* Generate the jump */
2640         g_falsejump (CF_NONE, FalseLab);
2641
2642         /* Parse more boolean and's */
2643         while (CurTok.Tok == TOK_BOOL_AND) {
2644
2645             /* Skip the && */
2646             NextToken ();
2647
2648             /* Get rhs */
2649             hie2 (&Expr2);
2650             if (!ED_IsTested (&Expr2)) {
2651                 ED_MarkForTest (&Expr2);
2652             }
2653             LoadExpr (CF_FORCECHAR, &Expr2);
2654
2655             /* Do short circuit evaluation */
2656             if (CurTok.Tok == TOK_BOOL_AND) {
2657                 g_falsejump (CF_NONE, FalseLab);
2658             } else {
2659                 /* Last expression - will evaluate to true */
2660                 g_truejump (CF_NONE, TrueLab);
2661             }
2662         }
2663
2664         /* Define the false jump label here */
2665         g_defcodelabel (FalseLab);
2666
2667         /* The result is an rvalue in primary */
2668         ED_MakeRValExpr (Expr);
2669         ED_TestDone (Expr);     /* Condition codes are set */
2670     }
2671 }
2672
2673
2674
2675 static void hieOr (ExprDesc *Expr)
2676 /* Process "exp || exp". */
2677 {
2678     ExprDesc Expr2;
2679     int BoolOp = 0;             /* Did we have a boolean op? */
2680     int AndOp;                  /* Did we have a && operation? */
2681     unsigned TrueLab;           /* Jump to this label if true */
2682     unsigned DoneLab;
2683
2684     /* Get a label */
2685     TrueLab = GetLocalLabel ();
2686
2687     /* Call the next level parser */
2688     hieAnd (Expr, TrueLab, &BoolOp);
2689
2690     /* Any boolean or's? */
2691     if (CurTok.Tok == TOK_BOOL_OR) {
2692
2693         /* If the expr hasn't set condition codes, set the force-test flag */
2694         if (!ED_IsTested (Expr)) {
2695             ED_MarkForTest (Expr);
2696         }
2697
2698         /* Get first expr */
2699         LoadExpr (CF_FORCECHAR, Expr);
2700
2701         /* For each expression jump to TrueLab if true. Beware: If we
2702          * had && operators, the jump is already in place!
2703          */
2704         if (!BoolOp) {
2705             g_truejump (CF_NONE, TrueLab);
2706         }
2707
2708         /* Remember that we had a boolean op */
2709         BoolOp = 1;
2710
2711         /* while there's more expr */
2712         while (CurTok.Tok == TOK_BOOL_OR) {
2713
2714             /* skip the || */
2715             NextToken ();
2716
2717             /* Get a subexpr */
2718             AndOp = 0;
2719             hieAnd (&Expr2, TrueLab, &AndOp);
2720             if (!ED_IsTested (&Expr2)) {
2721                 ED_MarkForTest (&Expr2);
2722             }
2723             LoadExpr (CF_FORCECHAR, &Expr2);
2724
2725             /* If there is more to come, add shortcut boolean eval. */
2726             g_truejump (CF_NONE, TrueLab);
2727
2728         }
2729
2730         /* The result is an rvalue in primary */
2731         ED_MakeRValExpr (Expr);
2732         ED_TestDone (Expr);                     /* Condition codes are set */
2733     }
2734
2735     /* If we really had boolean ops, generate the end sequence */
2736     if (BoolOp) {
2737         DoneLab = GetLocalLabel ();
2738         g_getimmed (CF_INT | CF_CONST, 0, 0);   /* Load FALSE */
2739         g_falsejump (CF_NONE, DoneLab);
2740         g_defcodelabel (TrueLab);
2741         g_getimmed (CF_INT | CF_CONST, 1, 0);   /* Load TRUE */
2742         g_defcodelabel (DoneLab);
2743     }
2744 }
2745
2746
2747
2748 static void hieQuest (ExprDesc* Expr)
2749 /* Parse the ternary operator */
2750 {
2751     int         FalseLab;
2752     int         TrueLab;
2753     CodeMark    TrueCodeEnd;
2754     ExprDesc    Expr2;          /* Expression 2 */
2755     ExprDesc    Expr3;          /* Expression 3 */
2756     int         Expr2IsNULL;    /* Expression 2 is a NULL pointer */
2757     int         Expr3IsNULL;    /* Expression 3 is a NULL pointer */
2758     Type*       ResultType;     /* Type of result */
2759
2760
2761     /* Call the lower level eval routine */
2762     if (Preprocessing) {
2763         hieOrPP (Expr);
2764     } else {
2765         hieOr (Expr);
2766     }
2767
2768     /* Check if it's a ternary expression */
2769     if (CurTok.Tok == TOK_QUEST) {
2770         NextToken ();
2771         if (!ED_IsTested (Expr)) {
2772             /* Condition codes not set, request a test */
2773             ED_MarkForTest (Expr);
2774         }
2775         LoadExpr (CF_NONE, Expr);
2776         FalseLab = GetLocalLabel ();
2777         g_falsejump (CF_NONE, FalseLab);
2778
2779         /* Parse second expression. Remember for later if it is a NULL pointer
2780          * expression, then load it into the primary.
2781          */
2782         ExprWithCheck (hie1, &Expr2);
2783         Expr2IsNULL = ED_IsNullPtr (&Expr2);
2784         if (!IsTypeVoid (Expr2.Type)) {
2785             /* Load it into the primary */
2786             LoadExpr (CF_NONE, &Expr2);
2787             ED_MakeRValExpr (&Expr2);
2788             Expr2.Type = PtrConversion (Expr2.Type);
2789         }
2790
2791         /* Remember the current code position */
2792         GetCodePos (&TrueCodeEnd);
2793
2794         /* Jump around the evaluation of the third expression */
2795         TrueLab = GetLocalLabel ();
2796         ConsumeColon ();
2797         g_jump (TrueLab);
2798
2799         /* Jump here if the first expression was false */
2800         g_defcodelabel (FalseLab);
2801
2802         /* Parse third expression. Remember for later if it is a NULL pointer
2803          * expression, then load it into the primary.
2804          */
2805         ExprWithCheck (hie1, &Expr3);
2806         Expr3IsNULL = ED_IsNullPtr (&Expr3);
2807         if (!IsTypeVoid (Expr3.Type)) {
2808             /* Load it into the primary */
2809             LoadExpr (CF_NONE, &Expr3);
2810             ED_MakeRValExpr (&Expr3);
2811             Expr3.Type = PtrConversion (Expr3.Type);
2812         }
2813
2814         /* Check if any conversions are needed, if so, do them.
2815          * Conversion rules for ?: expression are:
2816          *   - if both expressions are int expressions, default promotion
2817          *     rules for ints apply.
2818          *   - if both expressions are pointers of the same type, the
2819          *     result of the expression is of this type.
2820          *   - if one of the expressions is a pointer and the other is
2821          *     a zero constant, the resulting type is that of the pointer
2822          *     type.
2823          *   - if both expressions are void expressions, the result is of
2824          *     type void.
2825          *   - all other cases are flagged by an error.
2826          */
2827         if (IsClassInt (Expr2.Type) && IsClassInt (Expr3.Type)) {
2828
2829             CodeMark    CvtCodeStart;
2830             CodeMark    CvtCodeEnd;
2831
2832
2833             /* Get common type */
2834             ResultType = promoteint (Expr2.Type, Expr3.Type);
2835
2836             /* Convert the third expression to this type if needed */
2837             TypeConversion (&Expr3, ResultType);
2838
2839             /* Emit conversion code for the second expression, but remember
2840              * where it starts end ends.
2841              */
2842             GetCodePos (&CvtCodeStart);
2843             TypeConversion (&Expr2, ResultType);
2844             GetCodePos (&CvtCodeEnd);
2845
2846             /* If we had conversion code, move it to the right place */
2847             if (!CodeRangeIsEmpty (&CvtCodeStart, &CvtCodeEnd)) {
2848                 MoveCode (&CvtCodeStart, &CvtCodeEnd, &TrueCodeEnd);
2849             }
2850
2851         } else if (IsClassPtr (Expr2.Type) && IsClassPtr (Expr3.Type)) {
2852             /* Must point to same type */
2853             if (TypeCmp (Indirect (Expr2.Type), Indirect (Expr3.Type)) < TC_EQUAL) {
2854                 Error ("Incompatible pointer types");
2855             }
2856             /* Result has the common type */
2857             ResultType = Expr2.Type;
2858         } else if (IsClassPtr (Expr2.Type) && Expr3IsNULL) {
2859             /* Result type is pointer, no cast needed */
2860             ResultType = Expr2.Type;
2861         } else if (Expr2IsNULL && IsClassPtr (Expr3.Type)) {
2862             /* Result type is pointer, no cast needed */
2863             ResultType = Expr3.Type;
2864         } else if (IsTypeVoid (Expr2.Type) && IsTypeVoid (Expr3.Type)) {
2865             /* Result type is void */
2866             ResultType = Expr3.Type;
2867         } else {
2868             Error ("Incompatible types");
2869             ResultType = Expr2.Type;            /* Doesn't matter here */
2870         }
2871
2872         /* Define the final label */
2873         g_defcodelabel (TrueLab);
2874
2875         /* Setup the target expression */
2876         ED_MakeRValExpr (Expr);
2877         Expr->Type  = ResultType;
2878     }
2879 }
2880
2881
2882
2883 static void opeq (const GenDesc* Gen, ExprDesc* Expr, const char* Op)
2884 /* Process "op=" operators. */
2885 {
2886     ExprDesc Expr2;
2887     unsigned flags;
2888     CodeMark Mark;
2889     int MustScale;
2890
2891     /* op= can only be used with lvalues */
2892     if (!ED_IsLVal (Expr)) {
2893         Error ("Invalid lvalue in assignment");
2894         return;
2895     }
2896
2897     /* The left side must not be const qualified */
2898     if (IsQualConst (Expr->Type)) {
2899         Error ("Assignment to const");
2900     }
2901
2902     /* There must be an integer or pointer on the left side */
2903     if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
2904         Error ("Invalid left operand type");
2905         /* Continue. Wrong code will be generated, but the compiler won't
2906          * break, so this is the best error recovery.
2907          */
2908     }
2909
2910     /* Skip the operator token */
2911     NextToken ();
2912
2913     /* Determine the type of the lhs */
2914     flags = TypeOf (Expr->Type);
2915     MustScale = (Gen->Func == g_add || Gen->Func == g_sub) && IsTypePtr (Expr->Type);
2916
2917     /* Get the lhs address on stack (if needed) */
2918     PushAddr (Expr);
2919
2920     /* Fetch the lhs into the primary register if needed */
2921     LoadExpr (CF_NONE, Expr);
2922
2923     /* Bring the lhs on stack */
2924     GetCodePos (&Mark);
2925     g_push (flags, 0);
2926
2927     /* Evaluate the rhs */
2928     MarkedExprWithCheck (hie1, &Expr2);
2929
2930     /* The rhs must be an integer (or a float, but we don't support that yet */
2931     if (!IsClassInt (Expr2.Type)) {
2932         Error ("Invalid right operand for binary operator `%s'", Op);
2933         /* Continue. Wrong code will be generated, but the compiler won't
2934          * break, so this is the best error recovery.
2935          */
2936     }
2937
2938     /* Check for a constant expression */
2939     if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) {
2940         /* The resulting value is a constant. If the generator has the NOPUSH
2941          * flag set, don't push the lhs.
2942          */
2943         if (Gen->Flags & GEN_NOPUSH) {
2944             RemoveCode (&Mark);
2945         }
2946         if (MustScale) {
2947             /* lhs is a pointer, scale rhs */
2948             Expr2.IVal *= CheckedSizeOf (Expr->Type+1);
2949         }
2950
2951         /* If the lhs is character sized, the operation may be later done
2952          * with characters.
2953          */
2954         if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
2955             flags |= CF_FORCECHAR;
2956         }
2957
2958         /* Special handling for add and sub - some sort of a hack, but short code */
2959         if (Gen->Func == g_add) {
2960             g_inc (flags | CF_CONST, Expr2.IVal);
2961         } else if (Gen->Func == g_sub) {
2962             g_dec (flags | CF_CONST, Expr2.IVal);
2963         } else {
2964             if (Expr2.IVal == 0) {
2965                 /* Check for div by zero/mod by zero */
2966                 if (Gen->Func == g_div) {
2967                     Error ("Division by zero");
2968                 } else if (Gen->Func == g_mod) {
2969                     Error ("Modulo operation with zero");
2970                 }
2971             }
2972             Gen->Func (flags | CF_CONST, Expr2.IVal);
2973         }
2974     } else {
2975
2976         /* rhs is not constant. Load into the primary */
2977         LoadExpr (CF_NONE, &Expr2);
2978         if (MustScale) {
2979             /* lhs is a pointer, scale rhs */
2980             g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Expr->Type+1));
2981         }
2982
2983         /* If the lhs is character sized, the operation may be later done
2984          * with characters.
2985          */
2986         if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
2987             flags |= CF_FORCECHAR;
2988         }
2989
2990         /* Adjust the types of the operands if needed */
2991         Gen->Func (g_typeadjust (flags, TypeOf (Expr2.Type)), 0);
2992     }
2993     Store (Expr, 0);
2994     ED_MakeRValExpr (Expr);
2995 }
2996
2997
2998
2999 static void addsubeq (const GenDesc* Gen, ExprDesc *Expr, const char* Op)
3000 /* Process the += and -= operators */
3001 {
3002     ExprDesc Expr2;
3003     unsigned lflags;
3004     unsigned rflags;
3005     int      MustScale;
3006
3007
3008     /* We're currently only able to handle some adressing modes */
3009     if (ED_GetLoc (Expr) == E_LOC_EXPR || ED_GetLoc (Expr) == E_LOC_PRIMARY) {
3010         /* Use generic routine */
3011         opeq (Gen, Expr, Op);
3012         return;
3013     }
3014
3015     /* We must have an lvalue */
3016     if (ED_IsRVal (Expr)) {
3017         Error ("Invalid lvalue in assignment");
3018         return;
3019     }
3020
3021     /* The left side must not be const qualified */
3022     if (IsQualConst (Expr->Type)) {
3023         Error ("Assignment to const");
3024     }
3025
3026     /* There must be an integer or pointer on the left side */
3027     if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
3028         Error ("Invalid left operand type");
3029         /* Continue. Wrong code will be generated, but the compiler won't
3030          * break, so this is the best error recovery.
3031          */
3032     }
3033
3034     /* Skip the operator */
3035     NextToken ();
3036
3037     /* Check if we have a pointer expression and must scale rhs */
3038     MustScale = IsTypePtr (Expr->Type);
3039
3040     /* Initialize the code generator flags */
3041     lflags = 0;
3042     rflags = 0;
3043
3044     /* Evaluate the rhs. We expect an integer here, since float is not
3045      * supported
3046      */
3047     hie1 (&Expr2);
3048     if (!IsClassInt (Expr2.Type)) {
3049         Error ("Invalid right operand for binary operator `%s'", Op);
3050         /* Continue. Wrong code will be generated, but the compiler won't
3051          * break, so this is the best error recovery.
3052          */
3053     }
3054     if (ED_IsConstAbs (&Expr2)) {
3055         /* The resulting value is a constant. Scale it. */
3056         if (MustScale) {
3057             Expr2.IVal *= CheckedSizeOf (Indirect (Expr->Type));
3058         }
3059         rflags |= CF_CONST;
3060         lflags |= CF_CONST;
3061     } else {
3062         /* Not constant, load into the primary */
3063         LoadExpr (CF_NONE, &Expr2);
3064         if (MustScale) {
3065             /* lhs is a pointer, scale rhs */
3066             g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Indirect (Expr->Type)));
3067         }
3068     }
3069
3070     /* Setup the code generator flags */
3071     lflags |= TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR;
3072     rflags |= TypeOf (Expr2.Type) | CF_FORCECHAR;
3073
3074     /* Convert the type of the lhs to that of the rhs */
3075     g_typecast (lflags, rflags);
3076
3077     /* Output apropriate code depending on the location */
3078     switch (ED_GetLoc (Expr)) {
3079
3080         case E_LOC_ABS:
3081             /* Absolute: numeric address or const */
3082             if (Gen->Tok == TOK_PLUS_ASSIGN) {
3083                 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3084             } else {
3085                 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3086             }
3087             break;
3088
3089         case E_LOC_GLOBAL:
3090             /* Global variable */
3091             if (Gen->Tok == TOK_PLUS_ASSIGN) {
3092                 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3093             } else {
3094                 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3095             }
3096             break;
3097
3098         case E_LOC_STATIC:
3099         case E_LOC_LITERAL:
3100             /* Static variable or literal in the literal pool */
3101             if (Gen->Tok == TOK_PLUS_ASSIGN) {
3102                 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3103             } else {
3104                 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3105             }
3106             break;
3107
3108         case E_LOC_REGISTER:
3109             /* Register variable */
3110             if (Gen->Tok == TOK_PLUS_ASSIGN) {
3111                 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3112             } else {
3113                 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3114             }
3115             break;
3116
3117         case E_LOC_STACK:
3118             /* Value on the stack */
3119             if (Gen->Tok == TOK_PLUS_ASSIGN) {
3120                 g_addeqlocal (lflags, Expr->IVal, Expr2.IVal);
3121             } else {
3122                 g_subeqlocal (lflags, Expr->IVal, Expr2.IVal);
3123             }
3124             break;
3125
3126         default:
3127             Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
3128     }
3129
3130     /* Expression is a rvalue in the primary now */
3131     ED_MakeRValExpr (Expr);
3132 }
3133
3134
3135
3136 void hie1 (ExprDesc* Expr)
3137 /* Parse first level of expression hierarchy. */
3138 {
3139     hieQuest (Expr);
3140     switch (CurTok.Tok) {
3141
3142         case TOK_ASSIGN:
3143             Assignment (Expr);
3144             break;
3145
3146         case TOK_PLUS_ASSIGN:
3147             addsubeq (&GenPASGN, Expr, "+=");
3148             break;
3149
3150         case TOK_MINUS_ASSIGN:
3151             addsubeq (&GenSASGN, Expr, "-=");
3152             break;
3153
3154         case TOK_MUL_ASSIGN:
3155             opeq (&GenMASGN, Expr, "*=");
3156             break;
3157
3158         case TOK_DIV_ASSIGN:
3159             opeq (&GenDASGN, Expr, "/=");
3160             break;
3161
3162         case TOK_MOD_ASSIGN:
3163             opeq (&GenMOASGN, Expr, "%=");
3164             break;
3165
3166         case TOK_SHL_ASSIGN:
3167             opeq (&GenSLASGN, Expr, "<<=");
3168             break;
3169
3170         case TOK_SHR_ASSIGN:
3171             opeq (&GenSRASGN, Expr, ">>=");
3172             break;
3173
3174         case TOK_AND_ASSIGN:
3175             opeq (&GenAASGN, Expr, "&=");
3176             break;
3177
3178         case TOK_XOR_ASSIGN:
3179             opeq (&GenXOASGN, Expr, "^=");
3180             break;
3181
3182         case TOK_OR_ASSIGN:
3183             opeq (&GenOASGN, Expr, "|=");
3184             break;
3185
3186         default:
3187             break;
3188     }
3189 }
3190
3191
3192
3193 void hie0 (ExprDesc *Expr)
3194 /* Parse comma operator. */
3195 {
3196     hie1 (Expr);
3197     while (CurTok.Tok == TOK_COMMA) {
3198         NextToken ();
3199         hie1 (Expr);
3200     }
3201 }
3202
3203
3204
3205 int evalexpr (unsigned Flags, void (*Func) (ExprDesc*), ExprDesc* Expr)
3206 /* Will evaluate an expression via the given function. If the result is a
3207  * constant, 0 is returned and the value is put in the Expr struct. If the
3208  * result is not constant, LoadExpr is called to bring the value into the
3209  * primary register and 1 is returned.
3210  */
3211 {
3212     /* Evaluate */
3213     ExprWithCheck (Func, Expr);
3214
3215     /* Check for a constant expression */
3216     if (ED_IsConstAbs (Expr)) {
3217         /* Constant expression */
3218         return 0;
3219     } else {
3220         /* Not constant, load into the primary */
3221         LoadExpr (Flags, Expr);
3222         return 1;
3223     }
3224 }
3225
3226
3227
3228 void Expression0 (ExprDesc* Expr)
3229 /* Evaluate an expression via hie0 and put the result into the primary register */
3230 {
3231     ExprWithCheck (hie0, Expr);
3232     LoadExpr (CF_NONE, Expr);
3233 }
3234
3235
3236
3237 void ConstExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3238 /* Will evaluate an expression via the given function. If the result is not
3239  * a constant of some sort, a diagnostic will be printed, and the value is
3240  * replaced by a constant one to make sure there are no internal errors that
3241  * result from this input error.
3242  */
3243 {
3244     ExprWithCheck (Func, Expr);
3245     if (!ED_IsConst (Expr)) {
3246         Error ("Constant expression expected");
3247         /* To avoid any compiler errors, make the expression a valid const */
3248         ED_MakeConstAbsInt (Expr, 1);
3249     }
3250 }
3251
3252
3253
3254 void BoolExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3255 /* Will evaluate an expression via the given function. If the result is not
3256  * something that may be evaluated in a boolean context, a diagnostic will be
3257  * printed, and the value is replaced by a constant one to make sure there
3258  * are no internal errors that result from this input error.
3259  */
3260 {
3261     ExprWithCheck (Func, Expr);
3262     if (!ED_IsBool (Expr)) {
3263         Error ("Boolean expression expected");
3264         /* To avoid any compiler errors, make the expression a valid int */
3265         ED_MakeConstAbsInt (Expr, 1);
3266     }
3267 }
3268
3269
3270
3271 void ConstAbsIntExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3272 /* Will evaluate an expression via the given function. If the result is not
3273  * a constant numeric integer value, a diagnostic will be printed, and the
3274  * value is replaced by a constant one to make sure there are no internal
3275  * errors that result from this input error.
3276  */
3277 {
3278     ExprWithCheck (Func, Expr);
3279     if (!ED_IsConstAbsInt (Expr)) {
3280         Error ("Constant integer expression expected");
3281         /* To avoid any compiler errors, make the expression a valid const */
3282         ED_MakeConstAbsInt (Expr, 1);
3283     }
3284 }
3285
3286
3287