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