]> git.sur5r.net Git - cc65/blob - src/cc65/expr.c
Rename trampoline to wrappedcall everywhere
[cc65] / src / cc65 / expr.c
1 /* expr.c
2 **
3 ** 1998-06-21, Ullrich von Bassewitz
4 ** 2015-06-26, 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_IDENT:
700             /* Identifier. Get a pointer to the symbol table entry */
701             Sym = E->Sym = FindSym (CurTok.Ident);
702
703             /* Is the symbol known? */
704             if (Sym) {
705
706                 /* We found the symbol - skip the name token */
707                 NextToken ();
708
709                 /* Check for illegal symbol types */
710                 CHECK ((Sym->Flags & SC_LABEL) != SC_LABEL);
711                 if (Sym->Flags & SC_TYPE) {
712                     /* Cannot use type symbols */
713                     Error ("Variable identifier expected");
714                     /* Assume an int type to make E valid */
715                     E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
716                     E->Type  = type_int;
717                     return;
718                 }
719
720                 /* Mark the symbol as referenced */
721                 Sym->Flags |= SC_REF;
722
723                 /* The expression type is the symbol type */
724                 E->Type = Sym->Type;
725
726                 /* Check for legal symbol types */
727                 if ((Sym->Flags & SC_CONST) == SC_CONST) {
728                     /* Enum or some other numeric constant */
729                     E->Flags = E_LOC_ABS | E_RTYPE_RVAL;
730                     E->IVal = Sym->V.ConstVal;
731                 } else if ((Sym->Flags & SC_FUNC) == SC_FUNC) {
732                     /* Function */
733                     E->Flags = E_LOC_GLOBAL | E_RTYPE_LVAL;
734                     E->Name = (unsigned long) Sym->Name;
735                 } else if ((Sym->Flags & SC_AUTO) == SC_AUTO) {
736                     /* Local variable. If this is a parameter for a variadic
737                     ** function, we have to add some address calculations, and the
738                     ** address is not const.
739                     */
740                     if ((Sym->Flags & SC_PARAM) == SC_PARAM && F_IsVariadic (CurrentFunc)) {
741                         /* Variadic parameter */
742                         g_leavariadic (Sym->V.Offs - F_GetParamSize (CurrentFunc));
743                         E->Flags = E_LOC_EXPR | E_RTYPE_LVAL;
744                     } else {
745                         /* Normal parameter */
746                         E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
747                         E->IVal  = Sym->V.Offs;
748                     }
749                 } else if ((Sym->Flags & SC_REGISTER) == SC_REGISTER) {
750                     /* Register variable, zero page based */
751                     E->Flags = E_LOC_REGISTER | E_RTYPE_LVAL;
752                     E->Name  = Sym->V.R.RegOffs;
753                 } else if ((Sym->Flags & SC_STATIC) == SC_STATIC) {
754                     /* Static variable */
755                     if (Sym->Flags & (SC_EXTERN | SC_STORAGE)) {
756                         E->Flags = E_LOC_GLOBAL | E_RTYPE_LVAL;
757                         E->Name = (unsigned long) Sym->Name;
758                     } else {
759                         E->Flags = E_LOC_STATIC | E_RTYPE_LVAL;
760                         E->Name = Sym->V.Label;
761                     }
762                 } else {
763                     /* Local static variable */
764                     E->Flags = E_LOC_STATIC | E_RTYPE_LVAL;
765                     E->Name  = Sym->V.Offs;
766                 }
767
768                 /* We've made all variables lvalues above. However, this is
769                 ** not always correct: An array is actually the address of its
770                 ** first element, which is a rvalue, and a function is a
771                 ** rvalue, too, because we cannot store anything in a function.
772                 ** So fix the flags depending on the type.
773                 */
774                 if (IsTypeArray (E->Type) || IsTypeFunc (E->Type)) {
775                     ED_MakeRVal (E);
776                 }
777
778             } else {
779
780                 /* We did not find the symbol. Remember the name, then skip it */
781                 ident Ident;
782                 strcpy (Ident, CurTok.Ident);
783                 NextToken ();
784
785                 /* IDENT is either an auto-declared function or an undefined variable. */
786                 if (CurTok.Tok == TOK_LPAREN) {
787                     /* C99 doesn't allow calls to undefined functions, so
788                     ** generate an error and otherwise a warning. Declare a
789                     ** function returning int. For that purpose, prepare a
790                     ** function signature for a function having an empty param
791                     ** list and returning int.
792                     */
793                     if (IS_Get (&Standard) >= STD_C99) {
794                         Error ("Call to undefined function `%s'", Ident);
795                     } else {
796                         Warning ("Call to undefined function `%s'", Ident);
797                     }
798                     Sym = AddGlobalSym (Ident, GetImplicitFuncType(), SC_EXTERN | SC_REF | SC_FUNC);
799                     E->Type  = Sym->Type;
800                     E->Flags = E_LOC_GLOBAL | E_RTYPE_RVAL;
801                     E->Name  = (unsigned long) Sym->Name;
802                 } else {
803                     /* Undeclared Variable */
804                     Sym = AddLocalSym (Ident, type_int, SC_AUTO | SC_REF, 0);
805                     E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
806                     E->Type = type_int;
807                     Error ("Undefined symbol: `%s'", Ident);
808                 }
809
810             }
811             break;
812
813         case TOK_SCONST:
814         case TOK_WCSCONST:
815             /* String literal */
816             E->LVal  = UseLiteral (CurTok.SVal);
817             E->Type  = GetCharArrayType (GetLiteralSize (CurTok.SVal));
818             E->Flags = E_LOC_LITERAL | E_RTYPE_RVAL;
819             E->IVal  = 0;
820             E->Name  = GetLiteralLabel (CurTok.SVal);
821             NextToken ();
822             break;
823
824         case TOK_ASM:
825             /* ASM statement */
826             AsmStatement ();
827             E->Flags = E_LOC_EXPR | E_RTYPE_RVAL;
828             E->Type  = type_void;
829             break;
830
831         case TOK_A:
832             /* Register pseudo variable */
833             E->Type  = type_uchar;
834             E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
835             NextToken ();
836             break;
837
838         case TOK_AX:
839             /* Register pseudo variable */
840             E->Type  = type_uint;
841             E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
842             NextToken ();
843             break;
844
845         case TOK_EAX:
846             /* Register pseudo variable */
847             E->Type  = type_ulong;
848             E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
849             NextToken ();
850             break;
851
852         default:
853             /* Illegal primary. Be sure to skip the token to avoid endless
854             ** error loops.
855             */
856             Error ("Expression expected");
857             NextToken ();
858             ED_MakeConstAbsInt (E, 1);
859             break;
860     }
861 }
862
863
864
865 static void ArrayRef (ExprDesc* Expr)
866 /* Handle an array reference. This function needs a rewrite. */
867 {
868     int         ConstBaseAddr;
869     ExprDesc    Subscript;
870     CodeMark    Mark1;
871     CodeMark    Mark2;
872     TypeCode    Qualifiers;
873     Type*       ElementType;
874     Type*       tptr1;
875
876
877     /* Skip the bracket */
878     NextToken ();
879
880     /* Get the type of left side */
881     tptr1 = Expr->Type;
882
883     /* We can apply a special treatment for arrays that have a const base
884     ** address. This is true for most arrays and will produce a lot better
885     ** code. Check if this is a const base address.
886     */
887     ConstBaseAddr = ED_IsRVal (Expr) &&
888                     (ED_IsLocConst (Expr) || ED_IsLocStack (Expr));
889
890     /* If we have a constant base, we delay the address fetch */
891     GetCodePos (&Mark1);
892     if (!ConstBaseAddr) {
893         /* Get a pointer to the array into the primary */
894         LoadExpr (CF_NONE, Expr);
895
896         /* Get the array pointer on stack. Do not push more than 16
897         ** bit, even if this value is greater, since we cannot handle
898         ** other than 16bit stuff when doing indexing.
899         */
900         GetCodePos (&Mark2);
901         g_push (CF_PTR, 0);
902     }
903
904     /* TOS now contains ptr to array elements. Get the subscript. */
905     MarkedExprWithCheck (hie0, &Subscript);
906
907     /* Check the types of array and subscript. We can either have a
908     ** pointer/array to the left, in which case the subscript must be of an
909     ** integer type, or we have an integer to the left, in which case the
910     ** subscript must be a pointer/array.
911     ** Since we do the necessary checking here, we can rely later on the
912     ** correct types.
913     */
914     Qualifiers = T_QUAL_NONE;
915     if (IsClassPtr (Expr->Type)) {
916         if (!IsClassInt (Subscript.Type))  {
917             Error ("Array subscript is not an integer");
918             /* To avoid any compiler errors, make the expression a valid int */
919             ED_MakeConstAbsInt (&Subscript, 0);
920         }
921         if (IsTypeArray (Expr->Type)) {
922             Qualifiers = GetQualifier (Expr->Type);
923         }
924         ElementType = Indirect (Expr->Type);
925     } else if (IsClassInt (Expr->Type)) {
926         if (!IsClassPtr (Subscript.Type)) {
927             Error ("Subscripted value is neither array nor pointer");
928             /* To avoid compiler errors, make the subscript a char[] at
929             ** address 0.
930             */
931             ED_MakeConstAbs (&Subscript, 0, GetCharArrayType (1));
932         } else if (IsTypeArray (Subscript.Type)) {
933             Qualifiers = GetQualifier (Subscript.Type);
934         }
935         ElementType = Indirect (Subscript.Type);
936     } else {
937         Error ("Cannot subscript");
938         /* To avoid compiler errors, fake both the array and the subscript, so
939         ** we can just proceed.
940         */
941         ED_MakeConstAbs (Expr, 0, GetCharArrayType (1));
942         ED_MakeConstAbsInt (&Subscript, 0);
943         ElementType = Indirect (Expr->Type);
944     }
945
946     /* The element type has the combined qualifiers from itself and the array,
947     ** it is a member of (if any).
948     */
949     if (GetQualifier (ElementType) != (GetQualifier (ElementType) | Qualifiers)) {
950         ElementType = TypeDup (ElementType);
951         ElementType->C |= Qualifiers;
952     }
953
954     /* If the subscript is a bit-field, load it and make it an rvalue */
955     if (ED_IsBitField (&Subscript)) {
956         LoadExpr (CF_NONE, &Subscript);
957         ED_MakeRValExpr (&Subscript);
958     }
959
960     /* Check if the subscript is constant absolute value */
961     if (ED_IsConstAbs (&Subscript) && ED_CodeRangeIsEmpty (&Subscript)) {
962
963         /* The array subscript is a numeric constant. If we had pushed the
964         ** array base address onto the stack before, we can remove this value,
965         ** since we can generate expression+offset.
966         */
967         if (!ConstBaseAddr) {
968             RemoveCode (&Mark2);
969         } else {
970             /* Get an array pointer into the primary */
971             LoadExpr (CF_NONE, Expr);
972         }
973
974         if (IsClassPtr (Expr->Type)) {
975
976             /* Lhs is pointer/array. Scale the subscript value according to
977             ** the element size.
978             */
979             Subscript.IVal *= CheckedSizeOf (ElementType);
980
981             /* Remove the address load code */
982             RemoveCode (&Mark1);
983
984             /* In case of an array, we can adjust the offset of the expression
985             ** already in Expr. If the base address was a constant, we can even
986             ** remove the code that loaded the address into the primary.
987             */
988             if (IsTypeArray (Expr->Type)) {
989
990                 /* Adjust the offset */
991                 Expr->IVal += Subscript.IVal;
992
993             } else {
994
995                 /* It's a pointer, so we do have to load it into the primary
996                 ** first (if it's not already there).
997                 */
998                 if (ConstBaseAddr || ED_IsLVal (Expr)) {
999                     LoadExpr (CF_NONE, Expr);
1000                     ED_MakeRValExpr (Expr);
1001                 }
1002
1003                 /* Use the offset */
1004                 Expr->IVal = Subscript.IVal;
1005             }
1006
1007         } else {
1008
1009             /* Scale the rhs value according to the element type */
1010             g_scale (TypeOf (tptr1), CheckedSizeOf (ElementType));
1011
1012             /* Add the subscript. Since arrays are indexed by integers,
1013             ** we will ignore the true type of the subscript here and
1014             ** use always an int. #### Use offset but beware of LoadExpr!
1015             */
1016             g_inc (CF_INT | CF_CONST, Subscript.IVal);
1017
1018         }
1019
1020     } else {
1021
1022         /* Array subscript is not constant. Load it into the primary */
1023         GetCodePos (&Mark2);
1024         LoadExpr (CF_NONE, &Subscript);
1025
1026         /* Do scaling */
1027         if (IsClassPtr (Expr->Type)) {
1028
1029             /* Indexing is based on unsigneds, so we will just use the integer
1030             ** portion of the index (which is in (e)ax, so there's no further
1031             ** action required).
1032             */
1033             g_scale (CF_INT, CheckedSizeOf (ElementType));
1034
1035         } else {
1036
1037             /* Get the int value on top. If we come here, we're sure, both
1038             ** values are 16 bit (the first one was truncated if necessary
1039             ** and the second one is a pointer). Note: If ConstBaseAddr is
1040             ** true, we don't have a value on stack, so to "swap" both, just
1041             ** push the subscript.
1042             */
1043             if (ConstBaseAddr) {
1044                 g_push (CF_INT, 0);
1045                 LoadExpr (CF_NONE, Expr);
1046                 ConstBaseAddr = 0;
1047             } else {
1048                 g_swap (CF_INT);
1049             }
1050
1051             /* Scale it */
1052             g_scale (TypeOf (tptr1), CheckedSizeOf (ElementType));
1053
1054         }
1055
1056         /* The offset is now in the primary register. It we didn't have a
1057         ** constant base address for the lhs, the lhs address is already
1058         ** on stack, and we must add the offset. If the base address was
1059         ** constant, we call special functions to add the address to the
1060         ** offset value.
1061         */
1062         if (!ConstBaseAddr) {
1063
1064             /* The array base address is on stack and the subscript is in the
1065             ** primary. Add both.
1066             */
1067             g_add (CF_INT, 0);
1068
1069         } else {
1070
1071             /* The subscript is in the primary, and the array base address is
1072             ** in Expr. If the subscript has itself a constant address, it is
1073             ** often a better idea to reverse again the order of the
1074             ** evaluation. This will generate better code if the subscript is
1075             ** a byte sized variable. But beware: This is only possible if the
1076             ** subscript was not scaled, that is, if this was a byte array
1077             ** or pointer.
1078             */
1079             if ((ED_IsLocConst (&Subscript) || ED_IsLocStack (&Subscript)) &&
1080                 CheckedSizeOf (ElementType) == SIZEOF_CHAR) {
1081
1082                 unsigned Flags;
1083
1084                 /* Reverse the order of evaluation */
1085                 if (CheckedSizeOf (Subscript.Type) == SIZEOF_CHAR) {
1086                     Flags = CF_CHAR;
1087                 } else {
1088                     Flags = CF_INT;
1089                 }
1090                 RemoveCode (&Mark2);
1091
1092                 /* Get a pointer to the array into the primary. */
1093                 LoadExpr (CF_NONE, Expr);
1094
1095                 /* Add the variable */
1096                 if (ED_IsLocStack (&Subscript)) {
1097                     g_addlocal (Flags, Subscript.IVal);
1098                 } else {
1099                     Flags |= GlobalModeFlags (&Subscript);
1100                     g_addstatic (Flags, Subscript.Name, Subscript.IVal);
1101                 }
1102             } else {
1103
1104                 if (ED_IsLocAbs (Expr)) {
1105                     /* Constant numeric address. Just add it */
1106                     g_inc (CF_INT, Expr->IVal);
1107                 } else if (ED_IsLocStack (Expr)) {
1108                     /* Base address is a local variable address */
1109                     if (IsTypeArray (Expr->Type)) {
1110                         g_addaddr_local (CF_INT, Expr->IVal);
1111                     } else {
1112                         g_addlocal (CF_PTR, Expr->IVal);
1113                     }
1114                 } else {
1115                     /* Base address is a static variable address */
1116                     unsigned Flags = CF_INT | GlobalModeFlags (Expr);
1117                     if (ED_IsRVal (Expr)) {
1118                         /* Add the address of the location */
1119                         g_addaddr_static (Flags, Expr->Name, Expr->IVal);
1120                     } else {
1121                         /* Add the contents of the location */
1122                         g_addstatic (Flags, Expr->Name, Expr->IVal);
1123                     }
1124                 }
1125             }
1126
1127
1128         }
1129
1130         /* The result is an expression in the primary */
1131         ED_MakeRValExpr (Expr);
1132
1133     }
1134
1135     /* Result is of element type */
1136     Expr->Type = ElementType;
1137
1138     /* An array element is actually a variable. So the rules for variables
1139     ** with respect to the reference type apply: If it's an array, it is
1140     ** a rvalue, otherwise it's an lvalue. (A function would also be a rvalue,
1141     ** but an array cannot contain functions).
1142     */
1143     if (IsTypeArray (Expr->Type)) {
1144         ED_MakeRVal (Expr);
1145     } else {
1146         ED_MakeLVal (Expr);
1147     }
1148
1149     /* Consume the closing bracket */
1150     ConsumeRBrack ();
1151 }
1152
1153
1154
1155 static void StructRef (ExprDesc* Expr)
1156 /* Process struct field after . or ->. */
1157 {
1158     ident Ident;
1159     SymEntry* Field;
1160     Type* FinalType;
1161     TypeCode Q;
1162
1163     /* Skip the token and check for an identifier */
1164     NextToken ();
1165     if (CurTok.Tok != TOK_IDENT) {
1166         Error ("Identifier expected");
1167         /* Make the expression an integer at address zero */
1168         ED_MakeConstAbs (Expr, 0, type_int);
1169         return;
1170     }
1171
1172     /* Get the symbol table entry and check for a struct field */
1173     strcpy (Ident, CurTok.Ident);
1174     NextToken ();
1175     Field = FindStructField (Expr->Type, Ident);
1176     if (Field == 0) {
1177         Error ("Struct/union has no field named `%s'", Ident);
1178         /* Make the expression an integer at address zero */
1179         ED_MakeConstAbs (Expr, 0, type_int);
1180         return;
1181     }
1182
1183     /* If we have a struct pointer that is an lvalue and not already in the
1184     ** primary, load it now.
1185     */
1186     if (ED_IsLVal (Expr) && IsTypePtr (Expr->Type)) {
1187
1188         /* Load into the primary */
1189         LoadExpr (CF_NONE, Expr);
1190
1191         /* Make it an lvalue expression */
1192         ED_MakeLValExpr (Expr);
1193     }
1194
1195     /* The type is the type of the field plus any qualifiers from the struct */
1196     if (IsClassStruct (Expr->Type)) {
1197         Q = GetQualifier (Expr->Type);
1198     } else {
1199         Q = GetQualifier (Indirect (Expr->Type));
1200     }
1201     if (GetQualifier (Field->Type) == (GetQualifier (Field->Type) | Q)) {
1202         FinalType = Field->Type;
1203     } else {
1204         FinalType = TypeDup (Field->Type);
1205         FinalType->C |= Q;
1206     }
1207
1208     /* A struct is usually an lvalue. If not, it is a struct in the primary
1209     ** register.
1210     */
1211     if (ED_IsRVal (Expr) && ED_IsLocExpr (Expr) && !IsTypePtr (Expr->Type)) {
1212
1213         unsigned Flags = 0;
1214         unsigned BitOffs;
1215
1216         /* Get the size of the type */
1217         unsigned Size = SizeOf (Expr->Type);
1218
1219         /* Safety check */
1220         CHECK (Field->V.Offs + Size <= SIZEOF_LONG);
1221
1222         /* The type of the operation depends on the type of the struct */
1223         switch (Size) {
1224             case 1:     Flags = CF_CHAR | CF_UNSIGNED | CF_CONST;       break;
1225             case 2:     Flags = CF_INT  | CF_UNSIGNED | CF_CONST;       break;
1226             case 3:     /* FALLTHROUGH */
1227             case 4:     Flags = CF_LONG | CF_UNSIGNED | CF_CONST;       break;
1228             default:    Internal ("Invalid struct size: %u", Size);     break;
1229         }
1230
1231         /* Generate a shift to get the field in the proper position in the
1232         ** primary. For bit fields, mask the value.
1233         */
1234         BitOffs = Field->V.Offs * CHAR_BITS;
1235         if (SymIsBitField (Field)) {
1236             BitOffs += Field->V.B.BitOffs;
1237             g_asr (Flags, BitOffs);
1238             /* Mask the value. This is unnecessary if the shift executed above
1239             ** moved only zeroes into the value.
1240             */
1241             if (BitOffs + Field->V.B.BitWidth != Size * CHAR_BITS) {
1242                 g_and (CF_INT | CF_UNSIGNED | CF_CONST,
1243                        (0x0001U << Field->V.B.BitWidth) - 1U);
1244             }
1245         } else {
1246             g_asr (Flags, BitOffs);
1247         }
1248
1249         /* Use the new type */
1250         Expr->Type = FinalType;
1251
1252     } else {
1253
1254         /* Set the struct field offset */
1255         Expr->IVal += Field->V.Offs;
1256
1257         /* Use the new type */
1258         Expr->Type = FinalType;
1259
1260         /* An struct member is actually a variable. So the rules for variables
1261         ** with respect to the reference type apply: If it's an array, it is
1262         ** a rvalue, otherwise it's an lvalue. (A function would also be a rvalue,
1263         ** but a struct field cannot be a function).
1264         */
1265         if (IsTypeArray (Expr->Type)) {
1266             ED_MakeRVal (Expr);
1267         } else {
1268             ED_MakeLVal (Expr);
1269         }
1270
1271         /* Make the expression a bit field if necessary */
1272         if (SymIsBitField (Field)) {
1273             ED_MakeBitField (Expr, Field->V.B.BitOffs, Field->V.B.BitWidth);
1274         }
1275     }
1276
1277 }
1278
1279
1280
1281 static void hie11 (ExprDesc *Expr)
1282 /* Handle compound types (structs and arrays) */
1283 {
1284     /* Name value used in invalid function calls */
1285     static const char IllegalFunc[] = "illegal_function_call";
1286
1287     /* Evaluate the lhs */
1288     Primary (Expr);
1289
1290     /* Check for a rhs */
1291     while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN ||
1292            CurTok.Tok == TOK_DOT    || CurTok.Tok == TOK_PTR_REF) {
1293
1294         switch (CurTok.Tok) {
1295
1296             case TOK_LBRACK:
1297                 /* Array reference */
1298                 ArrayRef (Expr);
1299                 break;
1300
1301             case TOK_LPAREN:
1302                 /* Function call. */
1303                 if (!IsTypeFunc (Expr->Type) && !IsTypeFuncPtr (Expr->Type)) {
1304                     /* Not a function */
1305                     Error ("Illegal function call");
1306                     /* Force the type to be a implicitly defined function, one
1307                     ** returning an int and taking any number of arguments.
1308                     ** Since we don't have a name, invent one.
1309                     */
1310                     ED_MakeConstAbs (Expr, 0, GetImplicitFuncType ());
1311                     Expr->Name = (long) IllegalFunc;
1312                 }
1313                 /* Call the function */
1314                 FunctionCall (Expr);
1315                 break;
1316
1317             case TOK_DOT:
1318                 if (!IsClassStruct (Expr->Type)) {
1319                     Error ("Struct expected");
1320                 }
1321                 StructRef (Expr);
1322                 break;
1323
1324             case TOK_PTR_REF:
1325                 /* If we have an array, convert it to pointer to first element */
1326                 if (IsTypeArray (Expr->Type)) {
1327                     Expr->Type = ArrayToPtr (Expr->Type);
1328                 }
1329                 if (!IsClassPtr (Expr->Type) || !IsClassStruct (Indirect (Expr->Type))) {
1330                     Error ("Struct pointer expected");
1331                 }
1332                 StructRef (Expr);
1333                 break;
1334
1335             default:
1336                 Internal ("Invalid token in hie11: %d", CurTok.Tok);
1337
1338         }
1339     }
1340 }
1341
1342
1343
1344 void Store (ExprDesc* Expr, const Type* StoreType)
1345 /* Store the primary register into the location denoted by Expr. If StoreType
1346 ** is given, use this type when storing instead of Expr->Type. If StoreType
1347 ** is NULL, use Expr->Type instead.
1348 */
1349 {
1350     unsigned Flags;
1351
1352     /* If StoreType was not given, use Expr->Type instead */
1353     if (StoreType == 0) {
1354         StoreType = Expr->Type;
1355     }
1356
1357     /* Prepare the code generator flags */
1358     Flags = TypeOf (StoreType) | GlobalModeFlags (Expr);
1359
1360     /* Do the store depending on the location */
1361     switch (ED_GetLoc (Expr)) {
1362
1363         case E_LOC_ABS:
1364             /* Absolute: numeric address or const */
1365             g_putstatic (Flags, Expr->IVal, 0);
1366             break;
1367
1368         case E_LOC_GLOBAL:
1369             /* Global variable */
1370             g_putstatic (Flags, Expr->Name, Expr->IVal);
1371             break;
1372
1373         case E_LOC_STATIC:
1374         case E_LOC_LITERAL:
1375             /* Static variable or literal in the literal pool */
1376             g_putstatic (Flags, Expr->Name, Expr->IVal);
1377             break;
1378
1379         case E_LOC_REGISTER:
1380             /* Register variable */
1381             g_putstatic (Flags, Expr->Name, Expr->IVal);
1382             break;
1383
1384         case E_LOC_STACK:
1385             /* Value on the stack */
1386             g_putlocal (Flags, Expr->IVal, 0);
1387             break;
1388
1389         case E_LOC_PRIMARY:
1390             /* The primary register (value is already there) */
1391             break;
1392
1393         case E_LOC_EXPR:
1394             /* An expression in the primary register */
1395             g_putind (Flags, Expr->IVal);
1396             break;
1397
1398         default:
1399             Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
1400     }
1401
1402     /* Assume that each one of the stores will invalidate CC */
1403     ED_MarkAsUntested (Expr);
1404 }
1405
1406
1407
1408 static void PreInc (ExprDesc* Expr)
1409 /* Handle the preincrement operators */
1410 {
1411     unsigned Flags;
1412     unsigned long Val;
1413
1414     /* Skip the operator token */
1415     NextToken ();
1416
1417     /* Evaluate the expression and check that it is an lvalue */
1418     hie10 (Expr);
1419     if (!ED_IsLVal (Expr)) {
1420         Error ("Invalid lvalue");
1421         return;
1422     }
1423
1424     /* We cannot modify const values */
1425     if (IsQualConst (Expr->Type)) {
1426         Error ("Increment of read-only variable");
1427     }
1428
1429     /* Get the data type */
1430     Flags = TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR | CF_CONST;
1431
1432     /* Get the increment value in bytes */
1433     Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1434
1435     /* Check the location of the data */
1436     switch (ED_GetLoc (Expr)) {
1437
1438         case E_LOC_ABS:
1439             /* Absolute: numeric address or const */
1440             g_addeqstatic (Flags, Expr->IVal, 0, Val);
1441             break;
1442
1443         case E_LOC_GLOBAL:
1444             /* Global variable */
1445             g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1446             break;
1447
1448         case E_LOC_STATIC:
1449         case E_LOC_LITERAL:
1450             /* Static variable or literal in the literal pool */
1451             g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1452             break;
1453
1454         case E_LOC_REGISTER:
1455             /* Register variable */
1456             g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1457             break;
1458
1459         case E_LOC_STACK:
1460             /* Value on the stack */
1461             g_addeqlocal (Flags, Expr->IVal, Val);
1462             break;
1463
1464         case E_LOC_PRIMARY:
1465             /* The primary register */
1466             g_inc (Flags, Val);
1467             break;
1468
1469         case E_LOC_EXPR:
1470             /* An expression in the primary register */
1471             g_addeqind (Flags, Expr->IVal, Val);
1472             break;
1473
1474         default:
1475             Internal ("Invalid location in PreInc(): 0x%04X", ED_GetLoc (Expr));
1476     }
1477
1478     /* Result is an expression, no reference */
1479     ED_MakeRValExpr (Expr);
1480 }
1481
1482
1483
1484 static void PreDec (ExprDesc* Expr)
1485 /* Handle the predecrement operators */
1486 {
1487     unsigned Flags;
1488     unsigned long Val;
1489
1490     /* Skip the operator token */
1491     NextToken ();
1492
1493     /* Evaluate the expression and check that it is an lvalue */
1494     hie10 (Expr);
1495     if (!ED_IsLVal (Expr)) {
1496         Error ("Invalid lvalue");
1497         return;
1498     }
1499
1500     /* We cannot modify const values */
1501     if (IsQualConst (Expr->Type)) {
1502         Error ("Decrement of read-only variable");
1503     }
1504
1505     /* Get the data type */
1506     Flags = TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR | CF_CONST;
1507
1508     /* Get the increment value in bytes */
1509     Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1510
1511     /* Check the location of the data */
1512     switch (ED_GetLoc (Expr)) {
1513
1514         case E_LOC_ABS:
1515             /* Absolute: numeric address or const */
1516             g_subeqstatic (Flags, Expr->IVal, 0, Val);
1517             break;
1518
1519         case E_LOC_GLOBAL:
1520             /* Global variable */
1521             g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1522             break;
1523
1524         case E_LOC_STATIC:
1525         case E_LOC_LITERAL:
1526             /* Static variable or literal in the literal pool */
1527             g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1528             break;
1529
1530         case E_LOC_REGISTER:
1531             /* Register variable */
1532             g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1533             break;
1534
1535         case E_LOC_STACK:
1536             /* Value on the stack */
1537             g_subeqlocal (Flags, Expr->IVal, Val);
1538             break;
1539
1540         case E_LOC_PRIMARY:
1541             /* The primary register */
1542             g_inc (Flags, Val);
1543             break;
1544
1545         case E_LOC_EXPR:
1546             /* An expression in the primary register */
1547             g_subeqind (Flags, Expr->IVal, Val);
1548             break;
1549
1550         default:
1551             Internal ("Invalid location in PreDec(): 0x%04X", ED_GetLoc (Expr));
1552     }
1553
1554     /* Result is an expression, no reference */
1555     ED_MakeRValExpr (Expr);
1556 }
1557
1558
1559
1560 static void PostInc (ExprDesc* Expr)
1561 /* Handle the postincrement operator */
1562 {
1563     unsigned Flags;
1564
1565     NextToken ();
1566
1567     /* The expression to increment must be an lvalue */
1568     if (!ED_IsLVal (Expr)) {
1569         Error ("Invalid lvalue");
1570         return;
1571     }
1572
1573     /* We cannot modify const values */
1574     if (IsQualConst (Expr->Type)) {
1575         Error ("Increment of read-only variable");
1576     }
1577
1578     /* Get the data type */
1579     Flags = TypeOf (Expr->Type);
1580
1581     /* Push the address if needed */
1582     PushAddr (Expr);
1583
1584     /* Fetch the value and save it (since it's the result of the expression) */
1585     LoadExpr (CF_NONE, Expr);
1586     g_save (Flags | CF_FORCECHAR);
1587
1588     /* If we have a pointer expression, increment by the size of the type */
1589     if (IsTypePtr (Expr->Type)) {
1590         g_inc (Flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (Expr->Type + 1));
1591     } else {
1592         g_inc (Flags | CF_CONST | CF_FORCECHAR, 1);
1593     }
1594
1595     /* Store the result back */
1596     Store (Expr, 0);
1597
1598     /* Restore the original value in the primary register */
1599     g_restore (Flags | CF_FORCECHAR);
1600
1601     /* The result is always an expression, no reference */
1602     ED_MakeRValExpr (Expr);
1603 }
1604
1605
1606
1607 static void PostDec (ExprDesc* Expr)
1608 /* Handle the postdecrement operator */
1609 {
1610     unsigned Flags;
1611
1612     NextToken ();
1613
1614     /* The expression to increment must be an lvalue */
1615     if (!ED_IsLVal (Expr)) {
1616         Error ("Invalid lvalue");
1617         return;
1618     }
1619
1620     /* We cannot modify const values */
1621     if (IsQualConst (Expr->Type)) {
1622         Error ("Decrement of read-only variable");
1623     }
1624
1625     /* Get the data type */
1626     Flags = TypeOf (Expr->Type);
1627
1628     /* Push the address if needed */
1629     PushAddr (Expr);
1630
1631     /* Fetch the value and save it (since it's the result of the expression) */
1632     LoadExpr (CF_NONE, Expr);
1633     g_save (Flags | CF_FORCECHAR);
1634
1635     /* If we have a pointer expression, increment by the size of the type */
1636     if (IsTypePtr (Expr->Type)) {
1637         g_dec (Flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (Expr->Type + 1));
1638     } else {
1639         g_dec (Flags | CF_CONST | CF_FORCECHAR, 1);
1640     }
1641
1642     /* Store the result back */
1643     Store (Expr, 0);
1644
1645     /* Restore the original value in the primary register */
1646     g_restore (Flags | CF_FORCECHAR);
1647
1648     /* The result is always an expression, no reference */
1649     ED_MakeRValExpr (Expr);
1650 }
1651
1652
1653
1654 static void UnaryOp (ExprDesc* Expr)
1655 /* Handle unary -/+ and ~ */
1656 {
1657     unsigned Flags;
1658
1659     /* Remember the operator token and skip it */
1660     token_t Tok = CurTok.Tok;
1661     NextToken ();
1662
1663     /* Get the expression */
1664     hie10 (Expr);
1665
1666     /* We can only handle integer types */
1667     if (!IsClassInt (Expr->Type)) {
1668         Error ("Argument must have integer type");
1669         ED_MakeConstAbsInt (Expr, 1);
1670     }
1671
1672     /* Check for a constant expression */
1673     if (ED_IsConstAbs (Expr)) {
1674         /* Value is constant */
1675         switch (Tok) {
1676             case TOK_MINUS: Expr->IVal = -Expr->IVal;   break;
1677             case TOK_PLUS:                              break;
1678             case TOK_COMP:  Expr->IVal = ~Expr->IVal;   break;
1679             default:        Internal ("Unexpected token: %d", Tok);
1680         }
1681     } else {
1682         /* Value is not constant */
1683         LoadExpr (CF_NONE, Expr);
1684
1685         /* Get the type of the expression */
1686         Flags = TypeOf (Expr->Type);
1687
1688         /* Handle the operation */
1689         switch (Tok) {
1690             case TOK_MINUS: g_neg (Flags);  break;
1691             case TOK_PLUS:                  break;
1692             case TOK_COMP:  g_com (Flags);  break;
1693             default:        Internal ("Unexpected token: %d", Tok);
1694         }
1695
1696         /* The result is a rvalue in the primary */
1697         ED_MakeRValExpr (Expr);
1698     }
1699 }
1700
1701
1702
1703 void hie10 (ExprDesc* Expr)
1704 /* Handle ++, --, !, unary - etc. */
1705 {
1706     unsigned long Size;
1707
1708     switch (CurTok.Tok) {
1709
1710         case TOK_INC:
1711             PreInc (Expr);
1712             break;
1713
1714         case TOK_DEC:
1715             PreDec (Expr);
1716             break;
1717
1718         case TOK_PLUS:
1719         case TOK_MINUS:
1720         case TOK_COMP:
1721             UnaryOp (Expr);
1722             break;
1723
1724         case TOK_BOOL_NOT:
1725             NextToken ();
1726             if (evalexpr (CF_NONE, hie10, Expr) == 0) {
1727                 /* Constant expression */
1728                 Expr->IVal = !Expr->IVal;
1729             } else {
1730                 g_bneg (TypeOf (Expr->Type));
1731                 ED_MakeRValExpr (Expr);
1732                 ED_TestDone (Expr);             /* bneg will set cc */
1733             }
1734             break;
1735
1736         case TOK_STAR:
1737             NextToken ();
1738             ExprWithCheck (hie10, Expr);
1739             if (ED_IsLVal (Expr) || !(ED_IsLocConst (Expr) || ED_IsLocStack (Expr))) {
1740                 /* Not a const, load it into the primary and make it a
1741                 ** calculated value.
1742                 */
1743                 LoadExpr (CF_NONE, Expr);
1744                 ED_MakeRValExpr (Expr);
1745             }
1746             /* If the expression is already a pointer to function, the
1747             ** additional dereferencing operator must be ignored. A function
1748             ** itself is represented as "pointer to function", so any number
1749             ** of dereference operators is legal, since the result will
1750             ** always be converted to "pointer to function".
1751             */
1752             if (IsTypeFuncPtr (Expr->Type) || IsTypeFunc (Expr->Type)) {
1753                 /* Expression not storable */
1754                 ED_MakeRVal (Expr);
1755             } else {
1756                 if (IsClassPtr (Expr->Type)) {
1757                     Expr->Type = Indirect (Expr->Type);
1758                 } else {
1759                     Error ("Illegal indirection");
1760                 }
1761                 /* If the expression points to an array, then don't convert the
1762                 ** address -- it already is the location of the first element.
1763                 */
1764                 if (!IsTypeArray (Expr->Type)) {
1765                     /* The * operator yields an lvalue */
1766                     ED_MakeLVal (Expr);
1767                 }
1768             }
1769             break;
1770
1771         case TOK_AND:
1772             NextToken ();
1773             ExprWithCheck (hie10, Expr);
1774             /* The & operator may be applied to any lvalue, and it may be
1775             ** applied to functions, even if they're no lvalues.
1776             */
1777             if (ED_IsRVal (Expr) && !IsTypeFunc (Expr->Type) && !IsTypeArray (Expr->Type)) {
1778                 Error ("Illegal address");
1779             } else {
1780                 if (ED_IsBitField (Expr)) {
1781                     Error ("Cannot take address of bit-field");
1782                     /* Do it anyway, just to avoid further warnings */
1783                     Expr->Flags &= ~E_BITFIELD;
1784                 }
1785                 Expr->Type = PointerTo (Expr->Type);
1786                 /* The & operator yields an rvalue */
1787                 ED_MakeRVal (Expr);
1788             }
1789             break;
1790
1791         case TOK_SIZEOF:
1792             NextToken ();
1793             if (TypeSpecAhead ()) {
1794                 Type T[MAXTYPELEN];
1795                 NextToken ();
1796                 Size = CheckedSizeOf (ParseType (T));
1797                 ConsumeRParen ();
1798             } else {
1799                 /* Remember the output queue pointer */
1800                 CodeMark Mark;
1801                 GetCodePos (&Mark);
1802                 hie10 (Expr);
1803                 /* If the expression is a literal string, release it, so it
1804                 ** won't be output as data if not used elsewhere.
1805                 */
1806                 if (ED_IsLocLiteral (Expr)) {
1807                     ReleaseLiteral (Expr->LVal);
1808                 }
1809                 /* Calculate the size */
1810                 Size = CheckedSizeOf (Expr->Type);
1811                 /* Remove any generated code */
1812                 RemoveCode (&Mark);
1813             }
1814             ED_MakeConstAbs (Expr, Size, type_size_t);
1815             ED_MarkAsUntested (Expr);
1816             break;
1817
1818         default:
1819             if (TypeSpecAhead ()) {
1820
1821                 /* A typecast */
1822                 TypeCast (Expr);
1823
1824             } else {
1825
1826                 /* An expression */
1827                 hie11 (Expr);
1828
1829                 /* Handle post increment */
1830                 switch (CurTok.Tok) {
1831                     case TOK_INC:   PostInc (Expr); break;
1832                     case TOK_DEC:   PostDec (Expr); break;
1833                     default:                        break;
1834                 }
1835
1836             }
1837             break;
1838     }
1839 }
1840
1841
1842
1843 static void hie_internal (const GenDesc* Ops,   /* List of generators */
1844                           ExprDesc* Expr,
1845                           void (*hienext) (ExprDesc*),
1846                           int* UsedGen)
1847 /* Helper function */
1848 {
1849     ExprDesc Expr2;
1850     CodeMark Mark1;
1851     CodeMark Mark2;
1852     const GenDesc* Gen;
1853     token_t Tok;                        /* The operator token */
1854     unsigned ltype, type;
1855     int lconst;                         /* Left operand is a constant */
1856     int rconst;                         /* Right operand is a constant */
1857
1858
1859     ExprWithCheck (hienext, Expr);
1860
1861     *UsedGen = 0;
1862     while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
1863
1864         /* Tell the caller that we handled it's ops */
1865         *UsedGen = 1;
1866
1867         /* All operators that call this function expect an int on the lhs */
1868         if (!IsClassInt (Expr->Type)) {
1869             Error ("Integer expression expected");
1870             /* To avoid further errors, make Expr a valid int expression */
1871             ED_MakeConstAbsInt (Expr, 1);
1872         }
1873
1874         /* Remember the operator token, then skip it */
1875         Tok = CurTok.Tok;
1876         NextToken ();
1877
1878         /* Get the lhs on stack */
1879         GetCodePos (&Mark1);
1880         ltype = TypeOf (Expr->Type);
1881         lconst = ED_IsConstAbs (Expr);
1882         if (lconst) {
1883             /* Constant value */
1884             GetCodePos (&Mark2);
1885             /* If the operator is commutative, don't push the left side, if
1886             ** it's a constant, since we will exchange both operands.
1887             */
1888             if ((Gen->Flags & GEN_COMM) == 0) {
1889                 g_push (ltype | CF_CONST, Expr->IVal);
1890             }
1891         } else {
1892             /* Value not constant */
1893             LoadExpr (CF_NONE, Expr);
1894             GetCodePos (&Mark2);
1895             g_push (ltype, 0);
1896         }
1897
1898         /* Get the right hand side */
1899         MarkedExprWithCheck (hienext, &Expr2);
1900
1901         /* Check for a constant expression */
1902         rconst = (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2));
1903         if (!rconst) {
1904             /* Not constant, load into the primary */
1905             LoadExpr (CF_NONE, &Expr2);
1906         }
1907
1908         /* Check the type of the rhs */
1909         if (!IsClassInt (Expr2.Type)) {
1910             Error ("Integer expression expected");
1911         }
1912
1913         /* Check for const operands */
1914         if (lconst && rconst) {
1915
1916             /* Both operands are constant, remove the generated code */
1917             RemoveCode (&Mark1);
1918
1919             /* Get the type of the result */
1920             Expr->Type = promoteint (Expr->Type, Expr2.Type);
1921
1922             /* Handle the op differently for signed and unsigned types */
1923             if (IsSignSigned (Expr->Type)) {
1924
1925                 /* Evaluate the result for signed operands */
1926                 signed long Val1 = Expr->IVal;
1927                 signed long Val2 = Expr2.IVal;
1928                 switch (Tok) {
1929                     case TOK_OR:
1930                         Expr->IVal = (Val1 | Val2);
1931                         break;
1932                     case TOK_XOR:
1933                         Expr->IVal = (Val1 ^ Val2);
1934                         break;
1935                     case TOK_AND:
1936                         Expr->IVal = (Val1 & Val2);
1937                         break;
1938                     case TOK_STAR:
1939                         Expr->IVal = (Val1 * Val2);
1940                         break;
1941                     case TOK_DIV:
1942                         if (Val2 == 0) {
1943                             Error ("Division by zero");
1944                             Expr->IVal = 0x7FFFFFFF;
1945                         } else {
1946                             Expr->IVal = (Val1 / Val2);
1947                         }
1948                         break;
1949                     case TOK_MOD:
1950                         if (Val2 == 0) {
1951                             Error ("Modulo operation with zero");
1952                             Expr->IVal = 0;
1953                         } else {
1954                             Expr->IVal = (Val1 % Val2);
1955                         }
1956                         break;
1957                     default:
1958                         Internal ("hie_internal: got token 0x%X\n", Tok);
1959                 }
1960             } else {
1961
1962                 /* Evaluate the result for unsigned operands */
1963                 unsigned long Val1 = Expr->IVal;
1964                 unsigned long Val2 = Expr2.IVal;
1965                 switch (Tok) {
1966                     case TOK_OR:
1967                         Expr->IVal = (Val1 | Val2);
1968                         break;
1969                     case TOK_XOR:
1970                         Expr->IVal = (Val1 ^ Val2);
1971                         break;
1972                     case TOK_AND:
1973                         Expr->IVal = (Val1 & Val2);
1974                         break;
1975                     case TOK_STAR:
1976                         Expr->IVal = (Val1 * Val2);
1977                         break;
1978                     case TOK_DIV:
1979                         if (Val2 == 0) {
1980                             Error ("Division by zero");
1981                             Expr->IVal = 0xFFFFFFFF;
1982                         } else {
1983                             Expr->IVal = (Val1 / Val2);
1984                         }
1985                         break;
1986                     case TOK_MOD:
1987                         if (Val2 == 0) {
1988                             Error ("Modulo operation with zero");
1989                             Expr->IVal = 0;
1990                         } else {
1991                             Expr->IVal = (Val1 % Val2);
1992                         }
1993                         break;
1994                     default:
1995                         Internal ("hie_internal: got token 0x%X\n", Tok);
1996                 }
1997             }
1998
1999         } else if (lconst && (Gen->Flags & GEN_COMM) && !rconst) {
2000
2001             /* The left side is constant, the right side is not, and the
2002             ** operator allows swapping the operands. We haven't pushed the
2003             ** left side onto the stack in this case, and will reverse the
2004             ** operation because this allows for better code.
2005             */
2006             unsigned rtype = ltype | CF_CONST;
2007             ltype = TypeOf (Expr2.Type);       /* Expr2 is now left */
2008             type = CF_CONST;
2009             if ((Gen->Flags & GEN_NOPUSH) == 0) {
2010                 g_push (ltype, 0);
2011             } else {
2012                 ltype |= CF_REG;        /* Value is in register */
2013             }
2014
2015             /* Determine the type of the operation result. */
2016             type |= g_typeadjust (ltype, rtype);
2017             Expr->Type = promoteint (Expr->Type, Expr2.Type);
2018
2019             /* Generate code */
2020             Gen->Func (type, Expr->IVal);
2021
2022             /* We have a rvalue in the primary now */
2023             ED_MakeRValExpr (Expr);
2024
2025         } else {
2026
2027             /* If the right hand side is constant, and the generator function
2028             ** expects the lhs in the primary, remove the push of the primary
2029             ** now.
2030             */
2031             unsigned rtype = TypeOf (Expr2.Type);
2032             type = 0;
2033             if (rconst) {
2034                 /* Second value is constant - check for div */
2035                 type |= CF_CONST;
2036                 rtype |= CF_CONST;
2037                 if (Tok == TOK_DIV && Expr2.IVal == 0) {
2038                     Error ("Division by zero");
2039                 } else if (Tok == TOK_MOD && Expr2.IVal == 0) {
2040                     Error ("Modulo operation with zero");
2041                 }
2042                 if ((Gen->Flags & GEN_NOPUSH) != 0) {
2043                     RemoveCode (&Mark2);
2044                     ltype |= CF_REG;    /* Value is in register */
2045                 }
2046             }
2047
2048             /* Determine the type of the operation result. */
2049             type |= g_typeadjust (ltype, rtype);
2050             Expr->Type = promoteint (Expr->Type, Expr2.Type);
2051
2052             /* Generate code */
2053             Gen->Func (type, Expr2.IVal);
2054
2055             /* We have a rvalue in the primary now */
2056             ED_MakeRValExpr (Expr);
2057         }
2058     }
2059 }
2060
2061
2062
2063 static void hie_compare (const GenDesc* Ops,    /* List of generators */
2064                          ExprDesc* Expr,
2065                          void (*hienext) (ExprDesc*))
2066 /* Helper function for the compare operators */
2067 {
2068     ExprDesc Expr2;
2069     CodeMark Mark0;
2070     CodeMark Mark1;
2071     CodeMark Mark2;
2072     const GenDesc* Gen;
2073     token_t Tok;                        /* The operator token */
2074     unsigned ltype;
2075     int rconst;                         /* Operand is a constant */
2076
2077
2078     GetCodePos (&Mark0);
2079     ExprWithCheck (hienext, Expr);
2080
2081     while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
2082
2083         /* Remember the generator function */
2084         void (*GenFunc) (unsigned, unsigned long) = Gen->Func;
2085
2086         /* Remember the operator token, then skip it */
2087         Tok = CurTok.Tok;
2088         NextToken ();
2089
2090         /* If lhs is a function, convert it to pointer to function */
2091         if (IsTypeFunc (Expr->Type)) {
2092             Expr->Type = PointerTo (Expr->Type);
2093         }
2094
2095         /* Get the lhs on stack */
2096         GetCodePos (&Mark1);
2097         ltype = TypeOf (Expr->Type);
2098         if (ED_IsConstAbs (Expr)) {
2099             /* Constant value */
2100             GetCodePos (&Mark2);
2101             g_push (ltype | CF_CONST, Expr->IVal);
2102         } else {
2103             /* Value not constant */
2104             LoadExpr (CF_NONE, Expr);
2105             GetCodePos (&Mark2);
2106             g_push (ltype, 0);
2107         }
2108
2109         /* Get the right hand side */
2110         MarkedExprWithCheck (hienext, &Expr2);
2111
2112         /* If rhs is a function, convert it to pointer to function */
2113         if (IsTypeFunc (Expr2.Type)) {
2114             Expr2.Type = PointerTo (Expr2.Type);
2115         }
2116
2117         /* Check for a constant expression */
2118         rconst = (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2));
2119         if (!rconst) {
2120             /* Not constant, load into the primary */
2121             LoadExpr (CF_NONE, &Expr2);
2122         }
2123
2124         /* Some operations aren't allowed on function pointers */
2125         if ((Gen->Flags & GEN_NOFUNC) != 0) {
2126             /* Output only one message even if both sides are wrong */
2127             if (IsTypeFuncPtr (Expr->Type)) {
2128                 Error ("Invalid left operand for relational operator");
2129                 /* Avoid further errors */
2130                 ED_MakeConstAbsInt (Expr, 0);
2131                 ED_MakeConstAbsInt (&Expr2, 0);
2132             } else if (IsTypeFuncPtr (Expr2.Type)) {
2133                 Error ("Invalid right operand for relational operator");
2134                 /* Avoid further errors */
2135                 ED_MakeConstAbsInt (Expr, 0);
2136                 ED_MakeConstAbsInt (&Expr2, 0);
2137             }
2138         }
2139
2140         /* Make sure, the types are compatible */
2141         if (IsClassInt (Expr->Type)) {
2142             if (!IsClassInt (Expr2.Type) && !(IsClassPtr(Expr2.Type) && ED_IsNullPtr(Expr))) {
2143                 Error ("Incompatible types");
2144             }
2145         } else if (IsClassPtr (Expr->Type)) {
2146             if (IsClassPtr (Expr2.Type)) {
2147                 /* Both pointers are allowed in comparison if they point to
2148                 ** the same type, or if one of them is a void pointer.
2149                 */
2150                 Type* left  = Indirect (Expr->Type);
2151                 Type* right = Indirect (Expr2.Type);
2152                 if (TypeCmp (left, right) < TC_QUAL_DIFF && left->C != T_VOID && right->C != T_VOID) {
2153                     /* Incompatible pointers */
2154                     Error ("Incompatible types");
2155                 }
2156             } else if (!ED_IsNullPtr (&Expr2)) {
2157                 Error ("Incompatible types");
2158             }
2159         }
2160
2161         /* Check for const operands */
2162         if (ED_IsConstAbs (Expr) && rconst) {
2163
2164             /* If the result is constant, this is suspicious when not in
2165             ** preprocessor mode.
2166             */
2167             WarnConstCompareResult ();
2168
2169             /* Both operands are constant, remove the generated code */
2170             RemoveCode (&Mark1);
2171
2172             /* Determine if this is a signed or unsigned compare */
2173             if (IsClassInt (Expr->Type) && IsSignSigned (Expr->Type) &&
2174                 IsClassInt (Expr2.Type) && IsSignSigned (Expr2.Type)) {
2175
2176                 /* Evaluate the result for signed operands */
2177                 signed long Val1 = Expr->IVal;
2178                 signed long Val2 = Expr2.IVal;
2179                 switch (Tok) {
2180                     case TOK_EQ: Expr->IVal = (Val1 == Val2);   break;
2181                     case TOK_NE: Expr->IVal = (Val1 != Val2);   break;
2182                     case TOK_LT: Expr->IVal = (Val1 < Val2);    break;
2183                     case TOK_LE: Expr->IVal = (Val1 <= Val2);   break;
2184                     case TOK_GE: Expr->IVal = (Val1 >= Val2);   break;
2185                     case TOK_GT: Expr->IVal = (Val1 > Val2);    break;
2186                     default:     Internal ("hie_compare: got token 0x%X\n", Tok);
2187                 }
2188
2189             } else {
2190
2191                 /* Evaluate the result for unsigned operands */
2192                 unsigned long Val1 = Expr->IVal;
2193                 unsigned long Val2 = Expr2.IVal;
2194                 switch (Tok) {
2195                     case TOK_EQ: Expr->IVal = (Val1 == Val2);   break;
2196                     case TOK_NE: Expr->IVal = (Val1 != Val2);   break;
2197                     case TOK_LT: Expr->IVal = (Val1 < Val2);    break;
2198                     case TOK_LE: Expr->IVal = (Val1 <= Val2);   break;
2199                     case TOK_GE: Expr->IVal = (Val1 >= Val2);   break;
2200                     case TOK_GT: Expr->IVal = (Val1 > Val2);    break;
2201                     default:     Internal ("hie_compare: got token 0x%X\n", Tok);
2202                 }
2203             }
2204
2205         } else {
2206
2207             /* Determine the signedness of the operands */
2208             int LeftSigned  = IsSignSigned (Expr->Type);
2209             int RightSigned = IsSignSigned (Expr2.Type);
2210
2211             /* If the right hand side is constant, and the generator function
2212             ** expects the lhs in the primary, remove the push of the primary
2213             ** now.
2214             */
2215             unsigned flags = 0;
2216             if (rconst) {
2217                 flags |= CF_CONST;
2218                 if ((Gen->Flags & GEN_NOPUSH) != 0) {
2219                     RemoveCode (&Mark2);
2220                     ltype |= CF_REG;    /* Value is in register */
2221                 }
2222             }
2223
2224             /* Determine the type of the operation. */
2225             if (IsTypeChar (Expr->Type) && rconst) {
2226
2227                 /* Left side is unsigned char, right side is constant.
2228                 ** Determine the minimum and maximum values
2229                 */
2230                 int LeftMin, LeftMax;
2231                 if (LeftSigned) {
2232                     LeftMin = -128;
2233                     LeftMax = 127;
2234                 } else {
2235                     LeftMin = 0;
2236                     LeftMax = 255;
2237                 }
2238                 /* An integer value is always represented as a signed in the
2239                 ** ExprDesc structure. This may lead to false results below,
2240                 ** if it is actually unsigned, but interpreted as signed
2241                 ** because of the representation. Fortunately, in this case,
2242                 ** the actual value doesn't matter, since it's always greater
2243                 ** than what can be represented in a char. So correct the
2244                 ** value accordingly.
2245                 */
2246                 if (!RightSigned && Expr2.IVal < 0) {
2247                     /* Correct the value so it is an unsigned. It will then
2248                     ** anyway match one of the cases below.
2249                     */
2250                     Expr2.IVal = LeftMax + 1;
2251                 }
2252
2253                 /* Comparing a char against a constant may have a constant
2254                 ** result. Please note: It is not possible to remove the code
2255                 ** for the compare alltogether, because it may have side
2256                 ** effects.
2257                 */
2258                 switch (Tok) {
2259
2260                     case TOK_EQ:
2261                         if (Expr2.IVal < LeftMin || Expr2.IVal > LeftMax) {
2262                             ED_MakeConstAbsInt (Expr, 0);
2263                             WarnConstCompareResult ();
2264                             goto Done;
2265                         }
2266                         break;
2267
2268                     case TOK_NE:
2269                         if (Expr2.IVal < LeftMin || Expr2.IVal > LeftMax) {
2270                             ED_MakeConstAbsInt (Expr, 1);
2271                             WarnConstCompareResult ();
2272                             goto Done;
2273                         }
2274                         break;
2275
2276                     case TOK_LT:
2277                         if (Expr2.IVal <= LeftMin || Expr2.IVal > LeftMax) {
2278                             ED_MakeConstAbsInt (Expr, Expr2.IVal > LeftMax);
2279                             WarnConstCompareResult ();
2280                             goto Done;
2281                         }
2282                         break;
2283
2284                     case TOK_LE:
2285                         if (Expr2.IVal < LeftMin || Expr2.IVal >= LeftMax) {
2286                             ED_MakeConstAbsInt (Expr, Expr2.IVal >= LeftMax);
2287                             WarnConstCompareResult ();
2288                             goto Done;
2289                         }
2290                         break;
2291
2292                     case TOK_GE:
2293                         if (Expr2.IVal <= LeftMin || Expr2.IVal > LeftMax) {
2294                             ED_MakeConstAbsInt (Expr, Expr2.IVal <= LeftMin);
2295                             WarnConstCompareResult ();
2296                             goto Done;
2297                         }
2298                         break;
2299
2300                     case TOK_GT:
2301                         if (Expr2.IVal < LeftMin || Expr2.IVal >= LeftMax) {
2302                             ED_MakeConstAbsInt (Expr, Expr2.IVal < LeftMin);
2303                             WarnConstCompareResult ();
2304                             goto Done;
2305                         }
2306                         break;
2307
2308                     default:
2309                         Internal ("hie_compare: got token 0x%X\n", Tok);
2310                 }
2311
2312                 /* If the result is not already constant (as evaluated in the
2313                 ** switch above), we can execute the operation as a char op,
2314                 ** since the right side constant is in a valid range.
2315                 */
2316                 flags |= (CF_CHAR | CF_FORCECHAR);
2317                 if (!LeftSigned) {
2318                     flags |= CF_UNSIGNED;
2319                 }
2320
2321             } else if (IsTypeChar (Expr->Type) && IsTypeChar (Expr2.Type) &&
2322                 GetSignedness (Expr->Type) == GetSignedness (Expr2.Type)) {
2323
2324                 /* Both are chars with the same signedness. We can encode the
2325                 ** operation as a char operation.
2326                 */
2327                 flags |= CF_CHAR;
2328                 if (rconst) {
2329                     flags |= CF_FORCECHAR;
2330                 }
2331                 if (!LeftSigned) {
2332                     flags |= CF_UNSIGNED;
2333                 }
2334             } else {
2335                 unsigned rtype = TypeOf (Expr2.Type) | (flags & CF_CONST);
2336                 flags |= g_typeadjust (ltype, rtype);
2337             }
2338
2339             /* If the left side is an unsigned and the right is a constant,
2340             ** we may be able to change the compares to something more
2341             ** effective.
2342             */
2343             if (!LeftSigned && rconst) {
2344
2345                 switch (Tok) {
2346
2347                     case TOK_LT:
2348                         if (Expr2.IVal == 1) {
2349                             /* An unsigned compare to one means that the value
2350                             ** must be zero.
2351                             */
2352                             GenFunc = g_eq;
2353                             Expr2.IVal = 0;
2354                         }
2355                         break;
2356
2357                     case TOK_LE:
2358                         if (Expr2.IVal == 0) {
2359                             /* An unsigned compare to zero means that the value
2360                             ** must be zero.
2361                             */
2362                             GenFunc = g_eq;
2363                         }
2364                         break;
2365
2366                     case TOK_GE:
2367                         if (Expr2.IVal == 1) {
2368                             /* An unsigned compare to one means that the value
2369                             ** must not be zero.
2370                             */
2371                             GenFunc = g_ne;
2372                             Expr2.IVal = 0;
2373                         }
2374                         break;
2375
2376                     case TOK_GT:
2377                         if (Expr2.IVal == 0) {
2378                             /* An unsigned compare to zero means that the value
2379                             ** must not be zero.
2380                             */
2381                             GenFunc = g_ne;
2382                         }
2383                         break;
2384
2385                     default:
2386                         break;
2387
2388                 }
2389
2390             }
2391
2392             /* Generate code */
2393             GenFunc (flags, Expr2.IVal);
2394
2395             /* The result is an rvalue in the primary */
2396             ED_MakeRValExpr (Expr);
2397         }
2398
2399         /* Result type is always int */
2400         Expr->Type = type_int;
2401
2402 Done:   /* Condition codes are set */
2403         ED_TestDone (Expr);
2404     }
2405 }
2406
2407
2408
2409 static void hie9 (ExprDesc *Expr)
2410 /* Process * and / operators. */
2411 {
2412     static const GenDesc hie9_ops[] = {
2413         { TOK_STAR,     GEN_NOPUSH | GEN_COMM,  g_mul   },
2414         { TOK_DIV,      GEN_NOPUSH,             g_div   },
2415         { TOK_MOD,      GEN_NOPUSH,             g_mod   },
2416         { TOK_INVALID,  0,                      0       }
2417     };
2418     int UsedGen;
2419
2420     hie_internal (hie9_ops, Expr, hie10, &UsedGen);
2421 }
2422
2423
2424
2425 static void parseadd (ExprDesc* Expr)
2426 /* Parse an expression with the binary plus operator. Expr contains the
2427 ** unprocessed left hand side of the expression and will contain the
2428 ** result of the expression on return.
2429 */
2430 {
2431     ExprDesc Expr2;
2432     unsigned flags;             /* Operation flags */
2433     CodeMark Mark;              /* Remember code position */
2434     Type* lhst;                 /* Type of left hand side */
2435     Type* rhst;                 /* Type of right hand side */
2436
2437     /* Skip the PLUS token */
2438     NextToken ();
2439
2440     /* Get the left hand side type, initialize operation flags */
2441     lhst = Expr->Type;
2442     flags = 0;
2443
2444     /* Check for constness on both sides */
2445     if (ED_IsConst (Expr)) {
2446
2447         /* The left hand side is a constant of some sort. Good. Get rhs */
2448         ExprWithCheck (hie9, &Expr2);
2449         if (ED_IsConstAbs (&Expr2)) {
2450
2451             /* Right hand side is a constant numeric value. Get the rhs type */
2452             rhst = Expr2.Type;
2453
2454             /* Both expressions are constants. Check for pointer arithmetic */
2455             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2456                 /* Left is pointer, right is int, must scale rhs */
2457                 Expr->IVal += Expr2.IVal * CheckedPSizeOf (lhst);
2458                 /* Result type is a pointer */
2459             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2460                 /* Left is int, right is pointer, must scale lhs */
2461                 Expr->IVal = Expr->IVal * CheckedPSizeOf (rhst) + Expr2.IVal;
2462                 /* Result type is a pointer */
2463                 Expr->Type = Expr2.Type;
2464             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2465                 /* Integer addition */
2466                 Expr->IVal += Expr2.IVal;
2467                 typeadjust (Expr, &Expr2, 1);
2468             } else {
2469                 /* OOPS */
2470                 Error ("Invalid operands for binary operator `+'");
2471             }
2472
2473         } else {
2474
2475             /* lhs is a constant and rhs is not constant. Load rhs into
2476             ** the primary.
2477             */
2478             LoadExpr (CF_NONE, &Expr2);
2479
2480             /* Beware: The check above (for lhs) lets not only pass numeric
2481             ** constants, but also constant addresses (labels), maybe even
2482             ** with an offset. We have to check for that here.
2483             */
2484
2485             /* First, get the rhs type. */
2486             rhst = Expr2.Type;
2487
2488             /* Setup flags */
2489             if (ED_IsLocAbs (Expr)) {
2490                 /* A numerical constant */
2491                 flags |= CF_CONST;
2492             } else {
2493                 /* Constant address label */
2494                 flags |= GlobalModeFlags (Expr) | CF_CONSTADDR;
2495             }
2496
2497             /* Check for pointer arithmetic */
2498             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2499                 /* Left is pointer, right is int, must scale rhs */
2500                 g_scale (CF_INT, CheckedPSizeOf (lhst));
2501                 /* Operate on pointers, result type is a pointer */
2502                 flags |= CF_PTR;
2503                 /* Generate the code for the add */
2504                 if (ED_GetLoc (Expr) == E_LOC_ABS) {
2505                     /* Numeric constant */
2506                     g_inc (flags, Expr->IVal);
2507                 } else {
2508                     /* Constant address */
2509                     g_addaddr_static (flags, Expr->Name, Expr->IVal);
2510                 }
2511             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2512
2513                 /* Left is int, right is pointer, must scale lhs. */
2514                 unsigned ScaleFactor = CheckedPSizeOf (rhst);
2515
2516                 /* Operate on pointers, result type is a pointer */
2517                 flags |= CF_PTR;
2518                 Expr->Type = Expr2.Type;
2519
2520                 /* Since we do already have rhs in the primary, if lhs is
2521                 ** not a numeric constant, and the scale factor is not one
2522                 ** (no scaling), we must take the long way over the stack.
2523                 */
2524                 if (ED_IsLocAbs (Expr)) {
2525                     /* Numeric constant, scale lhs */
2526                     Expr->IVal *= ScaleFactor;
2527                     /* Generate the code for the add */
2528                     g_inc (flags, Expr->IVal);
2529                 } else if (ScaleFactor == 1) {
2530                     /* Constant address but no need to scale */
2531                     g_addaddr_static (flags, Expr->Name, Expr->IVal);
2532                 } else {
2533                     /* Constant address that must be scaled */
2534                     g_push (TypeOf (Expr2.Type), 0);    /* rhs --> stack */
2535                     g_getimmed (flags, Expr->Name, Expr->IVal);
2536                     g_scale (CF_PTR, ScaleFactor);
2537                     g_add (CF_PTR, 0);
2538                 }
2539             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2540                 /* Integer addition */
2541                 flags |= typeadjust (Expr, &Expr2, 1);
2542                 /* Generate the code for the add */
2543                 if (ED_IsLocAbs (Expr)) {
2544                     /* Numeric constant */
2545                     g_inc (flags, Expr->IVal);
2546                 } else {
2547                     /* Constant address */
2548                     g_addaddr_static (flags, Expr->Name, Expr->IVal);
2549                 }
2550             } else {
2551                 /* OOPS */
2552                 Error ("Invalid operands for binary operator `+'");
2553                 flags = CF_INT;
2554             }
2555
2556             /* Result is a rvalue in primary register */
2557             ED_MakeRValExpr (Expr);
2558         }
2559
2560     } else {
2561
2562         /* Left hand side is not constant. Get the value onto the stack. */
2563         LoadExpr (CF_NONE, Expr);              /* --> primary register */
2564         GetCodePos (&Mark);
2565         g_push (TypeOf (Expr->Type), 0);        /* --> stack */
2566
2567         /* Evaluate the rhs */
2568         MarkedExprWithCheck (hie9, &Expr2);
2569
2570         /* Check for a constant rhs expression */
2571         if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) {
2572
2573             /* Right hand side is a constant. Get the rhs type */
2574             rhst = Expr2.Type;
2575
2576             /* Remove pushed value from stack */
2577             RemoveCode (&Mark);
2578
2579             /* Check for pointer arithmetic */
2580             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2581                 /* Left is pointer, right is int, must scale rhs */
2582                 Expr2.IVal *= CheckedPSizeOf (lhst);
2583                 /* Operate on pointers, result type is a pointer */
2584                 flags = CF_PTR;
2585             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2586                 /* Left is int, right is pointer, must scale lhs (ptr only) */
2587                 g_scale (CF_INT | CF_CONST, CheckedPSizeOf (rhst));
2588                 /* Operate on pointers, result type is a pointer */
2589                 flags = CF_PTR;
2590                 Expr->Type = Expr2.Type;
2591             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2592                 /* Integer addition */
2593                 flags = typeadjust (Expr, &Expr2, 1);
2594             } else {
2595                 /* OOPS */
2596                 Error ("Invalid operands for binary operator `+'");
2597                 flags = CF_INT;
2598             }
2599
2600             /* Generate code for the add */
2601             g_inc (flags | CF_CONST, Expr2.IVal);
2602
2603         } else {
2604
2605             /* Not constant, load into the primary */
2606             LoadExpr (CF_NONE, &Expr2);
2607
2608             /* lhs and rhs are not constant. Get the rhs type. */
2609             rhst = Expr2.Type;
2610
2611             /* Check for pointer arithmetic */
2612             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2613                 /* Left is pointer, right is int, must scale rhs */
2614                 g_scale (CF_INT, CheckedPSizeOf (lhst));
2615                 /* Operate on pointers, result type is a pointer */
2616                 flags = CF_PTR;
2617             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2618                 /* Left is int, right is pointer, must scale lhs */
2619                 g_tosint (TypeOf (lhst));       /* Make sure TOS is int */
2620                 g_swap (CF_INT);                /* Swap TOS and primary */
2621                 g_scale (CF_INT, 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. Note: Result is never constant.
2627                 ** Problem here is that typeadjust does not know if the
2628                 ** variable is an rvalue or lvalue, so if both operands
2629                 ** are dereferenced constant numeric addresses, typeadjust
2630                 ** thinks the operation works on constants. Removing
2631                 ** CF_CONST here means handling the symptoms, however, the
2632                 ** whole parser is such a mess that I fear to break anything
2633                 ** when trying to apply another solution.
2634                 */
2635                 flags = typeadjust (Expr, &Expr2, 0) & ~CF_CONST;
2636             } else {
2637                 /* OOPS */
2638                 Error ("Invalid operands for binary operator `+'");
2639                 flags = CF_INT;
2640             }
2641
2642             /* Generate code for the add */
2643             g_add (flags, 0);
2644
2645         }
2646
2647         /* Result is a rvalue in primary register */
2648         ED_MakeRValExpr (Expr);
2649     }
2650
2651     /* Condition codes not set */
2652     ED_MarkAsUntested (Expr);
2653 }
2654
2655
2656
2657 static void parsesub (ExprDesc* Expr)
2658 /* Parse an expression with the binary minus operator. Expr contains the
2659 ** unprocessed left hand side of the expression and will contain the
2660 ** result of the expression on return.
2661 */
2662 {
2663     ExprDesc Expr2;
2664     unsigned flags;             /* Operation flags */
2665     Type* lhst;                 /* Type of left hand side */
2666     Type* rhst;                 /* Type of right hand side */
2667     CodeMark Mark1;             /* Save position of output queue */
2668     CodeMark Mark2;             /* Another position in the queue */
2669     int rscale;                 /* Scale factor for the result */
2670
2671
2672     /* lhs cannot be function or pointer to function */
2673     if (IsTypeFunc (Expr->Type) || IsTypeFuncPtr (Expr->Type)) {
2674         Error ("Invalid left operand for binary operator `-'");
2675         /* Make it pointer to char to avoid further errors */
2676         Expr->Type = type_uchar;
2677     }
2678
2679     /* Skip the MINUS token */
2680     NextToken ();
2681
2682     /* Get the left hand side type, initialize operation flags */
2683     lhst = Expr->Type;
2684     rscale = 1;                 /* Scale by 1, that is, don't scale */
2685
2686     /* Remember the output queue position, then bring the value onto the stack */
2687     GetCodePos (&Mark1);
2688     LoadExpr (CF_NONE, Expr);  /* --> primary register */
2689     GetCodePos (&Mark2);
2690     g_push (TypeOf (lhst), 0);  /* --> stack */
2691
2692     /* Parse the right hand side */
2693     MarkedExprWithCheck (hie9, &Expr2);
2694
2695     /* rhs cannot be function or pointer to function */
2696     if (IsTypeFunc (Expr2.Type) || IsTypeFuncPtr (Expr2.Type)) {
2697         Error ("Invalid right operand for binary operator `-'");
2698         /* Make it pointer to char to avoid further errors */
2699         Expr2.Type = type_uchar;
2700     }
2701
2702     /* Check for a constant rhs expression */
2703     if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) {
2704
2705         /* The right hand side is constant. Get the rhs type. */
2706         rhst = Expr2.Type;
2707
2708         /* Check left hand side */
2709         if (ED_IsConstAbs (Expr)) {
2710
2711             /* Both sides are constant, remove generated code */
2712             RemoveCode (&Mark1);
2713
2714             /* Check for pointer arithmetic */
2715             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2716                 /* Left is pointer, right is int, must scale rhs */
2717                 Expr->IVal -= Expr2.IVal * CheckedPSizeOf (lhst);
2718                 /* Operate on pointers, result type is a pointer */
2719             } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2720                 /* Left is pointer, right is pointer, must scale result */
2721                 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2722                     Error ("Incompatible pointer types");
2723                 } else {
2724                     Expr->IVal = (Expr->IVal - Expr2.IVal) /
2725                                       CheckedPSizeOf (lhst);
2726                 }
2727                 /* Operate on pointers, result type is an integer */
2728                 Expr->Type = type_int;
2729             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2730                 /* Integer subtraction */
2731                 typeadjust (Expr, &Expr2, 1);
2732                 Expr->IVal -= Expr2.IVal;
2733             } else {
2734                 /* OOPS */
2735                 Error ("Invalid operands for binary operator `-'");
2736             }
2737
2738             /* Result is constant, condition codes not set */
2739             ED_MarkAsUntested (Expr);
2740
2741         } else {
2742
2743             /* Left hand side is not constant, right hand side is.
2744             ** Remove pushed value from stack.
2745             */
2746             RemoveCode (&Mark2);
2747
2748             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2749                 /* Left is pointer, right is int, must scale rhs */
2750                 Expr2.IVal *= CheckedPSizeOf (lhst);
2751                 /* Operate on pointers, result type is a pointer */
2752                 flags = CF_PTR;
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                     rscale = CheckedPSizeOf (lhst);
2759                 }
2760                 /* Operate on pointers, result type is an integer */
2761                 flags = CF_PTR;
2762                 Expr->Type = type_int;
2763             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2764                 /* Integer subtraction */
2765                 flags = typeadjust (Expr, &Expr2, 1);
2766             } else {
2767                 /* OOPS */
2768                 Error ("Invalid operands for binary operator `-'");
2769                 flags = CF_INT;
2770             }
2771
2772             /* Do the subtraction */
2773             g_dec (flags | CF_CONST, Expr2.IVal);
2774
2775             /* If this was a pointer subtraction, we must scale the result */
2776             if (rscale != 1) {
2777                 g_scale (flags, -rscale);
2778             }
2779
2780             /* Result is a rvalue in the primary register */
2781             ED_MakeRValExpr (Expr);
2782             ED_MarkAsUntested (Expr);
2783
2784         }
2785
2786     } else {
2787
2788         /* Not constant, load into the primary */
2789         LoadExpr (CF_NONE, &Expr2);
2790
2791         /* Right hand side is not constant. Get the rhs type. */
2792         rhst = Expr2.Type;
2793
2794         /* Check for pointer arithmetic */
2795         if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2796             /* Left is pointer, right is int, must scale rhs */
2797             g_scale (CF_INT, CheckedPSizeOf (lhst));
2798             /* Operate on pointers, result type is a pointer */
2799             flags = CF_PTR;
2800         } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2801             /* Left is pointer, right is pointer, must scale result */
2802             if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2803                 Error ("Incompatible pointer types");
2804             } else {
2805                 rscale = CheckedPSizeOf (lhst);
2806             }
2807             /* Operate on pointers, result type is an integer */
2808             flags = CF_PTR;
2809             Expr->Type = type_int;
2810         } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2811             /* Integer subtraction. If the left hand side descriptor says that
2812             ** the lhs is const, we have to remove this mark, since this is no
2813             ** longer true, lhs is on stack instead.
2814             */
2815             if (ED_IsLocAbs (Expr)) {
2816                 ED_MakeRValExpr (Expr);
2817             }
2818             /* Adjust operand types */
2819             flags = typeadjust (Expr, &Expr2, 0);
2820         } else {
2821             /* OOPS */
2822             Error ("Invalid operands for binary operator `-'");
2823             flags = CF_INT;
2824         }
2825
2826         /* Generate code for the sub (the & is a hack here) */
2827         g_sub (flags & ~CF_CONST, 0);
2828
2829         /* If this was a pointer subtraction, we must scale the result */
2830         if (rscale != 1) {
2831             g_scale (flags, -rscale);
2832         }
2833
2834         /* Result is a rvalue in the primary register */
2835         ED_MakeRValExpr (Expr);
2836         ED_MarkAsUntested (Expr);
2837     }
2838 }
2839
2840
2841
2842 void hie8 (ExprDesc* Expr)
2843 /* Process + and - binary operators. */
2844 {
2845     ExprWithCheck (hie9, Expr);
2846     while (CurTok.Tok == TOK_PLUS || CurTok.Tok == TOK_MINUS) {
2847         if (CurTok.Tok == TOK_PLUS) {
2848             parseadd (Expr);
2849         } else {
2850             parsesub (Expr);
2851         }
2852     }
2853 }
2854
2855
2856
2857 static void hie6 (ExprDesc* Expr)
2858 /* Handle greater-than type comparators */
2859 {
2860     static const GenDesc hie6_ops [] = {
2861         { TOK_LT,       GEN_NOPUSH | GEN_NOFUNC,     g_lt    },
2862         { TOK_LE,       GEN_NOPUSH | GEN_NOFUNC,     g_le    },
2863         { TOK_GE,       GEN_NOPUSH | GEN_NOFUNC,     g_ge    },
2864         { TOK_GT,       GEN_NOPUSH | GEN_NOFUNC,     g_gt    },
2865         { TOK_INVALID,  0,                           0       }
2866     };
2867     hie_compare (hie6_ops, Expr, ShiftExpr);
2868 }
2869
2870
2871
2872 static void hie5 (ExprDesc* Expr)
2873 /* Handle == and != */
2874 {
2875     static const GenDesc hie5_ops[] = {
2876         { TOK_EQ,       GEN_NOPUSH,     g_eq    },
2877         { TOK_NE,       GEN_NOPUSH,     g_ne    },
2878         { TOK_INVALID,  0,              0       }
2879     };
2880     hie_compare (hie5_ops, Expr, hie6);
2881 }
2882
2883
2884
2885 static void hie4 (ExprDesc* Expr)
2886 /* Handle & (bitwise and) */
2887 {
2888     static const GenDesc hie4_ops[] = {
2889         { TOK_AND,      GEN_NOPUSH | GEN_COMM,  g_and   },
2890         { TOK_INVALID,  0,                      0       }
2891     };
2892     int UsedGen;
2893
2894     hie_internal (hie4_ops, Expr, hie5, &UsedGen);
2895 }
2896
2897
2898
2899 static void hie3 (ExprDesc* Expr)
2900 /* Handle ^ (bitwise exclusive or) */
2901 {
2902     static const GenDesc hie3_ops[] = {
2903         { TOK_XOR,      GEN_NOPUSH | GEN_COMM,  g_xor   },
2904         { TOK_INVALID,  0,                      0       }
2905     };
2906     int UsedGen;
2907
2908     hie_internal (hie3_ops, Expr, hie4, &UsedGen);
2909 }
2910
2911
2912
2913 static void hie2 (ExprDesc* Expr)
2914 /* Handle | (bitwise or) */
2915 {
2916     static const GenDesc hie2_ops[] = {
2917         { TOK_OR,       GEN_NOPUSH | GEN_COMM,  g_or    },
2918         { TOK_INVALID,  0,                      0       }
2919     };
2920     int UsedGen;
2921
2922     hie_internal (hie2_ops, Expr, hie3, &UsedGen);
2923 }
2924
2925
2926
2927 static void hieAndPP (ExprDesc* Expr)
2928 /* Process "exp && exp" in preprocessor mode (that is, when the parser is
2929 ** called recursively from the preprocessor.
2930 */
2931 {
2932     ExprDesc Expr2;
2933
2934     ConstAbsIntExpr (hie2, Expr);
2935     while (CurTok.Tok == TOK_BOOL_AND) {
2936
2937         /* Skip the && */
2938         NextToken ();
2939
2940         /* Get rhs */
2941         ConstAbsIntExpr (hie2, &Expr2);
2942
2943         /* Combine the two */
2944         Expr->IVal = (Expr->IVal && Expr2.IVal);
2945     }
2946 }
2947
2948
2949
2950 static void hieOrPP (ExprDesc *Expr)
2951 /* Process "exp || exp" in preprocessor mode (that is, when the parser is
2952 ** called recursively from the preprocessor.
2953 */
2954 {
2955     ExprDesc Expr2;
2956
2957     ConstAbsIntExpr (hieAndPP, Expr);
2958     while (CurTok.Tok == TOK_BOOL_OR) {
2959
2960         /* Skip the && */
2961         NextToken ();
2962
2963         /* Get rhs */
2964         ConstAbsIntExpr (hieAndPP, &Expr2);
2965
2966         /* Combine the two */
2967         Expr->IVal = (Expr->IVal || Expr2.IVal);
2968     }
2969 }
2970
2971
2972
2973 static void hieAnd (ExprDesc* Expr, unsigned TrueLab, int* BoolOp)
2974 /* Process "exp && exp" */
2975 {
2976     int FalseLab;
2977     ExprDesc Expr2;
2978
2979     ExprWithCheck (hie2, Expr);
2980     if (CurTok.Tok == TOK_BOOL_AND) {
2981
2982         /* Tell our caller that we're evaluating a boolean */
2983         *BoolOp = 1;
2984
2985         /* Get a label that we will use for false expressions */
2986         FalseLab = GetLocalLabel ();
2987
2988         /* If the expr hasn't set condition codes, set the force-test flag */
2989         if (!ED_IsTested (Expr)) {
2990             ED_MarkForTest (Expr);
2991         }
2992
2993         /* Load the value */
2994         LoadExpr (CF_FORCECHAR, Expr);
2995
2996         /* Generate the jump */
2997         g_falsejump (CF_NONE, FalseLab);
2998
2999         /* Parse more boolean and's */
3000         while (CurTok.Tok == TOK_BOOL_AND) {
3001
3002             /* Skip the && */
3003             NextToken ();
3004
3005             /* Get rhs */
3006             hie2 (&Expr2);
3007             if (!ED_IsTested (&Expr2)) {
3008                 ED_MarkForTest (&Expr2);
3009             }
3010             LoadExpr (CF_FORCECHAR, &Expr2);
3011
3012             /* Do short circuit evaluation */
3013             if (CurTok.Tok == TOK_BOOL_AND) {
3014                 g_falsejump (CF_NONE, FalseLab);
3015             } else {
3016                 /* Last expression - will evaluate to true */
3017                 g_truejump (CF_NONE, TrueLab);
3018             }
3019         }
3020
3021         /* Define the false jump label here */
3022         g_defcodelabel (FalseLab);
3023
3024         /* The result is an rvalue in primary */
3025         ED_MakeRValExpr (Expr);
3026         ED_TestDone (Expr);     /* Condition codes are set */
3027     }
3028 }
3029
3030
3031
3032 static void hieOr (ExprDesc *Expr)
3033 /* Process "exp || exp". */
3034 {
3035     ExprDesc Expr2;
3036     int BoolOp = 0;             /* Did we have a boolean op? */
3037     int AndOp;                  /* Did we have a && operation? */
3038     unsigned TrueLab;           /* Jump to this label if true */
3039     unsigned DoneLab;
3040
3041     /* Get a label */
3042     TrueLab = GetLocalLabel ();
3043
3044     /* Call the next level parser */
3045     hieAnd (Expr, TrueLab, &BoolOp);
3046
3047     /* Any boolean or's? */
3048     if (CurTok.Tok == TOK_BOOL_OR) {
3049
3050         /* If the expr hasn't set condition codes, set the force-test flag */
3051         if (!ED_IsTested (Expr)) {
3052             ED_MarkForTest (Expr);
3053         }
3054
3055         /* Get first expr */
3056         LoadExpr (CF_FORCECHAR, Expr);
3057
3058         /* For each expression jump to TrueLab if true. Beware: If we
3059         ** had && operators, the jump is already in place!
3060         */
3061         if (!BoolOp) {
3062             g_truejump (CF_NONE, TrueLab);
3063         }
3064
3065         /* Remember that we had a boolean op */
3066         BoolOp = 1;
3067
3068         /* while there's more expr */
3069         while (CurTok.Tok == TOK_BOOL_OR) {
3070
3071             /* skip the || */
3072             NextToken ();
3073
3074             /* Get a subexpr */
3075             AndOp = 0;
3076             hieAnd (&Expr2, TrueLab, &AndOp);
3077             if (!ED_IsTested (&Expr2)) {
3078                 ED_MarkForTest (&Expr2);
3079             }
3080             LoadExpr (CF_FORCECHAR, &Expr2);
3081
3082             /* If there is more to come, add shortcut boolean eval. */
3083             g_truejump (CF_NONE, TrueLab);
3084
3085         }
3086
3087         /* The result is an rvalue in primary */
3088         ED_MakeRValExpr (Expr);
3089         ED_TestDone (Expr);                     /* Condition codes are set */
3090     }
3091
3092     /* If we really had boolean ops, generate the end sequence */
3093     if (BoolOp) {
3094         DoneLab = GetLocalLabel ();
3095         g_getimmed (CF_INT | CF_CONST, 0, 0);   /* Load FALSE */
3096         g_falsejump (CF_NONE, DoneLab);
3097         g_defcodelabel (TrueLab);
3098         g_getimmed (CF_INT | CF_CONST, 1, 0);   /* Load TRUE */
3099         g_defcodelabel (DoneLab);
3100     }
3101 }
3102
3103
3104
3105 static void hieQuest (ExprDesc* Expr)
3106 /* Parse the ternary operator */
3107 {
3108     int         FalseLab;
3109     int         TrueLab;
3110     CodeMark    TrueCodeEnd;
3111     ExprDesc    Expr2;          /* Expression 2 */
3112     ExprDesc    Expr3;          /* Expression 3 */
3113     int         Expr2IsNULL;    /* Expression 2 is a NULL pointer */
3114     int         Expr3IsNULL;    /* Expression 3 is a NULL pointer */
3115     Type*       ResultType;     /* Type of result */
3116
3117
3118     /* Call the lower level eval routine */
3119     if (Preprocessing) {
3120         ExprWithCheck (hieOrPP, Expr);
3121     } else {
3122         ExprWithCheck (hieOr, Expr);
3123     }
3124
3125     /* Check if it's a ternary expression */
3126     if (CurTok.Tok == TOK_QUEST) {
3127         NextToken ();
3128         if (!ED_IsTested (Expr)) {
3129             /* Condition codes not set, request a test */
3130             ED_MarkForTest (Expr);
3131         }
3132         LoadExpr (CF_NONE, Expr);
3133         FalseLab = GetLocalLabel ();
3134         g_falsejump (CF_NONE, FalseLab);
3135
3136         /* Parse second expression. Remember for later if it is a NULL pointer
3137         ** expression, then load it into the primary.
3138         */
3139         ExprWithCheck (hie1, &Expr2);
3140         Expr2IsNULL = ED_IsNullPtr (&Expr2);
3141         if (!IsTypeVoid (Expr2.Type)) {
3142             /* Load it into the primary */
3143             LoadExpr (CF_NONE, &Expr2);
3144             ED_MakeRValExpr (&Expr2);
3145             Expr2.Type = PtrConversion (Expr2.Type);
3146         }
3147
3148         /* Remember the current code position */
3149         GetCodePos (&TrueCodeEnd);
3150
3151         /* Jump around the evaluation of the third expression */
3152         TrueLab = GetLocalLabel ();
3153         ConsumeColon ();
3154         g_jump (TrueLab);
3155
3156         /* Jump here if the first expression was false */
3157         g_defcodelabel (FalseLab);
3158
3159         /* Parse third expression. Remember for later if it is a NULL pointer
3160         ** expression, then load it into the primary.
3161         */
3162         ExprWithCheck (hie1, &Expr3);
3163         Expr3IsNULL = ED_IsNullPtr (&Expr3);
3164         if (!IsTypeVoid (Expr3.Type)) {
3165             /* Load it into the primary */
3166             LoadExpr (CF_NONE, &Expr3);
3167             ED_MakeRValExpr (&Expr3);
3168             Expr3.Type = PtrConversion (Expr3.Type);
3169         }
3170
3171         /* Check if any conversions are needed, if so, do them.
3172         ** Conversion rules for ?: expression are:
3173         **   - if both expressions are int expressions, default promotion
3174         **     rules for ints apply.
3175         **   - if both expressions are pointers of the same type, the
3176         **     result of the expression is of this type.
3177         **   - if one of the expressions is a pointer and the other is
3178         **     a zero constant, the resulting type is that of the pointer
3179         **     type.
3180         **   - if both expressions are void expressions, the result is of
3181         **     type void.
3182         **   - all other cases are flagged by an error.
3183         */
3184         if (IsClassInt (Expr2.Type) && IsClassInt (Expr3.Type)) {
3185
3186             CodeMark    CvtCodeStart;
3187             CodeMark    CvtCodeEnd;
3188
3189
3190             /* Get common type */
3191             ResultType = promoteint (Expr2.Type, Expr3.Type);
3192
3193             /* Convert the third expression to this type if needed */
3194             TypeConversion (&Expr3, ResultType);
3195
3196             /* Emit conversion code for the second expression, but remember
3197             ** where it starts end ends.
3198             */
3199             GetCodePos (&CvtCodeStart);
3200             TypeConversion (&Expr2, ResultType);
3201             GetCodePos (&CvtCodeEnd);
3202
3203             /* If we had conversion code, move it to the right place */
3204             if (!CodeRangeIsEmpty (&CvtCodeStart, &CvtCodeEnd)) {
3205                 MoveCode (&CvtCodeStart, &CvtCodeEnd, &TrueCodeEnd);
3206             }
3207
3208         } else if (IsClassPtr (Expr2.Type) && IsClassPtr (Expr3.Type)) {
3209             /* Must point to same type */
3210             if (TypeCmp (Indirect (Expr2.Type), Indirect (Expr3.Type)) < TC_EQUAL) {
3211                 Error ("Incompatible pointer types");
3212             }
3213             /* Result has the common type */
3214             ResultType = Expr2.Type;
3215         } else if (IsClassPtr (Expr2.Type) && Expr3IsNULL) {
3216             /* Result type is pointer, no cast needed */
3217             ResultType = Expr2.Type;
3218         } else if (Expr2IsNULL && IsClassPtr (Expr3.Type)) {
3219             /* Result type is pointer, no cast needed */
3220             ResultType = Expr3.Type;
3221         } else if (IsTypeVoid (Expr2.Type) && IsTypeVoid (Expr3.Type)) {
3222             /* Result type is void */
3223             ResultType = Expr3.Type;
3224         } else {
3225             Error ("Incompatible types");
3226             ResultType = Expr2.Type;            /* Doesn't matter here */
3227         }
3228
3229         /* Define the final label */
3230         g_defcodelabel (TrueLab);
3231
3232         /* Setup the target expression */
3233         ED_MakeRValExpr (Expr);
3234         Expr->Type  = ResultType;
3235     }
3236 }
3237
3238
3239
3240 static void opeq (const GenDesc* Gen, ExprDesc* Expr, const char* Op)
3241 /* Process "op=" operators. */
3242 {
3243     ExprDesc Expr2;
3244     unsigned flags;
3245     CodeMark Mark;
3246     int MustScale;
3247
3248     /* op= can only be used with lvalues */
3249     if (!ED_IsLVal (Expr)) {
3250         Error ("Invalid lvalue in assignment");
3251         return;
3252     }
3253
3254     /* The left side must not be const qualified */
3255     if (IsQualConst (Expr->Type)) {
3256         Error ("Assignment to const");
3257     }
3258
3259     /* There must be an integer or pointer on the left side */
3260     if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
3261         Error ("Invalid left operand type");
3262         /* Continue. Wrong code will be generated, but the compiler won't
3263         ** break, so this is the best error recovery.
3264         */
3265     }
3266
3267     /* Skip the operator token */
3268     NextToken ();
3269
3270     /* Determine the type of the lhs */
3271     flags = TypeOf (Expr->Type);
3272     MustScale = (Gen->Func == g_add || Gen->Func == g_sub) && IsTypePtr (Expr->Type);
3273
3274     /* Get the lhs address on stack (if needed) */
3275     PushAddr (Expr);
3276
3277     /* Fetch the lhs into the primary register if needed */
3278     LoadExpr (CF_NONE, Expr);
3279
3280     /* Bring the lhs on stack */
3281     GetCodePos (&Mark);
3282     g_push (flags, 0);
3283
3284     /* Evaluate the rhs */
3285     MarkedExprWithCheck (hie1, &Expr2);
3286
3287     /* The rhs must be an integer (or a float, but we don't support that yet */
3288     if (!IsClassInt (Expr2.Type)) {
3289         Error ("Invalid right operand for binary operator `%s'", Op);
3290         /* Continue. Wrong code will be generated, but the compiler won't
3291         ** break, so this is the best error recovery.
3292         */
3293     }
3294
3295     /* Check for a constant expression */
3296     if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) {
3297         /* The resulting value is a constant. If the generator has the NOPUSH
3298         ** flag set, don't push the lhs.
3299         */
3300         if (Gen->Flags & GEN_NOPUSH) {
3301             RemoveCode (&Mark);
3302         }
3303         if (MustScale) {
3304             /* lhs is a pointer, scale rhs */
3305             Expr2.IVal *= CheckedSizeOf (Expr->Type+1);
3306         }
3307
3308         /* If the lhs is character sized, the operation may be later done
3309         ** with characters.
3310         */
3311         if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
3312             flags |= CF_FORCECHAR;
3313         }
3314
3315         /* Special handling for add and sub - some sort of a hack, but short code */
3316         if (Gen->Func == g_add) {
3317             g_inc (flags | CF_CONST, Expr2.IVal);
3318         } else if (Gen->Func == g_sub) {
3319             g_dec (flags | CF_CONST, Expr2.IVal);
3320         } else {
3321             if (Expr2.IVal == 0) {
3322                 /* Check for div by zero/mod by zero */
3323                 if (Gen->Func == g_div) {
3324                     Error ("Division by zero");
3325                 } else if (Gen->Func == g_mod) {
3326                     Error ("Modulo operation with zero");
3327                 }
3328             }
3329             Gen->Func (flags | CF_CONST, Expr2.IVal);
3330         }
3331     } else {
3332
3333         /* rhs is not constant. Load into the primary */
3334         LoadExpr (CF_NONE, &Expr2);
3335         if (MustScale) {
3336             /* lhs is a pointer, scale rhs */
3337             g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Expr->Type+1));
3338         }
3339
3340         /* If the lhs is character sized, the operation may be later done
3341         ** with characters.
3342         */
3343         if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
3344             flags |= CF_FORCECHAR;
3345         }
3346
3347         /* Adjust the types of the operands if needed */
3348         Gen->Func (g_typeadjust (flags, TypeOf (Expr2.Type)), 0);
3349     }
3350     Store (Expr, 0);
3351     ED_MakeRValExpr (Expr);
3352 }
3353
3354
3355
3356 static void addsubeq (const GenDesc* Gen, ExprDesc *Expr, const char* Op)
3357 /* Process the += and -= operators */
3358 {
3359     ExprDesc Expr2;
3360     unsigned lflags;
3361     unsigned rflags;
3362     int      MustScale;
3363
3364
3365     /* We're currently only able to handle some adressing modes */
3366     if (ED_GetLoc (Expr) == E_LOC_EXPR || ED_GetLoc (Expr) == E_LOC_PRIMARY) {
3367         /* Use generic routine */
3368         opeq (Gen, Expr, Op);
3369         return;
3370     }
3371
3372     /* We must have an lvalue */
3373     if (ED_IsRVal (Expr)) {
3374         Error ("Invalid lvalue in assignment");
3375         return;
3376     }
3377
3378     /* The left side must not be const qualified */
3379     if (IsQualConst (Expr->Type)) {
3380         Error ("Assignment to const");
3381     }
3382
3383     /* There must be an integer or pointer on the left side */
3384     if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
3385         Error ("Invalid left operand type");
3386         /* Continue. Wrong code will be generated, but the compiler won't
3387         ** break, so this is the best error recovery.
3388         */
3389     }
3390
3391     /* Skip the operator */
3392     NextToken ();
3393
3394     /* Check if we have a pointer expression and must scale rhs */
3395     MustScale = IsTypePtr (Expr->Type);
3396
3397     /* Initialize the code generator flags */
3398     lflags = 0;
3399     rflags = 0;
3400
3401     /* Evaluate the rhs. We expect an integer here, since float is not
3402     ** supported
3403     */
3404     hie1 (&Expr2);
3405     if (!IsClassInt (Expr2.Type)) {
3406         Error ("Invalid right operand for binary operator `%s'", Op);
3407         /* Continue. Wrong code will be generated, but the compiler won't
3408         ** break, so this is the best error recovery.
3409         */
3410     }
3411     if (ED_IsConstAbs (&Expr2)) {
3412         /* The resulting value is a constant. Scale it. */
3413         if (MustScale) {
3414             Expr2.IVal *= CheckedSizeOf (Indirect (Expr->Type));
3415         }
3416         rflags |= CF_CONST;
3417         lflags |= CF_CONST;
3418     } else {
3419         /* Not constant, load into the primary */
3420         LoadExpr (CF_NONE, &Expr2);
3421         if (MustScale) {
3422             /* lhs is a pointer, scale rhs */
3423             g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Indirect (Expr->Type)));
3424         }
3425     }
3426
3427     /* Setup the code generator flags */
3428     lflags |= TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR;
3429     rflags |= TypeOf (Expr2.Type) | CF_FORCECHAR;
3430
3431     /* Convert the type of the lhs to that of the rhs */
3432     g_typecast (lflags, rflags);
3433
3434     /* Output apropriate code depending on the location */
3435     switch (ED_GetLoc (Expr)) {
3436
3437         case E_LOC_ABS:
3438             /* Absolute: numeric address or const */
3439             if (Gen->Tok == TOK_PLUS_ASSIGN) {
3440                 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3441             } else {
3442                 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3443             }
3444             break;
3445
3446         case E_LOC_GLOBAL:
3447             /* Global variable */
3448             if (Gen->Tok == TOK_PLUS_ASSIGN) {
3449                 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3450             } else {
3451                 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3452             }
3453             break;
3454
3455         case E_LOC_STATIC:
3456         case E_LOC_LITERAL:
3457             /* Static variable or literal in the literal pool */
3458             if (Gen->Tok == TOK_PLUS_ASSIGN) {
3459                 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3460             } else {
3461                 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3462             }
3463             break;
3464
3465         case E_LOC_REGISTER:
3466             /* Register variable */
3467             if (Gen->Tok == TOK_PLUS_ASSIGN) {
3468                 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3469             } else {
3470                 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3471             }
3472             break;
3473
3474         case E_LOC_STACK:
3475             /* Value on the stack */
3476             if (Gen->Tok == TOK_PLUS_ASSIGN) {
3477                 g_addeqlocal (lflags, Expr->IVal, Expr2.IVal);
3478             } else {
3479                 g_subeqlocal (lflags, Expr->IVal, Expr2.IVal);
3480             }
3481             break;
3482
3483         default:
3484             Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
3485     }
3486
3487     /* Expression is a rvalue in the primary now */
3488     ED_MakeRValExpr (Expr);
3489 }
3490
3491
3492
3493 void hie1 (ExprDesc* Expr)
3494 /* Parse first level of expression hierarchy. */
3495 {
3496     hieQuest (Expr);
3497     switch (CurTok.Tok) {
3498
3499         case TOK_ASSIGN:
3500             Assignment (Expr);
3501             break;
3502
3503         case TOK_PLUS_ASSIGN:
3504             addsubeq (&GenPASGN, Expr, "+=");
3505             break;
3506
3507         case TOK_MINUS_ASSIGN:
3508             addsubeq (&GenSASGN, Expr, "-=");
3509             break;
3510
3511         case TOK_MUL_ASSIGN:
3512             opeq (&GenMASGN, Expr, "*=");
3513             break;
3514
3515         case TOK_DIV_ASSIGN:
3516             opeq (&GenDASGN, Expr, "/=");
3517             break;
3518
3519         case TOK_MOD_ASSIGN:
3520             opeq (&GenMOASGN, Expr, "%=");
3521             break;
3522
3523         case TOK_SHL_ASSIGN:
3524             opeq (&GenSLASGN, Expr, "<<=");
3525             break;
3526
3527         case TOK_SHR_ASSIGN:
3528             opeq (&GenSRASGN, Expr, ">>=");
3529             break;
3530
3531         case TOK_AND_ASSIGN:
3532             opeq (&GenAASGN, Expr, "&=");
3533             break;
3534
3535         case TOK_XOR_ASSIGN:
3536             opeq (&GenXOASGN, Expr, "^=");
3537             break;
3538
3539         case TOK_OR_ASSIGN:
3540             opeq (&GenOASGN, Expr, "|=");
3541             break;
3542
3543         default:
3544             break;
3545     }
3546 }
3547
3548
3549
3550 void hie0 (ExprDesc *Expr)
3551 /* Parse comma operator. */
3552 {
3553     hie1 (Expr);
3554     while (CurTok.Tok == TOK_COMMA) {
3555         NextToken ();
3556         hie1 (Expr);
3557     }
3558 }
3559
3560
3561
3562 int evalexpr (unsigned Flags, void (*Func) (ExprDesc*), ExprDesc* Expr)
3563 /* Will evaluate an expression via the given function. If the result is a
3564 ** constant, 0 is returned and the value is put in the Expr struct. If the
3565 ** result is not constant, LoadExpr is called to bring the value into the
3566 ** primary register and 1 is returned.
3567 */
3568 {
3569     /* Evaluate */
3570     ExprWithCheck (Func, Expr);
3571
3572     /* Check for a constant expression */
3573     if (ED_IsConstAbs (Expr)) {
3574         /* Constant expression */
3575         return 0;
3576     } else {
3577         /* Not constant, load into the primary */
3578         LoadExpr (Flags, Expr);
3579         return 1;
3580     }
3581 }
3582
3583
3584
3585 void Expression0 (ExprDesc* Expr)
3586 /* Evaluate an expression via hie0 and put the result into the primary register */
3587 {
3588     ExprWithCheck (hie0, Expr);
3589     LoadExpr (CF_NONE, Expr);
3590 }
3591
3592
3593
3594 void ConstExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3595 /* Will evaluate an expression via the given function. If the result is not
3596 ** a constant of some sort, a diagnostic will be printed, and the value is
3597 ** replaced by a constant one to make sure there are no internal errors that
3598 ** result from this input error.
3599 */
3600 {
3601     ExprWithCheck (Func, Expr);
3602     if (!ED_IsConst (Expr)) {
3603         Error ("Constant expression expected");
3604         /* To avoid any compiler errors, make the expression a valid const */
3605         ED_MakeConstAbsInt (Expr, 1);
3606     }
3607 }
3608
3609
3610
3611 void BoolExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3612 /* Will evaluate an expression via the given function. If the result is not
3613 ** something that may be evaluated in a boolean context, a diagnostic will be
3614 ** printed, and the value is replaced by a constant one to make sure there
3615 ** are no internal errors that result from this input error.
3616 */
3617 {
3618     ExprWithCheck (Func, Expr);
3619     if (!ED_IsBool (Expr)) {
3620         Error ("Boolean expression expected");
3621         /* To avoid any compiler errors, make the expression a valid int */
3622         ED_MakeConstAbsInt (Expr, 1);
3623     }
3624 }
3625
3626
3627
3628 void ConstAbsIntExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3629 /* Will evaluate an expression via the given function. If the result is not
3630 ** a constant numeric integer value, a diagnostic will be printed, and the
3631 ** value is replaced by a constant one to make sure there are no internal
3632 ** errors that result from this input error.
3633 */
3634 {
3635     ExprWithCheck (Func, Expr);
3636     if (!ED_IsConstAbsInt (Expr)) {
3637         Error ("Constant integer expression expected");
3638         /* To avoid any compiler errors, make the expression a valid const */
3639         ED_MakeConstAbsInt (Expr, 1);
3640     }
3641 }