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