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