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