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