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