4 * Ullrich von Bassewitz, 21.06.1998
39 /*****************************************************************************/
41 /*****************************************************************************/
45 /* Generator attributes */
46 #define GEN_NOPUSH 0x01 /* Don't push lhs */
48 /* Map a generator function and its attributes to a token */
50 token_t Tok; /* Token to map to */
51 unsigned Flags; /* Flags for generator function */
52 void (*Func) (unsigned, unsigned long); /* Generator func */
55 /* Descriptors for the operations */
56 static GenDesc GenMUL = { TOK_STAR, GEN_NOPUSH, g_mul };
57 static GenDesc GenDIV = { TOK_DIV, GEN_NOPUSH, g_div };
58 static GenDesc GenMOD = { TOK_MOD, GEN_NOPUSH, g_mod };
59 static GenDesc GenASL = { TOK_SHL, GEN_NOPUSH, g_asl };
60 static GenDesc GenASR = { TOK_SHR, GEN_NOPUSH, g_asr };
61 static GenDesc GenLT = { TOK_LT, GEN_NOPUSH, g_lt };
62 static GenDesc GenLE = { TOK_LE, GEN_NOPUSH, g_le };
63 static GenDesc GenGE = { TOK_GE, GEN_NOPUSH, g_ge };
64 static GenDesc GenGT = { TOK_GT, GEN_NOPUSH, g_gt };
65 static GenDesc GenEQ = { TOK_EQ, GEN_NOPUSH, g_eq };
66 static GenDesc GenNE = { TOK_NE, GEN_NOPUSH, g_ne };
67 static GenDesc GenAND = { TOK_AND, GEN_NOPUSH, g_and };
68 static GenDesc GenXOR = { TOK_XOR, GEN_NOPUSH, g_xor };
69 static GenDesc GenOR = { TOK_OR, GEN_NOPUSH, g_or };
70 static GenDesc GenPASGN = { TOK_PLUS_ASSIGN, GEN_NOPUSH, g_add };
71 static GenDesc GenSASGN = { TOK_MINUS_ASSIGN, GEN_NOPUSH, g_sub };
72 static GenDesc GenMASGN = { TOK_MUL_ASSIGN, GEN_NOPUSH, g_mul };
73 static GenDesc GenDASGN = { TOK_DIV_ASSIGN, GEN_NOPUSH, g_div };
74 static GenDesc GenMOASGN = { TOK_MOD_ASSIGN, GEN_NOPUSH, g_mod };
75 static GenDesc GenSLASGN = { TOK_SHL_ASSIGN, GEN_NOPUSH, g_asl };
76 static GenDesc GenSRASGN = { TOK_SHR_ASSIGN, GEN_NOPUSH, g_asr };
77 static GenDesc GenAASGN = { TOK_AND_ASSIGN, GEN_NOPUSH, g_and };
78 static GenDesc GenXOASGN = { TOK_XOR_ASSIGN, GEN_NOPUSH, g_xor };
79 static GenDesc GenOASGN = { TOK_OR_ASSIGN, GEN_NOPUSH, g_or };
83 /*****************************************************************************/
84 /* Function forwards */
85 /*****************************************************************************/
89 static int hie10 (ExprDesc* lval);
90 /* Handle ++, --, !, unary - etc. */
92 static int expr (int (*func) (ExprDesc*), ExprDesc *lval);
93 /* Expression parser; func is either hie0 or hie1. */
97 /*****************************************************************************/
98 /* Helper functions */
99 /*****************************************************************************/
103 static unsigned GlobalModeFlags (unsigned flags)
104 /* Return the addressing mode flags for the variable with the given flags */
107 if (flags == E_TGLAB) {
108 /* External linkage */
110 } else if (flags == E_TREGISTER) {
111 /* Register variable */
121 static int IsNullPtr (ExprDesc* lval)
122 /* Return true if this is the NULL pointer constant */
124 return (IsClassInt (lval->Type) && /* Is it an int? */
125 lval->Flags == E_MCONST && /* Is it constant? */
126 lval->ConstVal == 0); /* And is it's value zero? */
131 static type* promoteint (type* lhst, type* rhst)
132 /* In an expression with two ints, return the type of the result */
134 /* Rules for integer types:
135 * - If one of the values is a long, the result is long.
136 * - If one of the values is unsigned, the result is also unsigned.
137 * - Otherwise the result is an int.
139 if (IsTypeLong (lhst) || IsTypeLong (rhst)) {
140 if (IsSignUnsigned (lhst) || IsSignUnsigned (rhst)) {
146 if (IsSignUnsigned (lhst) || IsSignUnsigned (rhst)) {
156 static unsigned typeadjust (ExprDesc* lhs, ExprDesc* rhs, int NoPush)
157 /* Adjust the two values for a binary operation. lhs is expected on stack or
158 * to be constant, rhs is expected to be in the primary register or constant.
159 * The function will put the type of the result into lhs and return the
160 * code generator flags for the operation.
161 * If NoPush is given, it is assumed that the operation does not expect the lhs
162 * to be on stack, and that lhs is in a register instead.
163 * Beware: The function does only accept int types.
166 unsigned ltype, rtype;
169 /* Get the type strings */
170 type* lhst = lhs->Type;
171 type* rhst = rhs->Type;
173 /* Generate type adjustment code if needed */
174 ltype = TypeOf (lhst);
175 if (lhs->Flags == E_MCONST) {
179 /* Value is in primary register*/
182 rtype = TypeOf (rhst);
183 if (rhs->Flags == E_MCONST) {
186 flags = g_typeadjust (ltype, rtype);
188 /* Set the type of the result */
189 lhs->Type = promoteint (lhst, rhst);
191 /* Return the code generator flags */
197 unsigned assignadjust (type* lhst, ExprDesc* rhs)
198 /* Adjust the type of the right hand expression so that it can be assigned to
199 * the type on the left hand side. This function is used for assignment and
200 * for converting parameters in a function call. It returns the code generator
201 * flags for the operation. The type string of the right hand side will be
202 * set to the type of the left hand side.
205 /* Get the type of the right hand side. Treat function types as
206 * pointer-to-function
208 type* rhst = rhs->Type;
209 if (IsTypeFunc (rhst)) {
210 rhst = PointerTo (rhst);
213 /* After calling this function, rhs will have the type of the lhs */
216 /* First, do some type checking */
217 if (IsTypeVoid (lhst) || IsTypeVoid (rhst)) {
218 /* If one of the sides are of type void, output a more apropriate
221 Error ("Illegal type");
222 } else if (IsClassInt (lhst)) {
223 if (IsClassPtr (rhst)) {
224 /* Pointer -> int conversion */
225 Warning ("Converting pointer to integer without a cast");
226 } else if (!IsClassInt (rhst)) {
227 Error ("Incompatible types");
229 /* Convert the rhs to the type of the lhs. */
230 unsigned flags = TypeOf (rhst);
231 if (rhs->Flags == E_MCONST) {
234 return g_typecast (TypeOf (lhst), flags);
236 } else if (IsClassPtr (lhst)) {
237 if (IsClassPtr (rhst)) {
238 /* Pointer to pointer assignment is valid, if:
239 * - both point to the same types, or
240 * - the rhs pointer is a void pointer, or
241 * - the lhs pointer is a void pointer.
243 if (!IsTypeVoid (Indirect (lhst)) && !IsTypeVoid (Indirect (rhst))) {
244 /* Compare the types */
245 switch (TypeCmp (lhst, rhst)) {
247 case TC_INCOMPATIBLE:
248 Error ("Incompatible pointer types");
252 Error ("Pointer types differ in type qualifiers");
260 } else if (IsClassInt (rhst)) {
261 /* Int to pointer assignment is valid only for constant zero */
262 if (rhs->Flags != E_MCONST || rhs->ConstVal != 0) {
263 Warning ("Converting integer to pointer without a cast");
265 } else if (IsTypeFuncPtr (lhst) && IsTypeFunc(rhst)) {
266 /* Assignment of function to function pointer is allowed, provided
267 * that both functions have the same parameter list.
269 if (TypeCmp (Indirect (lhst), rhst) < TC_EQUAL) {
270 Error ("Incompatible types");
273 Error ("Incompatible types");
276 Error ("Incompatible types");
279 /* Return an int value in all cases where the operands are not both ints */
285 void DefineData (ExprDesc* Expr)
286 /* Output a data definition for the given expression */
288 unsigned Flags = Expr->Flags;
290 switch (Flags & E_MCTYPE) {
294 g_defdata (TypeOf (Expr->Type) | CF_CONST, Expr->ConstVal, 0);
298 /* Register variable. Taking the address is usually not
301 if (!AllowRegVarAddr) {
302 Error ("Cannot take the address of a register variable");
308 /* Local or global symbol */
309 g_defdata (GlobalModeFlags (Flags), Expr->Name, Expr->ConstVal);
313 /* a literal of some kind */
314 g_defdata (CF_STATIC, LiteralPoolLabel, Expr->ConstVal);
318 Internal ("Unknown constant type: %04X", Flags);
324 static void lconst (unsigned Flags, ExprDesc* Expr)
325 /* Load the primary register with some constant value. */
327 switch (Expr->Flags & E_MCTYPE) {
330 g_leasp (Expr->ConstVal);
334 /* Number constant */
335 g_getimmed (Flags | TypeOf (Expr->Type) | CF_CONST, Expr->ConstVal, 0);
339 /* Register variable. Taking the address is usually not
342 if (!AllowRegVarAddr) {
343 Error ("Cannot take the address of a register variable");
349 /* Local or global symbol, load address */
350 Flags |= GlobalModeFlags (Expr->Flags);
352 g_getimmed (Flags, Expr->Name, Expr->ConstVal);
357 g_getimmed (CF_STATIC, LiteralPoolLabel, Expr->ConstVal);
361 Internal ("Unknown constant type: %04X", Expr->Flags);
367 static int kcalc (int tok, long val1, long val2)
368 /* Calculate an operation with left and right operand constant. */
372 return (val1 == val2);
374 return (val1 != val2);
376 return (val1 < val2);
378 return (val1 <= val2);
380 return (val1 >= val2);
382 return (val1 > val2);
384 return (val1 | val2);
386 return (val1 ^ val2);
388 return (val1 & val2);
390 return (val1 >> val2);
392 return (val1 << val2);
394 return (val1 * val2);
397 Error ("Division by zero");
400 return (val1 / val2);
403 Error ("Modulo operation with zero");
406 return (val1 % val2);
408 Internal ("kcalc: got token 0x%X\n", tok);
415 static const GenDesc* FindGen (token_t Tok, const GenDesc** Table)
416 /* Find a token in a generator table */
419 while ((G = *Table) != 0) {
430 static int istypeexpr (void)
431 /* Return true if some sort of variable or type is waiting (helper for cast
432 * and sizeof() in hie10).
437 return CurTok.Tok == TOK_LPAREN && (
438 (NextTok.Tok >= TOK_FIRSTTYPE && NextTok.Tok <= TOK_LASTTYPE) ||
439 (NextTok.Tok == TOK_CONST) ||
440 (NextTok.Tok == TOK_IDENT &&
441 (Entry = FindSym (NextTok.Ident)) != 0 &&
447 static void PushAddr (ExprDesc* lval)
448 /* If the expression contains an address that was somehow evaluated,
449 * push this address on the stack. This is a helper function for all
450 * sorts of implicit or explicit assignment functions where the lvalue
451 * must be saved if it's not constant, before evaluating the rhs.
454 /* Get the address on stack if needed */
455 if (lval->Flags != E_MREG && (lval->Flags & E_MEXPR)) {
456 /* Push the address (always a pointer) */
463 static void MakeConstIntExpr (ExprDesc* Expr, long Value)
464 /* Make Expr a constant integer expression with the given value */
466 Expr->Flags = E_MCONST;
467 Expr->Type = type_int;
468 Expr->ConstVal = Value;
473 void ConstSubExpr (int (*F) (ExprDesc*), ExprDesc* Expr)
474 /* Will evaluate an expression via the given function. If the result is not
475 * a constant, a diagnostic will be printed, and the value is replaced by
476 * a constant one to make sure there are no internal errors that result
477 * from this input error.
480 memset (Expr, 0, sizeof (*Expr));
481 if (F (Expr) != 0 || Expr->Flags != E_MCONST) {
482 Error ("Constant expression expected");
483 /* To avoid any compiler errors, make the expression a valid const */
484 MakeConstIntExpr (Expr, 1);
490 /*****************************************************************************/
492 /*****************************************************************************/
496 void exprhs (unsigned flags, int k, ExprDesc *lval)
497 /* Put the result of an expression into the primary register */
503 /* Dereferenced lvalue */
504 flags |= TypeOf (lval->Type);
505 if (lval->Test & E_FORCETEST) {
507 lval->Test &= ~E_FORCETEST;
509 if (f & E_MGLOBAL) { /* ref to globalvar */
511 flags |= GlobalModeFlags (f);
512 g_getstatic (flags, lval->Name, lval->ConstVal);
513 } else if (f & E_MLOCAL) {
514 /* ref to localvar */
515 g_getlocal (flags, lval->ConstVal);
516 } else if (f & E_MCONST) {
517 /* ref to absolute address */
518 g_getstatic (flags | CF_ABSOLUTE, lval->ConstVal, 0);
519 } else if (f == E_MEOFFS) {
520 g_getind (flags, lval->ConstVal);
521 } else if (f != E_MREG) {
524 } else if (f == E_MEOFFS) {
525 /* reference not storable */
526 flags |= TypeOf (lval->Type);
527 g_inc (flags | CF_CONST, lval->ConstVal);
528 } else if ((f & E_MEXPR) == 0) {
529 /* Constant of some sort, load it into the primary */
530 lconst (flags, lval);
532 if (lval->Test & E_FORCETEST) { /* we testing this value? */
534 flags |= TypeOf (lval->Type);
535 g_test (flags); /* yes, force a test */
536 lval->Test &= ~E_FORCETEST;
542 static unsigned FunctionParamList (FuncDesc* Func)
543 /* Parse a function parameter list and pass the parameters to the called
544 * function. Depending on several criteria this may be done by just pushing
545 * each parameter separately, or creating the parameter frame once and then
546 * storing into this frame.
547 * The function returns the size of the parameters pushed.
552 /* Initialize variables */
553 SymEntry* Param = 0; /* Keep gcc silent */
554 unsigned ParamSize = 0; /* Size of parameters pushed */
555 unsigned ParamCount = 0; /* Number of parameters pushed */
556 unsigned FrameSize = 0; /* Size of parameter frame */
557 unsigned FrameParams = 0; /* Number of params in frame */
558 int FrameOffs = 0; /* Offset into parameter frame */
559 int Ellipsis = 0; /* Function is variadic */
561 /* As an optimization, we may allocate the complete parameter frame at
562 * once instead of pushing each parameter as it comes. We may do that,
565 * - optimizations that increase code size are enabled (allocating the
566 * stack frame at once gives usually larger code).
567 * - we have more than one parameter to push (don't count the last param
568 * for __fastcall__ functions).
570 if (CodeSizeFactor >= 200) {
572 /* Calculate the number and size of the parameters */
573 FrameParams = Func->ParamCount;
574 FrameSize = Func->ParamSize;
575 if (FrameParams > 0 && (Func->Flags & FD_FASTCALL) != 0) {
576 /* Last parameter is not pushed */
577 const SymEntry* LastParam = Func->SymTab->SymTail;
578 FrameSize -= CheckedSizeOf (LastParam->Type);
582 /* Do we have more than one parameter in the frame? */
583 if (FrameParams > 1) {
584 /* Okeydokey, setup the frame */
589 /* Don't use a preallocated frame */
594 /* Parse the actual parameter list */
595 while (CurTok.Tok != TOK_RPAREN) {
600 /* Count arguments */
603 /* Fetch the pointer to the next argument, check for too many args */
604 if (ParamCount <= Func->ParamCount) {
605 /* Beware: If there are parameters with identical names, they
606 * cannot go into the same symbol table, which means that in this
607 * case of errorneous input, the number of nodes in the symbol
608 * table and ParamCount are NOT equal. We have to handle this case
609 * below to avoid segmentation violations. Since we know that this
610 * problem can only occur if there is more than one parameter,
611 * we will just use the last one.
613 if (ParamCount == 1) {
615 Param = Func->SymTab->SymHead;
616 } else if (Param->NextSym != 0) {
618 Param = Param->NextSym;
619 CHECK ((Param->Flags & SC_PARAM) != 0);
621 } else if (!Ellipsis) {
622 /* Too many arguments. Do we have an open param list? */
623 if ((Func->Flags & FD_VARIADIC) == 0) {
624 /* End of param list reached, no ellipsis */
625 Error ("Too many arguments in function call");
627 /* Assume an ellipsis even in case of errors to avoid an error
628 * message for each other argument.
633 /* Do some optimization: If we have a constant value to push,
634 * use a special function that may optimize.
637 if (!Ellipsis && CheckedSizeOf (Param->Type) == 1) {
638 CFlags = CF_FORCECHAR;
641 if (evalexpr (CFlags, hie1, &lval) == 0) {
642 /* A constant value */
646 /* If we don't have an argument spec, accept anything, otherwise
647 * convert the actual argument to the type needed.
650 /* Promote the argument if needed */
651 assignadjust (Param->Type, &lval);
653 /* If we have a prototype, chars may be pushed as chars */
654 Flags |= CF_FORCECHAR;
657 /* Use the type of the argument for the push */
658 Flags |= TypeOf (lval.Type);
660 /* If this is a fastcall function, don't push the last argument */
661 if (ParamCount == Func->ParamCount && (Func->Flags & FD_FASTCALL) != 0) {
662 /* Just load the argument into the primary. This is only needed if
663 * we have a constant argument, otherwise the value is already in
666 if (Flags & CF_CONST) {
667 exprhs (CF_FORCECHAR, 0, &lval);
670 unsigned ArgSize = sizeofarg (Flags);
672 /* We have the space already allocated, store in the frame */
673 CHECK (FrameSize >= ArgSize);
674 FrameSize -= ArgSize;
675 FrameOffs -= ArgSize;
677 g_putlocal (Flags | CF_NOKEEP, FrameOffs, lval.ConstVal);
679 /* Push the argument */
680 g_push (Flags, lval.ConstVal);
683 /* Calculate total parameter size */
684 ParamSize += ArgSize;
687 /* Check for end of argument list */
688 if (CurTok.Tok != TOK_COMMA) {
694 /* Check if we had enough parameters */
695 if (ParamCount < Func->ParamCount) {
696 Error ("Too few arguments in function call");
699 /* The function returns the size of all parameters pushed onto the stack.
700 * However, if there are parameters missing (which is an error and was
701 * flagged by the compiler) AND a stack frame was preallocated above,
702 * we would loose track of the stackpointer and generate an internal error
703 * later. So we correct the value by the parameters that should have been
704 * pushed to avoid an internal compiler error. Since an error was
705 * generated before, no code will be output anyway.
707 return ParamSize + FrameSize;
712 static void FunctionCall (int k, ExprDesc* lval)
713 /* Perform a function call. */
715 FuncDesc* Func; /* Function descriptor */
716 int IsFuncPtr; /* Flag */
717 unsigned ParamSize; /* Number of parameter bytes */
718 CodeMark Mark = 0; /* Initialize to keep gcc silent */
719 int PtrOffs = 0; /* Offset of function pointer on stack */
720 int IsFastCall = 0; /* True if it's a fast call function */
721 int PtrOnStack = 0; /* True if a pointer copy is on stack */
723 /* Get a pointer to the function descriptor from the type string */
724 Func = GetFuncDesc (lval->Type);
726 /* Handle function pointers transparently */
727 IsFuncPtr = IsTypeFuncPtr (lval->Type);
730 /* Check wether it's a fastcall function that has parameters */
731 IsFastCall = IsFastCallFunc (lval->Type + 1) && (Func->ParamCount > 0);
733 /* Things may be difficult, depending on where the function pointer
734 * resides. If the function pointer is an expression of some sort
735 * (not a local or global variable), we have to evaluate this
736 * expression now and save the result for later. Since calls to
737 * function pointers may be nested, we must save it onto the stack.
738 * For fastcall functions we do also need to place a copy of the
739 * pointer on stack, since we cannot use a/x.
741 PtrOnStack = IsFastCall || ((lval->Flags & (E_MGLOBAL | E_MLOCAL)) == 0);
744 /* Not a global or local variable, or a fastcall function. Load
745 * the pointer into the primary and mark it as an expression.
747 exprhs (CF_NONE, k, lval);
748 lval->Flags |= E_MEXPR;
750 /* Remember the code position */
751 Mark = GetCodePos ();
753 /* Push the pointer onto the stack and remember the offset */
758 /* Check for known standard functions and inline them if requested */
759 } else if (InlineStdFuncs && IsStdFunc ((const char*) lval->Name)) {
761 /* Inline this function */
762 HandleStdFunc (Func, lval);
767 /* Parse the parameter list */
768 ParamSize = FunctionParamList (Func);
770 /* We need the closing paren here */
773 /* Special handling for function pointers */
776 /* If the function is not a fastcall function, load the pointer to
777 * the function into the primary.
781 /* Not a fastcall function - we may use the primary */
783 /* If we have no parameters, the pointer is still in the
784 * primary. Remove the code to push it and correct the
787 if (ParamSize == 0) {
792 /* Load from the saved copy */
793 g_getlocal (CF_PTR, PtrOffs);
796 /* Load from original location */
797 exprhs (CF_NONE, k, lval);
800 /* Call the function */
801 g_callind (TypeOf (lval->Type+1), ParamSize, PtrOffs);
805 /* Fastcall function. We cannot use the primary for the function
806 * pointer and must therefore use an offset to the stack location.
807 * Since fastcall functions may never be variadic, we can use the
808 * index register for this purpose.
810 g_callind (CF_LOCAL, ParamSize, PtrOffs);
813 /* If we have a pointer on stack, remove it */
815 g_space (- (int) sizeofarg (CF_PTR));
824 /* Normal function */
825 g_call (TypeOf (lval->Type), (const char*) lval->Name, ParamSize);
832 static int primary (ExprDesc* lval)
833 /* This is the lowest level of the expression parser. */
837 /* Initialize fields in the expression stucture */
838 lval->Test = 0; /* No test */
839 lval->Sym = 0; /* Symbol unknown */
841 /* Character and integer constants. */
842 if (CurTok.Tok == TOK_ICONST || CurTok.Tok == TOK_CCONST) {
843 lval->Flags = E_MCONST | E_TCONST;
844 lval->Type = CurTok.Type;
845 lval->ConstVal = CurTok.IVal;
850 /* Process parenthesized subexpression by calling the whole parser
853 if (CurTok.Tok == TOK_LPAREN) {
855 memset (lval, 0, sizeof (*lval)); /* Remove any attributes */
861 /* If we run into an identifier in preprocessing mode, we assume that this
862 * is an undefined macro and replace it by a constant value of zero.
864 if (Preprocessing && CurTok.Tok == TOK_IDENT) {
865 MakeConstIntExpr (lval, 0);
869 /* All others may only be used if the expression evaluation is not called
870 * recursively by the preprocessor.
873 /* Illegal expression in PP mode */
874 Error ("Preprocessor expression expected");
875 MakeConstIntExpr (lval, 1);
880 if (CurTok.Tok == TOK_IDENT) {
885 /* Get a pointer to the symbol table entry */
886 Sym = lval->Sym = FindSym (CurTok.Ident);
888 /* Is the symbol known? */
891 /* We found the symbol - skip the name token */
894 /* The expression type is the symbol type */
895 lval->Type = Sym->Type;
897 /* Check for illegal symbol types */
898 CHECK ((Sym->Flags & SC_LABEL) != SC_LABEL);
899 if (Sym->Flags & SC_TYPE) {
900 /* Cannot use type symbols */
901 Error ("Variable identifier expected");
902 /* Assume an int type to make lval valid */
903 lval->Flags = E_MLOCAL | E_TLOFFS;
904 lval->Type = type_int;
909 /* Check for legal symbol types */
910 if ((Sym->Flags & SC_CONST) == SC_CONST) {
911 /* Enum or some other numeric constant */
912 lval->Flags = E_MCONST;
913 lval->ConstVal = Sym->V.ConstVal;
915 } else if ((Sym->Flags & SC_FUNC) == SC_FUNC) {
917 lval->Flags = E_MGLOBAL | E_MCONST | E_TGLAB;
918 lval->Name = (unsigned long) Sym->Name;
920 } else if ((Sym->Flags & SC_AUTO) == SC_AUTO) {
921 /* Local variable. If this is a parameter for a variadic
922 * function, we have to add some address calculations, and the
923 * address is not const.
925 if ((Sym->Flags & SC_PARAM) == SC_PARAM && F_IsVariadic (CurrentFunc)) {
926 /* Variadic parameter */
927 g_leavariadic (Sym->V.Offs - F_GetParamSize (CurrentFunc));
928 lval->Flags = E_MEXPR;
931 /* Normal parameter */
932 lval->Flags = E_MLOCAL | E_TLOFFS;
933 lval->ConstVal = Sym->V.Offs;
935 } else if ((Sym->Flags & SC_STATIC) == SC_STATIC) {
936 /* Static variable */
937 if (Sym->Flags & (SC_EXTERN | SC_STORAGE)) {
938 lval->Flags = E_MGLOBAL | E_MCONST | E_TGLAB;
939 lval->Name = (unsigned long) Sym->Name;
941 lval->Flags = E_MGLOBAL | E_MCONST | E_TLLAB;
942 lval->Name = Sym->V.Label;
945 } else if ((Sym->Flags & SC_REGISTER) == SC_REGISTER) {
946 /* Register variable, zero page based */
947 lval->Flags = E_MGLOBAL | E_MCONST | E_TREGISTER;
948 lval->Name = Sym->V.Offs;
951 /* Local static variable */
952 lval->Flags = E_MGLOBAL | E_MCONST | E_TLLAB;
953 lval->Name = Sym->V.Offs;
957 /* The symbol is referenced now */
958 Sym->Flags |= SC_REF;
959 if (IsTypeFunc (lval->Type) || IsTypeArray (lval->Type)) {
965 /* We did not find the symbol. Remember the name, then skip it */
966 strcpy (Ident, CurTok.Ident);
969 /* IDENT is either an auto-declared function or an undefined variable. */
970 if (CurTok.Tok == TOK_LPAREN) {
971 /* Declare a function returning int. For that purpose, prepare a
972 * function signature for a function having an empty param list
975 Warning ("Function call without a prototype");
976 Sym = AddGlobalSym (Ident, GetImplicitFuncType(), SC_EXTERN | SC_REF | SC_FUNC);
977 lval->Type = Sym->Type;
978 lval->Flags = E_MGLOBAL | E_MCONST | E_TGLAB;
979 lval->Name = (unsigned long) Sym->Name;
985 /* Undeclared Variable */
986 Sym = AddLocalSym (Ident, type_int, SC_AUTO | SC_REF, 0);
987 lval->Flags = E_MLOCAL | E_TLOFFS;
988 lval->Type = type_int;
990 Error ("Undefined symbol: `%s'", Ident);
996 /* String literal? */
997 if (CurTok.Tok == TOK_SCONST) {
998 lval->Flags = E_MCONST | E_TLIT;
999 lval->ConstVal = CurTok.IVal;
1000 lval->Type = GetCharArrayType (GetLiteralPoolOffs () - CurTok.IVal);
1005 /* ASM statement? */
1006 if (CurTok.Tok == TOK_ASM) {
1008 lval->Type = type_void;
1009 lval->Flags = E_MEXPR;
1014 /* __AX__ and __EAX__ pseudo values? */
1015 if (CurTok.Tok == TOK_AX || CurTok.Tok == TOK_EAX) {
1016 lval->Type = (CurTok.Tok == TOK_AX)? type_uint : type_ulong;
1017 lval->Flags = E_MREG;
1018 lval->Test &= ~E_CC;
1021 return 1; /* May be used as lvalue */
1024 /* Illegal primary. */
1025 Error ("Expression expected");
1026 MakeConstIntExpr (lval, 1);
1032 static int arrayref (int k, ExprDesc* lval)
1033 /* Handle an array reference */
1047 /* Skip the bracket */
1050 /* Get the type of left side */
1053 /* We can apply a special treatment for arrays that have a const base
1054 * address. This is true for most arrays and will produce a lot better
1055 * code. Check if this is a const base address.
1057 lflags = lval->Flags & ~E_MCTYPE;
1058 ConstBaseAddr = (lflags == E_MCONST) || /* Constant numeric address */
1059 (lflags & E_MGLOBAL) != 0 || /* Static array, or ... */
1060 lflags == E_MLOCAL; /* Local array */
1062 /* If we have a constant base, we delay the address fetch */
1063 Mark1 = GetCodePos ();
1064 Mark2 = 0; /* Silence gcc */
1065 if (!ConstBaseAddr) {
1066 /* Get a pointer to the array into the primary */
1067 exprhs (CF_NONE, k, lval);
1069 /* Get the array pointer on stack. Do not push more than 16
1070 * bit, even if this value is greater, since we cannot handle
1071 * other than 16bit stuff when doing indexing.
1073 Mark2 = GetCodePos ();
1077 /* TOS now contains ptr to array elements. Get the subscript. */
1079 if (l == 0 && lval2.Flags == E_MCONST) {
1081 /* The array subscript is a constant - remove value from stack */
1082 if (!ConstBaseAddr) {
1086 /* Get an array pointer into the primary */
1087 exprhs (CF_NONE, k, lval);
1090 if (IsClassPtr (tptr1)) {
1092 /* Scale the subscript value according to element size */
1093 lval2.ConstVal *= CheckedPSizeOf (tptr1);
1095 /* Remove code for lhs load */
1098 /* Handle constant base array on stack. Be sure NOT to
1099 * handle pointers the same way, this won't work.
1101 if (IsTypeArray (tptr1) &&
1102 ((lval->Flags & ~E_MCTYPE) == E_MCONST ||
1103 (lval->Flags & ~E_MCTYPE) == E_MLOCAL ||
1104 (lval->Flags & E_MGLOBAL) != 0 ||
1105 (lval->Flags == E_MEOFFS))) {
1106 lval->ConstVal += lval2.ConstVal;
1109 /* Pointer - load into primary and remember offset */
1110 if ((lval->Flags & E_MEXPR) == 0 || k != 0) {
1111 exprhs (CF_NONE, k, lval);
1113 lval->ConstVal = lval2.ConstVal;
1114 lval->Flags = E_MEOFFS;
1117 /* Result is of element type */
1118 lval->Type = Indirect (tptr1);
1123 } else if (IsClassPtr (tptr2 = lval2.Type)) {
1124 /* Subscript is pointer, get element type */
1125 lval2.Type = Indirect (tptr2);
1127 /* Scale the rhs value in the primary register */
1128 g_scale (TypeOf (tptr1), CheckedSizeOf (lval2.Type));
1130 lval->Type = lval2.Type;
1132 Error ("Cannot subscript");
1135 /* Add the subscript. Since arrays are indexed by integers,
1136 * we will ignore the true type of the subscript here and
1137 * use always an int.
1139 g_inc (CF_INT | CF_CONST, lval2.ConstVal);
1143 /* Array subscript is not constant. Load it into the primary */
1144 Mark2 = GetCodePos ();
1145 exprhs (CF_NONE, l, &lval2);
1148 if (IsClassPtr (tptr1)) {
1150 /* Get the element type */
1151 lval->Type = Indirect (tptr1);
1153 /* Indexing is based on int's, so we will just use the integer
1154 * portion of the index (which is in (e)ax, so there's no further
1157 g_scale (CF_INT, CheckedSizeOf (lval->Type));
1159 } else if (IsClassPtr (tptr2)) {
1161 /* Get the element type */
1162 lval2.Type = Indirect (tptr2);
1164 /* Get the int value on top. If we go here, we're sure,
1165 * both values are 16 bit (the first one was truncated
1166 * if necessary and the second one is a pointer).
1167 * Note: If ConstBaseAddr is true, we don't have a value on
1168 * stack, so to "swap" both, just push the subscript.
1170 if (ConstBaseAddr) {
1172 exprhs (CF_NONE, k, lval);
1179 g_scale (TypeOf (tptr1), CheckedSizeOf (lval2.Type));
1180 lval->Type = lval2.Type;
1182 Error ("Cannot subscript");
1185 /* The offset is now in the primary register. It didn't have a
1186 * constant base address for the lhs, the lhs address is already
1187 * on stack, and we must add the offset. If the base address was
1188 * constant, we call special functions to add the address to the
1191 if (!ConstBaseAddr) {
1192 /* Add the subscript. Both values are int sized. */
1196 /* If the subscript has itself a constant address, it is often
1197 * a better idea to reverse again the order of the evaluation.
1198 * This will generate better code if the subscript is a byte
1199 * sized variable. But beware: This is only possible if the
1200 * subscript was not scaled, that is, if this was a byte array
1203 rflags = lval2.Flags & ~E_MCTYPE;
1204 ConstSubAddr = (rflags == E_MCONST) || /* Constant numeric address */
1205 (rflags & E_MGLOBAL) != 0 || /* Static array, or ... */
1206 rflags == E_MLOCAL; /* Local array */
1208 if (ConstSubAddr && CheckedSizeOf (lval->Type) == 1) {
1212 /* Reverse the order of evaluation */
1213 unsigned flags = (CheckedSizeOf (lval2.Type) == 1)? CF_CHAR : CF_INT;
1216 /* Get a pointer to the array into the primary. We have changed
1217 * Type above but we need the original type to load the
1218 * address, so restore it temporarily.
1220 SavedType = lval->Type;
1222 exprhs (CF_NONE, k, lval);
1223 lval->Type = SavedType;
1225 /* Add the variable */
1226 if (rflags == E_MLOCAL) {
1227 g_addlocal (flags, lval2.ConstVal);
1229 flags |= GlobalModeFlags (lval2.Flags);
1230 g_addstatic (flags, lval2.Name, lval2.ConstVal);
1233 if (lflags == E_MCONST) {
1234 /* Constant numeric address. Just add it */
1235 g_inc (CF_INT | CF_UNSIGNED, lval->ConstVal);
1236 } else if (lflags == E_MLOCAL) {
1237 /* Base address is a local variable address */
1238 if (IsTypeArray (tptr1)) {
1239 g_addaddr_local (CF_INT, lval->ConstVal);
1241 g_addlocal (CF_PTR, lval->ConstVal);
1244 /* Base address is a static variable address */
1245 unsigned flags = CF_INT;
1246 flags |= GlobalModeFlags (lval->Flags);
1247 if (IsTypeArray (tptr1)) {
1248 g_addaddr_static (flags, lval->Name, lval->ConstVal);
1250 g_addstatic (flags, lval->Name, lval->ConstVal);
1256 lval->Flags = E_MEXPR;
1259 return !IsTypeArray (lval->Type);
1265 static int structref (int k, ExprDesc* lval)
1266 /* Process struct field after . or ->. */
1272 /* Skip the token and check for an identifier */
1274 if (CurTok.Tok != TOK_IDENT) {
1275 Error ("Identifier expected");
1276 lval->Type = type_int;
1280 /* Get the symbol table entry and check for a struct field */
1281 strcpy (Ident, CurTok.Ident);
1283 Field = FindStructField (lval->Type, Ident);
1285 Error ("Struct/union has no field named `%s'", Ident);
1286 lval->Type = type_int;
1290 /* If we have constant input data, the result is also constant */
1291 flags = lval->Flags & ~E_MCTYPE;
1292 if (flags == E_MCONST ||
1293 (k == 0 && (flags == E_MLOCAL ||
1294 (flags & E_MGLOBAL) != 0 ||
1295 lval->Flags == E_MEOFFS))) {
1296 lval->ConstVal += Field->V.Offs;
1298 if ((flags & E_MEXPR) == 0 || k != 0) {
1299 exprhs (CF_NONE, k, lval);
1301 lval->ConstVal = Field->V.Offs;
1302 lval->Flags = E_MEOFFS;
1304 lval->Type = Field->Type;
1305 return !IsTypeArray (Field->Type);
1310 static int hie11 (ExprDesc *lval)
1311 /* Handle compound types (structs and arrays) */
1318 if (CurTok.Tok < TOK_LBRACK || CurTok.Tok > TOK_PTR_REF) {
1325 if (CurTok.Tok == TOK_LBRACK) {
1327 /* Array reference */
1328 k = arrayref (k, lval);
1330 } else if (CurTok.Tok == TOK_LPAREN) {
1332 /* Function call. Skip the opening parenthesis */
1335 if (IsTypeFunc (lval->Type) || IsTypeFuncPtr (lval->Type)) {
1337 /* Call the function */
1338 FunctionCall (k, lval);
1340 /* Result is in the primary register */
1341 lval->Flags = E_MEXPR;
1344 lval->Type = GetFuncReturn (lval->Type);
1347 Error ("Illegal function call");
1351 } else if (CurTok.Tok == TOK_DOT) {
1353 if (!IsClassStruct (lval->Type)) {
1354 Error ("Struct expected");
1356 k = structref (0, lval);
1358 } else if (CurTok.Tok == TOK_PTR_REF) {
1361 if (tptr[0] != T_PTR || (tptr[1] & T_STRUCT) == 0) {
1362 Error ("Struct pointer expected");
1364 k = structref (k, lval);
1374 static void store (ExprDesc* lval)
1375 /* Store primary reg into this reference */
1381 flags = TypeOf (lval->Type);
1382 if (f & E_MGLOBAL) {
1383 flags |= GlobalModeFlags (f);
1390 g_putstatic (flags, lval->Name, lval->ConstVal);
1392 } else if (f & E_MLOCAL) {
1393 g_putlocal (flags, lval->ConstVal, 0);
1394 } else if (f == E_MEOFFS) {
1395 g_putind (flags, lval->ConstVal);
1396 } else if (f != E_MREG) {
1398 g_putind (flags, 0);
1400 /* Store into absolute address */
1401 g_putstatic (flags | CF_ABSOLUTE, lval->ConstVal, 0);
1405 /* Assume that each one of the stores will invalidate CC */
1406 lval->Test &= ~E_CC;
1411 static void pre_incdec (ExprDesc* lval, void (*inc) (unsigned, unsigned long))
1412 /* Handle --i and ++i */
1419 if ((k = hie10 (lval)) == 0) {
1420 Error ("Invalid lvalue");
1424 /* Get the data type */
1425 flags = TypeOf (lval->Type) | CF_FORCECHAR | CF_CONST;
1427 /* Get the increment value in bytes */
1428 val = (lval->Type [0] == T_PTR)? CheckedPSizeOf (lval->Type) : 1;
1430 /* We're currently only able to handle some adressing modes */
1431 if ((lval->Flags & E_MGLOBAL) == 0 && /* Global address? */
1432 (lval->Flags & E_MLOCAL) == 0 && /* Local address? */
1433 (lval->Flags & E_MCONST) == 0 && /* Constant address? */
1434 (lval->Flags & E_MEXPR) == 0) { /* Address in a/x? */
1436 /* Use generic code. Push the address if needed */
1439 /* Fetch the value */
1440 exprhs (CF_NONE, k, lval);
1442 /* Increment value in primary */
1445 /* Store the result back */
1450 /* Special code for some addressing modes - use the special += ops */
1451 if (lval->Flags & E_MGLOBAL) {
1452 flags |= GlobalModeFlags (lval->Flags);
1454 g_addeqstatic (flags, lval->Name, lval->ConstVal, val);
1456 g_subeqstatic (flags, lval->Name, lval->ConstVal, val);
1458 } else if (lval->Flags & E_MLOCAL) {
1459 /* ref to localvar */
1461 g_addeqlocal (flags, lval->ConstVal, val);
1463 g_subeqlocal (flags, lval->ConstVal, val);
1465 } else if (lval->Flags & E_MCONST) {
1466 /* ref to absolute address */
1467 flags |= CF_ABSOLUTE;
1469 g_addeqstatic (flags, lval->ConstVal, 0, val);
1471 g_subeqstatic (flags, lval->ConstVal, 0, val);
1473 } else if (lval->Flags & E_MEXPR) {
1474 /* Address in a/x, check if we have an offset */
1475 unsigned Offs = (lval->Flags == E_MEOFFS)? lval->ConstVal : 0;
1477 g_addeqind (flags, Offs, val);
1479 g_subeqind (flags, Offs, val);
1482 Internal ("Invalid addressing mode");
1487 /* Result is an expression */
1488 lval->Flags = E_MEXPR;
1493 static void post_incdec (ExprDesc *lval, int k, void (*inc) (unsigned, unsigned long))
1494 /* Handle i-- and i++ */
1500 Error ("Invalid lvalue");
1504 /* Get the data type */
1505 flags = TypeOf (lval->Type);
1507 /* Push the address if needed */
1510 /* Fetch the value and save it (since it's the result of the expression) */
1511 exprhs (CF_NONE, 1, lval);
1512 g_save (flags | CF_FORCECHAR);
1514 /* If we have a pointer expression, increment by the size of the type */
1515 if (lval->Type[0] == T_PTR) {
1516 inc (flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (lval->Type + 1));
1518 inc (flags | CF_CONST | CF_FORCECHAR, 1);
1521 /* Store the result back */
1524 /* Restore the original value */
1525 g_restore (flags | CF_FORCECHAR);
1526 lval->Flags = E_MEXPR;
1531 static void unaryop (int tok, ExprDesc* lval)
1532 /* Handle unary -/+ and ~ */
1539 if (k == 0 && (lval->Flags & E_MCONST) != 0) {
1540 /* Value is constant */
1542 case TOK_MINUS: lval->ConstVal = -lval->ConstVal; break;
1543 case TOK_PLUS: break;
1544 case TOK_COMP: lval->ConstVal = ~lval->ConstVal; break;
1545 default: Internal ("Unexpected token: %d", tok);
1548 /* Value is not constant */
1549 exprhs (CF_NONE, k, lval);
1551 /* Get the type of the expression */
1552 flags = TypeOf (lval->Type);
1554 /* Handle the operation */
1556 case TOK_MINUS: g_neg (flags); break;
1557 case TOK_PLUS: break;
1558 case TOK_COMP: g_com (flags); break;
1559 default: Internal ("Unexpected token: %d", tok);
1561 lval->Flags = E_MEXPR;
1567 static int typecast (ExprDesc* lval)
1568 /* Handle an explicit cast */
1571 type Type[MAXTYPELEN];
1573 /* Skip the left paren */
1582 /* Read the expression we have to cast */
1585 /* If the expression is a function, treat it as pointer-to-function */
1586 if (IsTypeFunc (lval->Type)) {
1587 lval->Type = PointerTo (lval->Type);
1590 /* Check for a constant on the right side */
1591 if (k == 0 && lval->Flags == E_MCONST) {
1593 /* A cast of a constant to something else. If the new type is an int,
1594 * be sure to handle the size extension correctly. If the new type is
1595 * not an int, the cast is implementation specific anyway, so leave
1598 if (IsClassInt (Type)) {
1600 /* Get the current and new size of the value */
1601 unsigned OldBits = CheckedSizeOf (lval->Type) * 8;
1602 unsigned NewBits = CheckedSizeOf (Type) * 8;
1604 /* Check if the new datatype will have a smaller range */
1605 if (NewBits <= OldBits) {
1607 /* Cut the value to the new size */
1608 lval->ConstVal &= (0xFFFFFFFFUL >> (32 - NewBits));
1610 /* If the new type is signed, sign extend the value */
1611 if (!IsSignUnsigned (Type)) {
1612 lval->ConstVal |= ((~0L) << NewBits);
1617 /* Sign extend the value if needed */
1618 if (!IsSignUnsigned (lval->Type) && !IsSignUnsigned (Type)) {
1619 if (lval->ConstVal & (0x01UL << (OldBits-1))) {
1620 lval->ConstVal |= ((~0L) << OldBits);
1628 /* Not a constant. Be sure to ignore casts to void */
1629 if (!IsTypeVoid (Type)) {
1631 /* If the size does not change, leave the value alone. Otherwise,
1632 * we have to load the value into the primary and generate code to
1633 * cast the value in the primary register.
1635 if (SizeOf (Type) != SizeOf (lval->Type)) {
1637 /* Load the value into the primary */
1638 exprhs (CF_NONE, k, lval);
1640 /* Emit typecast code */
1641 g_typecast (TypeOf (Type), TypeOf (lval->Type));
1643 /* Value is now in primary */
1644 lval->Flags = E_MEXPR;
1650 /* In any case, use the new type */
1651 lval->Type = TypeDup (Type);
1659 static int hie10 (ExprDesc* lval)
1660 /* Handle ++, --, !, unary - etc. */
1665 switch (CurTok.Tok) {
1668 pre_incdec (lval, g_inc);
1672 pre_incdec (lval, g_dec);
1678 unaryop (CurTok.Tok, lval);
1683 if (evalexpr (CF_NONE, hie10, lval) == 0) {
1684 /* Constant expression */
1685 lval->ConstVal = !lval->ConstVal;
1687 g_bneg (TypeOf (lval->Type));
1688 lval->Test |= E_CC; /* bneg will set cc */
1689 lval->Flags = E_MEXPR; /* say it's an expr */
1691 return 0; /* expr not storable */
1695 if (evalexpr (CF_NONE, hie10, lval) != 0) {
1696 /* Expression is not const, indirect value loaded into primary */
1697 lval->Flags = E_MEXPR;
1698 lval->ConstVal = 0; /* Offset is zero now */
1701 if (IsClassPtr (t)) {
1702 lval->Type = Indirect (t);
1704 Error ("Illegal indirection");
1711 /* The & operator may be applied to any lvalue, and it may be
1712 * applied to functions, even if they're no lvalues.
1714 if (k == 0 && !IsTypeFunc (lval->Type)) {
1715 /* Allow the & operator with an array */
1716 if (!IsTypeArray (lval->Type)) {
1717 Error ("Illegal address");
1720 t = TypeAlloc (TypeLen (lval->Type) + 2);
1722 TypeCpy (t + 1, lval->Type);
1729 if (istypeexpr ()) {
1730 type Type[MAXTYPELEN];
1732 lval->ConstVal = CheckedSizeOf (ParseType (Type));
1735 /* Remember the output queue pointer */
1736 CodeMark Mark = GetCodePos ();
1738 lval->ConstVal = CheckedSizeOf (lval->Type);
1739 /* Remove any generated code */
1742 lval->Flags = E_MCONST | E_TCONST;
1743 lval->Type = type_uint;
1744 lval->Test &= ~E_CC;
1748 if (istypeexpr ()) {
1750 return typecast (lval);
1755 switch (CurTok.Tok) {
1757 post_incdec (lval, k, g_inc);
1761 post_incdec (lval, k, g_dec);
1771 static int hie_internal (const GenDesc** ops, /* List of generators */
1772 ExprDesc* lval, /* parent expr's lval */
1773 int (*hienext) (ExprDesc*),
1774 int* UsedGen) /* next higher level */
1775 /* Helper function */
1782 token_t tok; /* The operator token */
1783 unsigned ltype, type;
1784 int rconst; /* Operand is a constant */
1790 while ((Gen = FindGen (CurTok.Tok, ops)) != 0) {
1792 /* Tell the caller that we handled it's ops */
1795 /* All operators that call this function expect an int on the lhs */
1796 if (!IsClassInt (lval->Type)) {
1797 Error ("Integer expression expected");
1800 /* Remember the operator token, then skip it */
1804 /* Get the lhs on stack */
1805 Mark1 = GetCodePos ();
1806 ltype = TypeOf (lval->Type);
1807 if (k == 0 && lval->Flags == E_MCONST) {
1808 /* Constant value */
1809 Mark2 = GetCodePos ();
1810 g_push (ltype | CF_CONST, lval->ConstVal);
1812 /* Value not constant */
1813 exprhs (CF_NONE, k, lval);
1814 Mark2 = GetCodePos ();
1818 /* Get the right hand side */
1819 rconst = (evalexpr (CF_NONE, hienext, &lval2) == 0);
1821 /* Check the type of the rhs */
1822 if (!IsClassInt (lval2.Type)) {
1823 Error ("Integer expression expected");
1826 /* Check for const operands */
1827 if (k == 0 && lval->Flags == E_MCONST && rconst) {
1829 /* Both operands are constant, remove the generated code */
1833 /* Evaluate the result */
1834 lval->ConstVal = kcalc (tok, lval->ConstVal, lval2.ConstVal);
1836 /* Get the type of the result */
1837 lval->Type = promoteint (lval->Type, lval2.Type);
1841 /* If the right hand side is constant, and the generator function
1842 * expects the lhs in the primary, remove the push of the primary
1845 unsigned rtype = TypeOf (lval2.Type);
1848 /* Second value is constant - check for div */
1851 if (tok == TOK_DIV && lval2.ConstVal == 0) {
1852 Error ("Division by zero");
1853 } else if (tok == TOK_MOD && lval2.ConstVal == 0) {
1854 Error ("Modulo operation with zero");
1856 if ((Gen->Flags & GEN_NOPUSH) != 0) {
1859 ltype |= CF_REG; /* Value is in register */
1863 /* Determine the type of the operation result. */
1864 type |= g_typeadjust (ltype, rtype);
1865 lval->Type = promoteint (lval->Type, lval2.Type);
1868 Gen->Func (type, lval2.ConstVal);
1869 lval->Flags = E_MEXPR;
1872 /* We have a rvalue now */
1881 static int hie_compare (const GenDesc** ops, /* List of generators */
1882 ExprDesc* lval, /* parent expr's lval */
1883 int (*hienext) (ExprDesc*))
1884 /* Helper function for the compare operators */
1891 token_t tok; /* The operator token */
1893 int rconst; /* Operand is a constant */
1898 while ((Gen = FindGen (CurTok.Tok, ops)) != 0) {
1900 /* Remember the operator token, then skip it */
1904 /* Get the lhs on stack */
1905 Mark1 = GetCodePos ();
1906 ltype = TypeOf (lval->Type);
1907 if (k == 0 && lval->Flags == E_MCONST) {
1908 /* Constant value */
1909 Mark2 = GetCodePos ();
1910 g_push (ltype | CF_CONST, lval->ConstVal);
1912 /* Value not constant */
1913 exprhs (CF_NONE, k, lval);
1914 Mark2 = GetCodePos ();
1918 /* Get the right hand side */
1919 rconst = (evalexpr (CF_NONE, hienext, &lval2) == 0);
1921 /* Make sure, the types are compatible */
1922 if (IsClassInt (lval->Type)) {
1923 if (!IsClassInt (lval2.Type) && !(IsClassPtr(lval2.Type) && IsNullPtr(lval))) {
1924 Error ("Incompatible types");
1926 } else if (IsClassPtr (lval->Type)) {
1927 if (IsClassPtr (lval2.Type)) {
1928 /* Both pointers are allowed in comparison if they point to
1929 * the same type, or if one of them is a void pointer.
1931 type* left = Indirect (lval->Type);
1932 type* right = Indirect (lval2.Type);
1933 if (TypeCmp (left, right) < TC_EQUAL && *left != T_VOID && *right != T_VOID) {
1934 /* Incomatible pointers */
1935 Error ("Incompatible types");
1937 } else if (!IsNullPtr (&lval2)) {
1938 Error ("Incompatible types");
1942 /* Check for const operands */
1943 if (k == 0 && lval->Flags == E_MCONST && rconst) {
1945 /* Both operands are constant, remove the generated code */
1949 /* Evaluate the result */
1950 lval->ConstVal = kcalc (tok, lval->ConstVal, lval2.ConstVal);
1954 /* If the right hand side is constant, and the generator function
1955 * expects the lhs in the primary, remove the push of the primary
1961 if ((Gen->Flags & GEN_NOPUSH) != 0) {
1964 ltype |= CF_REG; /* Value is in register */
1968 /* Determine the type of the operation result. If the left
1969 * operand is of type char and the right is a constant, or
1970 * if both operands are of type char, we will encode the
1971 * operation as char operation. Otherwise the default
1972 * promotions are used.
1974 if (IsTypeChar (lval->Type) && (IsTypeChar (lval2.Type) || rconst)) {
1976 if (IsSignUnsigned (lval->Type) || IsSignUnsigned (lval2.Type)) {
1977 flags |= CF_UNSIGNED;
1980 flags |= CF_FORCECHAR;
1983 unsigned rtype = TypeOf (lval2.Type) | (flags & CF_CONST);
1984 flags |= g_typeadjust (ltype, rtype);
1988 Gen->Func (flags, lval2.ConstVal);
1989 lval->Flags = E_MEXPR;
1992 /* Result type is always int */
1993 lval->Type = type_int;
1995 /* We have a rvalue now, condition codes are set */
2005 static int hie9 (ExprDesc *lval)
2006 /* Process * and / operators. */
2008 static const GenDesc* hie9_ops [] = {
2009 &GenMUL, &GenDIV, &GenMOD, 0
2013 return hie_internal (hie9_ops, lval, hie10, &UsedGen);
2018 static void parseadd (int k, ExprDesc* lval)
2019 /* Parse an expression with the binary plus operator. lval contains the
2020 * unprocessed left hand side of the expression and will contain the
2021 * result of the expression on return.
2025 unsigned flags; /* Operation flags */
2026 CodeMark Mark; /* Remember code position */
2027 type* lhst; /* Type of left hand side */
2028 type* rhst; /* Type of right hand side */
2031 /* Skip the PLUS token */
2034 /* Get the left hand side type, initialize operation flags */
2038 /* Check for constness on both sides */
2039 if (k == 0 && (lval->Flags & E_MCONST) != 0) {
2041 /* The left hand side is a constant. Good. Get rhs */
2043 if (k == 0 && lval2.Flags == E_MCONST) {
2045 /* Right hand side is also constant. Get the rhs type */
2048 /* Both expressions are constants. Check for pointer arithmetic */
2049 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2050 /* Left is pointer, right is int, must scale rhs */
2051 lval->ConstVal += lval2.ConstVal * CheckedPSizeOf (lhst);
2052 /* Result type is a pointer */
2053 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2054 /* Left is int, right is pointer, must scale lhs */
2055 lval->ConstVal = lval->ConstVal * CheckedPSizeOf (rhst) + lval2.ConstVal;
2056 /* Result type is a pointer */
2057 lval->Type = lval2.Type;
2058 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2059 /* Integer addition */
2060 lval->ConstVal += lval2.ConstVal;
2061 typeadjust (lval, &lval2, 1);
2064 Error ("Invalid operands for binary operator `+'");
2067 /* Result is constant, condition codes not set */
2068 lval->Test &= ~E_CC;
2072 /* lhs is a constant and rhs is not constant. Load rhs into
2075 exprhs (CF_NONE, k, &lval2);
2077 /* Beware: The check above (for lhs) lets not only pass numeric
2078 * constants, but also constant addresses (labels), maybe even
2079 * with an offset. We have to check for that here.
2082 /* First, get the rhs type. */
2086 if (lval->Flags == E_MCONST) {
2087 /* A numerical constant */
2090 /* Constant address label */
2091 flags |= GlobalModeFlags (lval->Flags) | CF_CONSTADDR;
2094 /* Check for pointer arithmetic */
2095 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2096 /* Left is pointer, right is int, must scale rhs */
2097 g_scale (CF_INT, CheckedPSizeOf (lhst));
2098 /* Operate on pointers, result type is a pointer */
2100 /* Generate the code for the add */
2101 if (lval->Flags == E_MCONST) {
2102 /* Numeric constant */
2103 g_inc (flags, lval->ConstVal);
2105 /* Constant address */
2106 g_addaddr_static (flags, lval->Name, lval->ConstVal);
2108 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2110 /* Left is int, right is pointer, must scale lhs. */
2111 unsigned ScaleFactor = CheckedPSizeOf (rhst);
2113 /* Operate on pointers, result type is a pointer */
2115 lval->Type = lval2.Type;
2117 /* Since we do already have rhs in the primary, if lhs is
2118 * not a numeric constant, and the scale factor is not one
2119 * (no scaling), we must take the long way over the stack.
2121 if (lval->Flags == E_MCONST) {
2122 /* Numeric constant, scale lhs */
2123 lval->ConstVal *= ScaleFactor;
2124 /* Generate the code for the add */
2125 g_inc (flags, lval->ConstVal);
2126 } else if (ScaleFactor == 1) {
2127 /* Constant address but no need to scale */
2128 g_addaddr_static (flags, lval->Name, lval->ConstVal);
2130 /* Constant address that must be scaled */
2131 g_push (TypeOf (lval2.Type), 0); /* rhs --> stack */
2132 g_getimmed (flags, lval->Name, lval->ConstVal);
2133 g_scale (CF_PTR, ScaleFactor);
2136 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2137 /* Integer addition */
2138 flags |= typeadjust (lval, &lval2, 1);
2139 /* Generate the code for the add */
2140 if (lval->Flags == E_MCONST) {
2141 /* Numeric constant */
2142 g_inc (flags, lval->ConstVal);
2144 /* Constant address */
2145 g_addaddr_static (flags, lval->Name, lval->ConstVal);
2149 Error ("Invalid operands for binary operator `+'");
2152 /* Result is in primary register */
2153 lval->Flags = E_MEXPR;
2154 lval->Test &= ~E_CC;
2160 /* Left hand side is not constant. Get the value onto the stack. */
2161 exprhs (CF_NONE, k, lval); /* --> primary register */
2162 Mark = GetCodePos ();
2163 g_push (TypeOf (lval->Type), 0); /* --> stack */
2165 /* Evaluate the rhs */
2166 if (evalexpr (CF_NONE, hie9, &lval2) == 0) {
2168 /* Right hand side is a constant. Get the rhs type */
2171 /* Remove pushed value from stack */
2173 pop (TypeOf (lval->Type));
2175 /* Check for pointer arithmetic */
2176 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2177 /* Left is pointer, right is int, must scale rhs */
2178 lval2.ConstVal *= CheckedPSizeOf (lhst);
2179 /* Operate on pointers, result type is a pointer */
2181 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2182 /* Left is int, right is pointer, must scale lhs (ptr only) */
2183 g_scale (CF_INT | CF_CONST, CheckedPSizeOf (rhst));
2184 /* Operate on pointers, result type is a pointer */
2186 lval->Type = lval2.Type;
2187 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2188 /* Integer addition */
2189 flags = typeadjust (lval, &lval2, 1);
2192 Error ("Invalid operands for binary operator `+'");
2195 /* Generate code for the add */
2196 g_inc (flags | CF_CONST, lval2.ConstVal);
2198 /* Result is in primary register */
2199 lval->Flags = E_MEXPR;
2200 lval->Test &= ~E_CC;
2204 /* lhs and rhs are not constant. Get the rhs type. */
2207 /* Check for pointer arithmetic */
2208 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2209 /* Left is pointer, right is int, must scale rhs */
2210 g_scale (CF_INT, CheckedPSizeOf (lhst));
2211 /* Operate on pointers, result type is a pointer */
2213 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2214 /* Left is int, right is pointer, must scale lhs */
2215 g_tosint (TypeOf (rhst)); /* Make sure, TOS is int */
2216 g_swap (CF_INT); /* Swap TOS and primary */
2217 g_scale (CF_INT, CheckedPSizeOf (rhst));
2218 /* Operate on pointers, result type is a pointer */
2220 lval->Type = lval2.Type;
2221 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2222 /* Integer addition */
2223 flags = typeadjust (lval, &lval2, 0);
2226 Error ("Invalid operands for binary operator `+'");
2229 /* Generate code for the add */
2232 /* Result is in primary register */
2233 lval->Flags = E_MEXPR;
2234 lval->Test &= ~E_CC;
2243 static void parsesub (int k, ExprDesc* lval)
2244 /* Parse an expression with the binary minus operator. lval contains the
2245 * unprocessed left hand side of the expression and will contain the
2246 * result of the expression on return.
2250 unsigned flags; /* Operation flags */
2251 type* lhst; /* Type of left hand side */
2252 type* rhst; /* Type of right hand side */
2253 CodeMark Mark1; /* Save position of output queue */
2254 CodeMark Mark2; /* Another position in the queue */
2255 int rscale; /* Scale factor for the result */
2258 /* Skip the MINUS token */
2261 /* Get the left hand side type, initialize operation flags */
2264 rscale = 1; /* Scale by 1, that is, don't scale */
2266 /* Remember the output queue position, then bring the value onto the stack */
2267 Mark1 = GetCodePos ();
2268 exprhs (CF_NONE, k, lval); /* --> primary register */
2269 Mark2 = GetCodePos ();
2270 g_push (TypeOf (lhst), 0); /* --> stack */
2272 /* Parse the right hand side */
2273 if (evalexpr (CF_NONE, hie9, &lval2) == 0) {
2275 /* The right hand side is constant. Get the rhs type. */
2278 /* Check left hand side */
2279 if (k == 0 && (lval->Flags & E_MCONST) != 0) {
2281 /* Both sides are constant, remove generated code */
2283 pop (TypeOf (lhst)); /* Clean up the stack */
2285 /* Check for pointer arithmetic */
2286 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2287 /* Left is pointer, right is int, must scale rhs */
2288 lval->ConstVal -= lval2.ConstVal * CheckedPSizeOf (lhst);
2289 /* Operate on pointers, result type is a pointer */
2290 } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2291 /* Left is pointer, right is pointer, must scale result */
2292 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2293 Error ("Incompatible pointer types");
2295 lval->ConstVal = (lval->ConstVal - lval2.ConstVal) /
2296 CheckedPSizeOf (lhst);
2298 /* Operate on pointers, result type is an integer */
2299 lval->Type = type_int;
2300 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2301 /* Integer subtraction */
2302 typeadjust (lval, &lval2, 1);
2303 lval->ConstVal -= lval2.ConstVal;
2306 Error ("Invalid operands for binary operator `-'");
2309 /* Result is constant, condition codes not set */
2310 /* lval->Flags = E_MCONST; ### */
2311 lval->Test &= ~E_CC;
2315 /* Left hand side is not constant, right hand side is.
2316 * Remove pushed value from stack.
2319 pop (TypeOf (lhst));
2321 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2322 /* Left is pointer, right is int, must scale rhs */
2323 lval2.ConstVal *= CheckedPSizeOf (lhst);
2324 /* Operate on pointers, result type is a pointer */
2326 } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2327 /* Left is pointer, right is pointer, must scale result */
2328 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2329 Error ("Incompatible pointer types");
2331 rscale = CheckedPSizeOf (lhst);
2333 /* Operate on pointers, result type is an integer */
2335 lval->Type = type_int;
2336 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2337 /* Integer subtraction */
2338 flags = typeadjust (lval, &lval2, 1);
2341 Error ("Invalid operands for binary operator `-'");
2344 /* Do the subtraction */
2345 g_dec (flags | CF_CONST, lval2.ConstVal);
2347 /* If this was a pointer subtraction, we must scale the result */
2349 g_scale (flags, -rscale);
2352 /* Result is in primary register */
2353 lval->Flags = E_MEXPR;
2354 lval->Test &= ~E_CC;
2360 /* Right hand side is not constant. Get the rhs type. */
2363 /* Check for pointer arithmetic */
2364 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2365 /* Left is pointer, right is int, must scale rhs */
2366 g_scale (CF_INT, CheckedPSizeOf (lhst));
2367 /* Operate on pointers, result type is a pointer */
2369 } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2370 /* Left is pointer, right is pointer, must scale result */
2371 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2372 Error ("Incompatible pointer types");
2374 rscale = CheckedPSizeOf (lhst);
2376 /* Operate on pointers, result type is an integer */
2378 lval->Type = type_int;
2379 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2380 /* Integer subtraction. If the left hand side descriptor says that
2381 * the lhs is const, we have to remove this mark, since this is no
2382 * longer true, lhs is on stack instead.
2384 if (lval->Flags == E_MCONST) {
2385 lval->Flags = E_MEXPR;
2387 /* Adjust operand types */
2388 flags = typeadjust (lval, &lval2, 0);
2391 Error ("Invalid operands for binary operator `-'");
2394 /* Generate code for the sub (the & is a hack here) */
2395 g_sub (flags & ~CF_CONST, 0);
2397 /* If this was a pointer subtraction, we must scale the result */
2399 g_scale (flags, -rscale);
2402 /* Result is in primary register */
2403 lval->Flags = E_MEXPR;
2404 lval->Test &= ~E_CC;
2410 static int hie8 (ExprDesc* lval)
2411 /* Process + and - binary operators. */
2413 int k = hie9 (lval);
2414 while (CurTok.Tok == TOK_PLUS || CurTok.Tok == TOK_MINUS) {
2416 if (CurTok.Tok == TOK_PLUS) {
2429 static int hie7 (ExprDesc *lval)
2430 /* Parse << and >>. */
2432 static const GenDesc* hie7_ops [] = {
2437 return hie_internal (hie7_ops, lval, hie8, &UsedGen);
2442 static int hie6 (ExprDesc *lval)
2443 /* process greater-than type comparators */
2445 static const GenDesc* hie6_ops [] = {
2446 &GenLT, &GenLE, &GenGE, &GenGT, 0
2448 return hie_compare (hie6_ops, lval, hie7);
2453 static int hie5 (ExprDesc *lval)
2455 static const GenDesc* hie5_ops[] = {
2458 return hie_compare (hie5_ops, lval, hie6);
2463 static int hie4 (ExprDesc* lval)
2464 /* Handle & (bitwise and) */
2466 static const GenDesc* hie4_ops [] = {
2471 return hie_internal (hie4_ops, lval, hie5, &UsedGen);
2476 static int hie3 (ExprDesc *lval)
2477 /* Handle ^ (bitwise exclusive or) */
2479 static const GenDesc* hie3_ops [] = {
2484 return hie_internal (hie3_ops, lval, hie4, &UsedGen);
2489 static int hie2 (ExprDesc *lval)
2490 /* Handle | (bitwise or) */
2492 static const GenDesc* hie2_ops [] = {
2497 return hie_internal (hie2_ops, lval, hie3, &UsedGen);
2502 static int hieAndPP (ExprDesc* lval)
2503 /* Process "exp && exp" in preprocessor mode (that is, when the parser is
2504 * called recursively from the preprocessor.
2509 ConstSubExpr (hie2, lval);
2510 while (CurTok.Tok == TOK_BOOL_AND) {
2512 /* Left hand side must be an int */
2513 if (!IsClassInt (lval->Type)) {
2514 Error ("Left hand side must be of integer type");
2515 MakeConstIntExpr (lval, 1);
2522 ConstSubExpr (hie2, &lval2);
2524 /* Since we are in PP mode, all we know about is integers */
2525 if (!IsClassInt (lval2.Type)) {
2526 Error ("Right hand side must be of integer type");
2527 MakeConstIntExpr (&lval2, 1);
2530 /* Combine the two */
2531 lval->ConstVal = (lval->ConstVal && lval2.ConstVal);
2534 /* Always a rvalue */
2540 static int hieOrPP (ExprDesc *lval)
2541 /* Process "exp || exp" in preprocessor mode (that is, when the parser is
2542 * called recursively from the preprocessor.
2547 ConstSubExpr (hieAndPP, lval);
2548 while (CurTok.Tok == TOK_BOOL_OR) {
2550 /* Left hand side must be an int */
2551 if (!IsClassInt (lval->Type)) {
2552 Error ("Left hand side must be of integer type");
2553 MakeConstIntExpr (lval, 1);
2560 ConstSubExpr (hieAndPP, &lval2);
2562 /* Since we are in PP mode, all we know about is integers */
2563 if (!IsClassInt (lval2.Type)) {
2564 Error ("Right hand side must be of integer type");
2565 MakeConstIntExpr (&lval2, 1);
2568 /* Combine the two */
2569 lval->ConstVal = (lval->ConstVal || lval2.ConstVal);
2572 /* Always a rvalue */
2578 static int hieAnd (ExprDesc* lval, unsigned TrueLab, int* BoolOp)
2579 /* Process "exp && exp" */
2586 if (CurTok.Tok == TOK_BOOL_AND) {
2588 /* Tell our caller that we're evaluating a boolean */
2591 /* Get a label that we will use for false expressions */
2592 lab = GetLocalLabel ();
2594 /* If the expr hasn't set condition codes, set the force-test flag */
2595 if ((lval->Test & E_CC) == 0) {
2596 lval->Test |= E_FORCETEST;
2599 /* Load the value */
2600 exprhs (CF_FORCECHAR, k, lval);
2602 /* Generate the jump */
2603 g_falsejump (CF_NONE, lab);
2605 /* Parse more boolean and's */
2606 while (CurTok.Tok == TOK_BOOL_AND) {
2613 if ((lval2.Test & E_CC) == 0) {
2614 lval2.Test |= E_FORCETEST;
2616 exprhs (CF_FORCECHAR, k, &lval2);
2618 /* Do short circuit evaluation */
2619 if (CurTok.Tok == TOK_BOOL_AND) {
2620 g_falsejump (CF_NONE, lab);
2622 /* Last expression - will evaluate to true */
2623 g_truejump (CF_NONE, TrueLab);
2627 /* Define the false jump label here */
2628 g_defcodelabel (lab);
2630 /* Define the label */
2631 lval->Flags = E_MEXPR;
2632 lval->Test |= E_CC; /* Condition codes are set */
2640 static int hieOr (ExprDesc *lval)
2641 /* Process "exp || exp". */
2645 int BoolOp = 0; /* Did we have a boolean op? */
2646 int AndOp; /* Did we have a && operation? */
2647 unsigned TrueLab; /* Jump to this label if true */
2651 TrueLab = GetLocalLabel ();
2653 /* Call the next level parser */
2654 k = hieAnd (lval, TrueLab, &BoolOp);
2656 /* Any boolean or's? */
2657 if (CurTok.Tok == TOK_BOOL_OR) {
2659 /* If the expr hasn't set condition codes, set the force-test flag */
2660 if ((lval->Test & E_CC) == 0) {
2661 lval->Test |= E_FORCETEST;
2664 /* Get first expr */
2665 exprhs (CF_FORCECHAR, k, lval);
2667 /* For each expression jump to TrueLab if true. Beware: If we
2668 * had && operators, the jump is already in place!
2671 g_truejump (CF_NONE, TrueLab);
2674 /* Remember that we had a boolean op */
2677 /* while there's more expr */
2678 while (CurTok.Tok == TOK_BOOL_OR) {
2685 k = hieAnd (&lval2, TrueLab, &AndOp);
2686 if ((lval2.Test & E_CC) == 0) {
2687 lval2.Test |= E_FORCETEST;
2689 exprhs (CF_FORCECHAR, k, &lval2);
2691 /* If there is more to come, add shortcut boolean eval. */
2692 g_truejump (CF_NONE, TrueLab);
2695 lval->Flags = E_MEXPR;
2696 lval->Test |= E_CC; /* Condition codes are set */
2700 /* If we really had boolean ops, generate the end sequence */
2702 DoneLab = GetLocalLabel ();
2703 g_getimmed (CF_INT | CF_CONST, 0, 0); /* Load FALSE */
2704 g_falsejump (CF_NONE, DoneLab);
2705 g_defcodelabel (TrueLab);
2706 g_getimmed (CF_INT | CF_CONST, 1, 0); /* Load TRUE */
2707 g_defcodelabel (DoneLab);
2714 static int hieQuest (ExprDesc *lval)
2715 /* Parse "lvalue ? exp : exp" */
2720 ExprDesc lval2; /* Expression 2 */
2721 ExprDesc lval3; /* Expression 3 */
2722 type* type2; /* Type of expression 2 */
2723 type* type3; /* Type of expression 3 */
2724 type* rtype; /* Type of result */
2725 CodeMark Mark1; /* Save position in output code */
2726 CodeMark Mark2; /* Save position in output code */
2730 k = Preprocessing? hieOrPP (lval) : hieOr (lval);
2731 if (CurTok.Tok == TOK_QUEST) {
2733 if ((lval->Test & E_CC) == 0) {
2734 /* Condition codes not set, force a test */
2735 lval->Test |= E_FORCETEST;
2737 exprhs (CF_NONE, k, lval);
2738 labf = GetLocalLabel ();
2739 g_falsejump (CF_NONE, labf);
2741 /* Parse second expression */
2742 k = expr (hie1, &lval2);
2744 if (!IsTypeVoid (lval2.Type)) {
2745 /* Load it into the primary */
2746 exprhs (CF_NONE, k, &lval2);
2748 labt = GetLocalLabel ();
2752 /* Parse the third expression */
2753 g_defcodelabel (labf);
2754 k = expr (hie1, &lval3);
2756 if (!IsTypeVoid (lval3.Type)) {
2757 /* Load it into the primary */
2758 exprhs (CF_NONE, k, &lval2);
2761 /* Check if any conversions are needed, if so, do them.
2762 * Conversion rules for ?: expression are:
2763 * - if both expressions are int expressions, default promotion
2764 * rules for ints apply.
2765 * - if both expressions are pointers of the same type, the
2766 * result of the expression is of this type.
2767 * - if one of the expressions is a pointer and the other is
2768 * a zero constant, the resulting type is that of the pointer
2770 * - if both expressions are void expressions, the result is of
2772 * - all other cases are flagged by an error.
2774 if (IsClassInt (type2) && IsClassInt (type3)) {
2776 /* Get common type */
2777 rtype = promoteint (type2, type3);
2779 /* Convert the third expression to this type if needed */
2780 g_typecast (TypeOf (rtype), TypeOf (type3));
2782 /* Setup a new label so that the expr3 code will jump around
2783 * the type cast code for expr2.
2785 labf = GetLocalLabel (); /* Get new label */
2786 Mark1 = GetCodePos (); /* Remember current position */
2787 g_jump (labf); /* Jump around code */
2789 /* The jump for expr2 goes here */
2790 g_defcodelabel (labt);
2792 /* Create the typecast code for expr2 */
2793 Mark2 = GetCodePos (); /* Remember position */
2794 g_typecast (TypeOf (rtype), TypeOf (type2));
2796 /* Jump here around the typecase code. */
2797 g_defcodelabel (labf);
2798 labt = 0; /* Mark other label as invalid */
2800 } else if (IsClassPtr (type2) && IsClassPtr (type3)) {
2801 /* Must point to same type */
2802 if (TypeCmp (Indirect (type2), Indirect (type3)) < TC_EQUAL) {
2803 Error ("Incompatible pointer types");
2805 /* Result has the common type */
2807 } else if (IsClassPtr (type2) && IsNullPtr (&lval3)) {
2808 /* Result type is pointer, no cast needed */
2810 } else if (IsNullPtr (&lval2) && IsClassPtr (type3)) {
2811 /* Result type is pointer, no cast needed */
2813 } else if (IsTypeVoid (type2) && IsTypeVoid (type3)) {
2814 /* Result type is void */
2817 Error ("Incompatible types");
2818 rtype = lval2.Type; /* Doesn't matter here */
2821 /* If we don't have the label defined until now, do it */
2823 g_defcodelabel (labt);
2826 /* Setup the target expression */
2827 lval->Flags = E_MEXPR;
2836 static void opeq (const GenDesc* Gen, ExprDesc *lval, int k)
2837 /* Process "op=" operators. */
2846 Error ("Invalid lvalue in assignment");
2850 /* Determine the type of the lhs */
2851 flags = TypeOf (lval->Type);
2852 MustScale = (Gen->Func == g_add || Gen->Func == g_sub) &&
2853 lval->Type [0] == T_PTR;
2855 /* Get the lhs address on stack (if needed) */
2858 /* Fetch the lhs into the primary register if needed */
2859 exprhs (CF_NONE, k, lval);
2861 /* Bring the lhs on stack */
2862 Mark = GetCodePos ();
2865 /* Evaluate the rhs */
2866 if (evalexpr (CF_NONE, hie1, &lval2) == 0) {
2867 /* The resulting value is a constant. If the generator has the NOPUSH
2868 * flag set, don't push the lhs.
2870 if (Gen->Flags & GEN_NOPUSH) {
2875 /* lhs is a pointer, scale rhs */
2876 lval2.ConstVal *= CheckedSizeOf (lval->Type+1);
2879 /* If the lhs is character sized, the operation may be later done
2882 if (CheckedSizeOf (lval->Type) == 1) {
2883 flags |= CF_FORCECHAR;
2886 /* Special handling for add and sub - some sort of a hack, but short code */
2887 if (Gen->Func == g_add) {
2888 g_inc (flags | CF_CONST, lval2.ConstVal);
2889 } else if (Gen->Func == g_sub) {
2890 g_dec (flags | CF_CONST, lval2.ConstVal);
2892 Gen->Func (flags | CF_CONST, lval2.ConstVal);
2895 /* rhs is not constant and already in the primary register */
2897 /* lhs is a pointer, scale rhs */
2898 g_scale (TypeOf (lval2.Type), CheckedSizeOf (lval->Type+1));
2901 /* If the lhs is character sized, the operation may be later done
2904 if (CheckedSizeOf (lval->Type) == 1) {
2905 flags |= CF_FORCECHAR;
2908 /* Adjust the types of the operands if needed */
2909 Gen->Func (g_typeadjust (flags, TypeOf (lval2.Type)), 0);
2912 lval->Flags = E_MEXPR;
2917 static void addsubeq (const GenDesc* Gen, ExprDesc *lval, int k)
2918 /* Process the += and -= operators */
2926 /* We must have an lvalue */
2928 Error ("Invalid lvalue in assignment");
2932 /* We're currently only able to handle some adressing modes */
2933 if ((lval->Flags & E_MGLOBAL) == 0 && /* Global address? */
2934 (lval->Flags & E_MLOCAL) == 0 && /* Local address? */
2935 (lval->Flags & E_MCONST) == 0) { /* Constant address? */
2936 /* Use generic routine */
2937 opeq (Gen, lval, k);
2941 /* Skip the operator */
2944 /* Check if we have a pointer expression and must scale rhs */
2945 MustScale = (lval->Type [0] == T_PTR);
2947 /* Initialize the code generator flags */
2951 /* Evaluate the rhs */
2952 if (evalexpr (CF_NONE, hie1, &lval2) == 0) {
2953 /* The resulting value is a constant. */
2955 /* lhs is a pointer, scale rhs */
2956 lval2.ConstVal *= CheckedSizeOf (lval->Type+1);
2961 /* rhs is not constant and already in the primary register */
2963 /* lhs is a pointer, scale rhs */
2964 g_scale (TypeOf (lval2.Type), CheckedSizeOf (lval->Type+1));
2968 /* Setup the code generator flags */
2969 lflags |= TypeOf (lval->Type) | CF_FORCECHAR;
2970 rflags |= TypeOf (lval2.Type);
2972 /* Cast the rhs to the type of the lhs */
2973 g_typecast (lflags, rflags);
2975 /* Output apropriate code */
2976 if (lval->Flags & E_MGLOBAL) {
2977 /* Static variable */
2978 lflags |= GlobalModeFlags (lval->Flags);
2979 if (Gen->Tok == TOK_PLUS_ASSIGN) {
2980 g_addeqstatic (lflags, lval->Name, lval->ConstVal, lval2.ConstVal);
2982 g_subeqstatic (lflags, lval->Name, lval->ConstVal, lval2.ConstVal);
2984 } else if (lval->Flags & E_MLOCAL) {
2985 /* ref to localvar */
2986 if (Gen->Tok == TOK_PLUS_ASSIGN) {
2987 g_addeqlocal (lflags, lval->ConstVal, lval2.ConstVal);
2989 g_subeqlocal (lflags, lval->ConstVal, lval2.ConstVal);
2991 } else if (lval->Flags & E_MCONST) {
2992 /* ref to absolute address */
2993 lflags |= CF_ABSOLUTE;
2994 if (Gen->Tok == TOK_PLUS_ASSIGN) {
2995 g_addeqstatic (lflags, lval->ConstVal, 0, lval2.ConstVal);
2997 g_subeqstatic (lflags, lval->ConstVal, 0, lval2.ConstVal);
2999 } else if (lval->Flags & E_MEXPR) {
3000 /* Address in a/x. */
3001 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3002 g_addeqind (lflags, lval->ConstVal, lval2.ConstVal);
3004 g_subeqind (lflags, lval->ConstVal, lval2.ConstVal);
3007 Internal ("Invalid addressing mode");
3010 /* Expression is in the primary now */
3011 lval->Flags = E_MEXPR;
3016 static void Assignment (ExprDesc* lval)
3017 /* Parse an assignment */
3022 type* ltype = lval->Type;
3024 /* Check for assignment to const */
3025 if (IsQualConst (ltype)) {
3026 Error ("Assignment to const");
3029 /* cc65 does not have full support for handling structs by value. Since
3030 * assigning structs is one of the more useful operations from this
3031 * family, allow it here.
3033 if (IsClassStruct (ltype)) {
3035 /* Bring the address of the lhs into the primary and push it */
3036 exprhs (0, 0, lval);
3037 g_push (CF_PTR | CF_UNSIGNED, 0);
3039 /* Get the expression on the right of the '=' into the primary */
3042 /* Get the address */
3043 exprhs (0, 0, &lval2);
3046 /* Push the address (or whatever is in ax in case of errors) */
3047 g_push (CF_PTR | CF_UNSIGNED, 0);
3049 /* Check for equality of the structs */
3050 if (TypeCmp (ltype, lval2.Type) < TC_STRICT_COMPATIBLE) {
3051 Error ("Incompatible types");
3054 /* Load the size of the struct into the primary */
3055 g_getimmed (CF_INT | CF_UNSIGNED | CF_CONST, CheckedSizeOf (ltype), 0);
3057 /* Call the memcpy function */
3058 g_call (CF_FIXARGC, "memcpy", 4);
3062 /* Get the address on stack if needed */
3065 /* No struct, setup flags for the load */
3067 /* Generates wrong code!!! ### */
3068 flags = CheckedSizeOf (ltype) == 1? CF_FORCECHAR : CF_NONE;
3073 /* Get the expression on the right of the '=' into the primary */
3074 if (evalexpr (flags, hie1, &lval2) == 0) {
3075 /* Constant expression. Adjust the types */
3076 assignadjust (ltype, &lval2);
3077 /* Put the value into the primary register */
3078 lconst (flags, &lval2);
3080 /* Expression is not constant and already in the primary */
3081 assignadjust (ltype, &lval2);
3084 /* Generate a store instruction */
3089 /* Value is still in primary */
3090 lval->Flags = E_MEXPR;
3095 int hie1 (ExprDesc* lval)
3096 /* Parse first level of expression hierarchy. */
3100 k = hieQuest (lval);
3101 switch (CurTok.Tok) {
3110 Error ("Invalid lvalue in assignment");
3116 case TOK_PLUS_ASSIGN:
3117 addsubeq (&GenPASGN, lval, k);
3120 case TOK_MINUS_ASSIGN:
3121 addsubeq (&GenSASGN, lval, k);
3124 case TOK_MUL_ASSIGN:
3125 opeq (&GenMASGN, lval, k);
3128 case TOK_DIV_ASSIGN:
3129 opeq (&GenDASGN, lval, k);
3132 case TOK_MOD_ASSIGN:
3133 opeq (&GenMOASGN, lval, k);
3136 case TOK_SHL_ASSIGN:
3137 opeq (&GenSLASGN, lval, k);
3140 case TOK_SHR_ASSIGN:
3141 opeq (&GenSRASGN, lval, k);
3144 case TOK_AND_ASSIGN:
3145 opeq (&GenAASGN, lval, k);
3148 case TOK_XOR_ASSIGN:
3149 opeq (&GenXOASGN, lval, k);
3153 opeq (&GenOASGN, lval, k);
3164 int hie0 (ExprDesc *lval)
3165 /* Parse comma operator. */
3170 while (CurTok.Tok == TOK_COMMA) {
3179 int evalexpr (unsigned flags, int (*f) (ExprDesc*), ExprDesc* lval)
3180 /* Will evaluate an expression via the given function. If the result is a
3181 * constant, 0 is returned and the value is put in the lval struct. If the
3182 * result is not constant, exprhs is called to bring the value into the
3183 * primary register and 1 is returned.
3190 if (k == 0 && lval->Flags == E_MCONST) {
3191 /* Constant expression */
3194 /* Not constant, load into the primary */
3195 exprhs (flags, k, lval);
3202 static int expr (int (*func) (ExprDesc*), ExprDesc *lval)
3203 /* Expression parser; func is either hie0 or hie1. */
3212 /* Do some checks if code generation is still constistent */
3213 if (savsp != oursp) {
3215 fprintf (stderr, "oursp != savesp (%d != %d)\n", oursp, savsp);
3217 Internal ("oursp != savsp (%d != %d)", oursp, savsp);
3225 void expression1 (ExprDesc* lval)
3226 /* Evaluate an expression on level 1 (no comma operator) and put it into
3227 * the primary register
3230 memset (lval, 0, sizeof (*lval));
3231 exprhs (CF_NONE, expr (hie1, lval), lval);
3236 void expression (ExprDesc* lval)
3237 /* Evaluate an expression and put it into the primary register */
3239 memset (lval, 0, sizeof (*lval));
3240 exprhs (CF_NONE, expr (hie0, lval), lval);
3245 void ConstExpr (ExprDesc* lval)
3246 /* Get a constant value */
3248 memset (lval, 0, sizeof (*lval));
3249 if (expr (hie1, lval) != 0 || (lval->Flags & E_MCONST) == 0) {
3250 Error ("Constant expression expected");
3251 /* To avoid any compiler errors, make the expression a valid const */
3252 MakeConstIntExpr (lval, 1);
3258 void ConstIntExpr (ExprDesc* Val)
3259 /* Get a constant int value */
3261 memset (Val, 0, sizeof (*Val));
3262 if (expr (hie1, Val) != 0 ||
3263 (Val->Flags & E_MCONST) == 0 ||
3264 !IsClassInt (Val->Type)) {
3265 Error ("Constant integer expression expected");
3266 /* To avoid any compiler errors, make the expression a valid const */
3267 MakeConstIntExpr (Val, 1);
3273 void intexpr (ExprDesc* lval)
3274 /* Get an integer expression */
3277 if (!IsClassInt (lval->Type)) {
3278 Error ("Integer expression expected");
3279 /* To avoid any compiler errors, make the expression a valid int */
3280 MakeConstIntExpr (lval, 1);
3286 void boolexpr (ExprDesc* lval)
3287 /* Get a boolean expression */
3289 /* Read an expression */
3292 /* If it's an integer, it's ok. If it's not an integer, but a pointer,
3293 * the pointer used in a boolean context is also ok
3295 if (!IsClassInt (lval->Type) && !IsClassPtr (lval->Type)) {
3296 Error ("Boolean expression expected");
3297 /* To avoid any compiler errors, make the expression a valid int */
3298 MakeConstIntExpr (lval, 1);
3304 void test (unsigned label, int cond)
3305 /* Generate code to perform test and jump if false. */
3310 /* Eat the parenthesis */
3313 /* Prepare the expression, setup labels */
3314 memset (&lval, 0, sizeof (lval));
3316 /* Generate code to eval the expr */
3317 k = expr (hie0, &lval);
3318 if (k == 0 && lval.Flags == E_MCONST) {
3319 /* Constant rvalue */
3320 if (cond == 0 && lval.ConstVal == 0) {
3322 Warning ("Unreachable code");
3323 } else if (cond && lval.ConstVal) {
3330 /* If the expr hasn't set condition codes, set the force-test flag */
3331 if ((lval.Test & E_CC) == 0) {
3332 lval.Test |= E_FORCETEST;
3335 /* Load the value into the primary register */
3336 exprhs (CF_FORCECHAR, k, &lval);
3338 /* Generate the jump */
3340 g_truejump (CF_NONE, label);
3342 /* Special case (putting this here is a small hack - but hey, the
3343 * compiler itself is one big hack...): If a semicolon follows, we
3344 * don't have a statement and may omit the jump.
3346 if (CurTok.Tok != TOK_SEMI) {
3347 g_falsejump (CF_NONE, label);
3351 /* Check for the closing brace */