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