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