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