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