3 * Ullrich von Bassewitz, 21.06.1998
13 #include "debugflag.h"
20 #include "assignment.h"
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 GenPASGN = { TOK_PLUS_ASSIGN, GEN_NOPUSH, g_add };
57 static GenDesc GenSASGN = { TOK_MINUS_ASSIGN, GEN_NOPUSH, g_sub };
58 static GenDesc GenMASGN = { TOK_MUL_ASSIGN, GEN_NOPUSH, g_mul };
59 static GenDesc GenDASGN = { TOK_DIV_ASSIGN, GEN_NOPUSH, g_div };
60 static GenDesc GenMOASGN = { TOK_MOD_ASSIGN, GEN_NOPUSH, g_mod };
61 static GenDesc GenSLASGN = { TOK_SHL_ASSIGN, GEN_NOPUSH, g_asl };
62 static GenDesc GenSRASGN = { TOK_SHR_ASSIGN, GEN_NOPUSH, g_asr };
63 static GenDesc GenAASGN = { TOK_AND_ASSIGN, GEN_NOPUSH, g_and };
64 static GenDesc GenXOASGN = { TOK_XOR_ASSIGN, GEN_NOPUSH, g_xor };
65 static GenDesc GenOASGN = { TOK_OR_ASSIGN, GEN_NOPUSH, g_or };
69 /*****************************************************************************/
70 /* Function forwards */
71 /*****************************************************************************/
75 void hie0 (ExprDesc *lval);
76 /* Parse comma operator. */
80 /*****************************************************************************/
81 /* Helper functions */
82 /*****************************************************************************/
86 static unsigned GlobalModeFlags (unsigned Flags)
87 /* Return the addressing mode flags for the variable with the given flags */
89 switch (Flags & E_MASK_LOC) {
90 case E_LOC_GLOBAL: return CF_EXTERNAL;
91 case E_LOC_STATIC: return CF_STATIC;
92 case E_LOC_REGISTER: return CF_REGVAR;
94 Internal ("GlobalModeFlags: Invalid flags value: %u", Flags);
100 static void ExprWithCheck (void (*Func) (ExprDesc*), ExprDesc *Expr)
101 /* Call an expression function with checks. */
103 /* Remember the stack pointer */
104 int OldSP = StackPtr;
106 /* Call the expression function */
109 /* Do some checks if code generation is still constistent */
110 if (StackPtr != OldSP) {
113 "Code generation messed up!\n"
114 "StackPtr is %d, should be %d",
117 Internal ("StackPtr is %d, should be %d\n", StackPtr, OldSP);
124 static type* promoteint (type* lhst, type* rhst)
125 /* In an expression with two ints, return the type of the result */
127 /* Rules for integer types:
128 * - If one of the values is a long, the result is long.
129 * - If one of the values is unsigned, the result is also unsigned.
130 * - Otherwise the result is an int.
132 if (IsTypeLong (lhst) || IsTypeLong (rhst)) {
133 if (IsSignUnsigned (lhst) || IsSignUnsigned (rhst)) {
139 if (IsSignUnsigned (lhst) || IsSignUnsigned (rhst)) {
149 static unsigned typeadjust (ExprDesc* lhs, ExprDesc* rhs, int NoPush)
150 /* Adjust the two values for a binary operation. lhs is expected on stack or
151 * to be constant, rhs is expected to be in the primary register or constant.
152 * The function will put the type of the result into lhs and return the
153 * code generator flags for the operation.
154 * If NoPush is given, it is assumed that the operation does not expect the lhs
155 * to be on stack, and that lhs is in a register instead.
156 * Beware: The function does only accept int types.
159 unsigned ltype, rtype;
162 /* Get the type strings */
163 type* lhst = lhs->Type;
164 type* rhst = rhs->Type;
166 /* Generate type adjustment code if needed */
167 ltype = TypeOf (lhst);
168 if (ED_IsLocAbs (lhs)) {
172 /* Value is in primary register*/
175 rtype = TypeOf (rhst);
176 if (ED_IsLocAbs (rhs)) {
179 flags = g_typeadjust (ltype, rtype);
181 /* Set the type of the result */
182 lhs->Type = promoteint (lhst, rhst);
184 /* Return the code generator flags */
190 void DefineData (ExprDesc* Expr)
191 /* Output a data definition for the given expression */
193 switch (ED_GetLoc (Expr)) {
196 /* Absolute: numeric address or const */
197 g_defdata (TypeOf (Expr->Type) | CF_CONST, Expr->Val, 0);
201 /* Global variable */
202 g_defdata (CF_EXTERNAL, Expr->Name, Expr->Val);
206 /* Static variable */
207 g_defdata (CF_STATIC, Expr->Name, Expr->Val);
211 /* Register variable. Taking the address is usually not
214 if (IS_Get (&AllowRegVarAddr) == 0) {
215 Error ("Cannot take the address of a register variable");
217 g_defdata (CF_REGVAR, Expr->Name, Expr->Val);
221 /* Literal in the literal pool */
222 g_defdata (CF_STATIC, LiteralPoolLabel, Expr->Val);
226 Internal ("Unknown constant type: 0x%04X", ED_GetLoc (Expr));
232 static void LoadConstant (unsigned Flags, ExprDesc* Expr)
233 /* Load the primary register with some constant value. */
235 switch (ED_GetLoc (Expr)) {
238 /* Number constant */
239 g_getimmed (Flags | TypeOf (Expr->Type) | CF_CONST, Expr->Val, 0);
243 /* Global symbol, load address */
244 g_getimmed ((Flags | CF_EXTERNAL) & ~CF_CONST, Expr->Name, Expr->Val);
248 /* Static symbol, load address */
249 g_getimmed ((Flags | CF_STATIC) & ~CF_CONST, Expr->Name, Expr->Val);
253 /* Register variable. Taking the address is usually not
256 if (IS_Get (&AllowRegVarAddr) == 0) {
257 Error ("Cannot take the address of a register variable");
259 g_getimmed ((Flags | CF_REGVAR) & ~CF_CONST, Expr->Name, Expr->Val);
267 g_getimmed (CF_STATIC, LiteralPoolLabel, Expr->Val);
271 Internal ("Unknown constant type: %04X", Expr->Flags);
277 static int kcalc (token_t tok, long val1, long val2)
278 /* Calculate an operation with left and right operand constant. */
282 return (val1 == val2);
284 return (val1 != val2);
286 return (val1 < val2);
288 return (val1 <= val2);
290 return (val1 >= val2);
292 return (val1 > val2);
294 return (val1 | val2);
296 return (val1 ^ val2);
298 return (val1 & val2);
300 return (val1 >> val2);
302 return (val1 << val2);
304 return (val1 * val2);
307 Error ("Division by zero");
310 return (val1 / val2);
313 Error ("Modulo operation with zero");
316 return (val1 % val2);
318 Internal ("kcalc: got token 0x%X\n", tok);
325 static const GenDesc* FindGen (token_t Tok, const GenDesc* Table)
326 /* Find a token in a generator table */
328 while (Table->Tok != TOK_INVALID) {
329 if (Table->Tok == Tok) {
339 static int TypeSpecAhead (void)
340 /* Return true if some sort of type is waiting (helper for cast and sizeof()
346 /* There's a type waiting if:
348 * We have an opening paren, and
349 * a. the next token is a type, or
350 * b. the next token is a type qualifier, or
351 * c. the next token is a typedef'd type
353 return CurTok.Tok == TOK_LPAREN && (
354 TokIsType (&NextTok) ||
355 TokIsTypeQual (&NextTok) ||
356 (NextTok.Tok == TOK_IDENT &&
357 (Entry = FindSym (NextTok.Ident)) != 0 &&
358 SymIsTypeDef (Entry)));
363 void PushAddr (const ExprDesc* Expr)
364 /* If the expression contains an address that was somehow evaluated,
365 * push this address on the stack. This is a helper function for all
366 * sorts of implicit or explicit assignment functions where the lvalue
367 * must be saved if it's not constant, before evaluating the rhs.
370 /* Get the address on stack if needed */
371 if (ED_IsLocExpr (Expr)) {
372 /* Push the address (always a pointer) */
379 /*****************************************************************************/
381 /*****************************************************************************/
385 void ExprLoad (unsigned Flags, ExprDesc* Expr)
386 /* Place the result of an expression into the primary register if it is not
390 if (ED_IsLVal (Expr)) {
392 /* Dereferenced lvalue */
393 Flags |= TypeOf (Expr->Type);
394 if (Expr->Test & E_FORCETEST) {
396 Expr->Test &= ~E_FORCETEST;
399 switch (ED_GetLoc (Expr)) {
402 /* Absolute: numeric address or const */
403 g_getstatic (Flags | CF_ABSOLUTE, Expr->Val, 0);
407 /* Global variable */
408 g_getstatic (Flags | CF_EXTERNAL, Expr->Name, Expr->Val);
412 /* Static variable */
413 g_getstatic (Flags | CF_STATIC, Expr->Name, Expr->Val);
417 /* Register variable */
418 g_getstatic (Flags | CF_REGVAR, Expr->Name, Expr->Val);
422 /* Value on the stack */
423 g_getlocal (Flags, Expr->Val);
427 /* The primary register - just test if necessary */
428 if (Flags & CF_TEST) {
434 /* Reference to address in primary with offset in Expr */
435 g_getind (Flags, Expr->Val);
439 /* Literal in the literal pool */
440 g_getstatic (Flags | CF_STATIC, LiteralPoolLabel, Expr->Val);
444 Internal ("Invalid location in ExprLoad: 0x%04X", ED_GetLoc (Expr));
449 if (ED_IsLocExpr (Expr)) {
450 if (Expr->Val != 0) {
451 /* We have an expression in the primary plus a constant
452 * offset. Adjust the value in the primary accordingly.
454 Flags |= TypeOf (Expr->Type);
455 g_inc (Flags | CF_CONST, Expr->Val);
458 /* Constant of some sort, load it into the primary */
459 LoadConstant (Flags, Expr);
462 /* Are we testing this value? */
463 if (Expr->Test & E_FORCETEST) {
464 /* Yes, force a test */
465 Flags |= TypeOf (Expr->Type);
467 Expr->Test &= ~E_FORCETEST;
472 /* Regardless of the original contents, Expr is now an rvalue in the
473 * primary. ### Later...
475 ED_MakeRValExpr (Expr);
481 static unsigned FunctionParamList (FuncDesc* Func)
482 /* Parse a function parameter list and pass the parameters to the called
483 * function. Depending on several criteria this may be done by just pushing
484 * each parameter separately, or creating the parameter frame once and then
485 * storing into this frame.
486 * The function returns the size of the parameters pushed.
491 /* Initialize variables */
492 SymEntry* Param = 0; /* Keep gcc silent */
493 unsigned ParamSize = 0; /* Size of parameters pushed */
494 unsigned ParamCount = 0; /* Number of parameters pushed */
495 unsigned FrameSize = 0; /* Size of parameter frame */
496 unsigned FrameParams = 0; /* Number of params in frame */
497 int FrameOffs = 0; /* Offset into parameter frame */
498 int Ellipsis = 0; /* Function is variadic */
500 /* As an optimization, we may allocate the complete parameter frame at
501 * once instead of pushing each parameter as it comes. We may do that,
504 * - optimizations that increase code size are enabled (allocating the
505 * stack frame at once gives usually larger code).
506 * - we have more than one parameter to push (don't count the last param
507 * for __fastcall__ functions).
509 * The FrameSize variable will contain a value > 0 if storing into a frame
510 * (instead of pushing) is enabled.
513 if (CodeSizeFactor >= 200) {
515 /* Calculate the number and size of the parameters */
516 FrameParams = Func->ParamCount;
517 FrameSize = Func->ParamSize;
518 if (FrameParams > 0 && (Func->Flags & FD_FASTCALL) != 0) {
519 /* Last parameter is not pushed */
520 FrameSize -= CheckedSizeOf (Func->LastParam->Type);
524 /* Do we have more than one parameter in the frame? */
525 if (FrameParams > 1) {
526 /* Okeydokey, setup the frame */
527 FrameOffs = StackPtr;
529 StackPtr -= FrameSize;
531 /* Don't use a preallocated frame */
536 /* Parse the actual parameter list */
537 while (CurTok.Tok != TOK_RPAREN) {
541 /* Count arguments */
544 /* Fetch the pointer to the next argument, check for too many args */
545 if (ParamCount <= Func->ParamCount) {
546 /* Beware: If there are parameters with identical names, they
547 * cannot go into the same symbol table, which means that in this
548 * case of errorneous input, the number of nodes in the symbol
549 * table and ParamCount are NOT equal. We have to handle this case
550 * below to avoid segmentation violations. Since we know that this
551 * problem can only occur if there is more than one parameter,
552 * we will just use the last one.
554 if (ParamCount == 1) {
556 Param = Func->SymTab->SymHead;
557 } else if (Param->NextSym != 0) {
559 Param = Param->NextSym;
560 CHECK ((Param->Flags & SC_PARAM) != 0);
562 } else if (!Ellipsis) {
563 /* Too many arguments. Do we have an open param list? */
564 if ((Func->Flags & FD_VARIADIC) == 0) {
565 /* End of param list reached, no ellipsis */
566 Error ("Too many arguments in function call");
568 /* Assume an ellipsis even in case of errors to avoid an error
569 * message for each other argument.
574 /* Evaluate the parameter expression */
577 /* If we don't have an argument spec, accept anything, otherwise
578 * convert the actual argument to the type needed.
582 /* Convert the argument to the parameter type if needed */
583 TypeConversion (&Expr, Param->Type);
585 /* If we have a prototype, chars may be pushed as chars */
586 Flags |= CF_FORCECHAR;
589 /* Load the value into the primary if it is not already there */
590 ExprLoad (Flags, &Expr);
592 /* Use the type of the argument for the push */
593 Flags |= TypeOf (Expr.Type);
595 /* If this is a fastcall function, don't push the last argument */
596 if (ParamCount != Func->ParamCount || (Func->Flags & FD_FASTCALL) == 0) {
597 unsigned ArgSize = sizeofarg (Flags);
599 /* We have the space already allocated, store in the frame.
600 * Because of invalid type conversions (that have produced an
601 * error before), we can end up here with a non aligned stack
602 * frame. Since no output will be generated anyway, handle
603 * these cases gracefully instead of doing a CHECK.
605 if (FrameSize >= ArgSize) {
606 FrameSize -= ArgSize;
610 FrameOffs -= ArgSize;
612 g_putlocal (Flags | CF_NOKEEP, FrameOffs, Expr.Val);
614 /* Push the argument */
615 g_push (Flags, Expr.Val);
618 /* Calculate total parameter size */
619 ParamSize += ArgSize;
622 /* Check for end of argument list */
623 if (CurTok.Tok != TOK_COMMA) {
629 /* Check if we had enough parameters */
630 if (ParamCount < Func->ParamCount) {
631 Error ("Too few arguments in function call");
634 /* The function returns the size of all parameters pushed onto the stack.
635 * However, if there are parameters missing (which is an error and was
636 * flagged by the compiler) AND a stack frame was preallocated above,
637 * we would loose track of the stackpointer and generate an internal error
638 * later. So we correct the value by the parameters that should have been
639 * pushed to avoid an internal compiler error. Since an error was
640 * generated before, no code will be output anyway.
642 return ParamSize + FrameSize;
647 static void FunctionCall (ExprDesc* Expr)
648 /* Perform a function call. */
650 FuncDesc* Func; /* Function descriptor */
651 int IsFuncPtr; /* Flag */
652 unsigned ParamSize; /* Number of parameter bytes */
653 CodeMark Mark = 0; /* Initialize to keep gcc silent */
654 int PtrOffs = 0; /* Offset of function pointer on stack */
655 int IsFastCall = 0; /* True if it's a fast call function */
656 int PtrOnStack = 0; /* True if a pointer copy is on stack */
658 /* Skip the left paren */
661 /* Get a pointer to the function descriptor from the type string */
662 Func = GetFuncDesc (Expr->Type);
664 /* Handle function pointers transparently */
665 IsFuncPtr = IsTypeFuncPtr (Expr->Type);
668 /* Check wether it's a fastcall function that has parameters */
669 IsFastCall = IsFastCallFunc (Expr->Type + 1) && (Func->ParamCount > 0);
671 /* Things may be difficult, depending on where the function pointer
672 * resides. If the function pointer is an expression of some sort
673 * (not a local or global variable), we have to evaluate this
674 * expression now and save the result for later. Since calls to
675 * function pointers may be nested, we must save it onto the stack.
676 * For fastcall functions we do also need to place a copy of the
677 * pointer on stack, since we cannot use a/x.
679 PtrOnStack = IsFastCall || !ED_IsConst (Expr);
682 /* Not a global or local variable, or a fastcall function. Load
683 * the pointer into the primary and mark it as an expression.
685 ExprLoad (CF_NONE, Expr);
686 ED_MakeRValExpr (Expr);
688 /* Remember the code position */
689 Mark = GetCodePos ();
691 /* Push the pointer onto the stack and remember the offset */
696 /* Check for known standard functions and inline them if requested */
697 } else if (IS_Get (&InlineStdFuncs) && IsStdFunc ((const char*) Expr->Name)) {
699 /* Inline this function */
700 HandleStdFunc (Func, Expr);
705 /* Parse the parameter list */
706 ParamSize = FunctionParamList (Func);
708 /* We need the closing paren here */
711 /* Special handling for function pointers */
714 /* If the function is not a fastcall function, load the pointer to
715 * the function into the primary.
719 /* Not a fastcall function - we may use the primary */
721 /* If we have no parameters, the pointer is still in the
722 * primary. Remove the code to push it and correct the
725 if (ParamSize == 0) {
730 /* Load from the saved copy */
731 g_getlocal (CF_PTR, PtrOffs);
734 /* Load from original location */
735 ExprLoad (CF_NONE, Expr);
738 /* Call the function */
739 g_callind (TypeOf (Expr->Type+1), ParamSize, PtrOffs);
743 /* Fastcall function. We cannot use the primary for the function
744 * pointer and must therefore use an offset to the stack location.
745 * Since fastcall functions may never be variadic, we can use the
746 * index register for this purpose.
748 g_callind (CF_LOCAL, ParamSize, PtrOffs);
751 /* If we have a pointer on stack, remove it */
753 g_space (- (int) sizeofarg (CF_PTR));
762 /* Normal function */
763 g_call (TypeOf (Expr->Type), (const char*) Expr->Name, ParamSize);
768 /* The function result is an rvalue in the primary register */
769 ED_MakeRValExpr (Expr);
770 Expr->Type = GetFuncReturn (Expr->Type);
775 static void Primary (ExprDesc* E)
776 /* This is the lowest level of the expression parser. */
780 /* Initialize fields in the expression stucture */
783 /* Character and integer constants. */
784 if (CurTok.Tok == TOK_ICONST || CurTok.Tok == TOK_CCONST) {
785 E->Flags = E_LOC_ABS | E_RTYPE_RVAL;
786 E->Type = CurTok.Type;
787 E->Val = CurTok.IVal;
792 /* Process parenthesized subexpression by calling the whole parser
795 if (CurTok.Tok == TOK_LPAREN) {
802 /* If we run into an identifier in preprocessing mode, we assume that this
803 * is an undefined macro and replace it by a constant value of zero.
805 if (Preprocessing && CurTok.Tok == TOK_IDENT) {
806 ED_MakeConstAbsInt (E, 0);
810 /* All others may only be used if the expression evaluation is not called
811 * recursively by the preprocessor.
814 /* Illegal expression in PP mode */
815 Error ("Preprocessor expression expected");
816 ED_MakeConstAbsInt (E, 1);
820 switch (CurTok.Tok) {
823 /* Identifier. Get a pointer to the symbol table entry */
824 Sym = E->Sym = FindSym (CurTok.Ident);
826 /* Is the symbol known? */
829 /* We found the symbol - skip the name token */
832 /* Check for illegal symbol types */
833 CHECK ((Sym->Flags & SC_LABEL) != SC_LABEL);
834 if (Sym->Flags & SC_TYPE) {
835 /* Cannot use type symbols */
836 Error ("Variable identifier expected");
837 /* Assume an int type to make E valid */
838 E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
843 /* Mark the symbol as referenced */
844 Sym->Flags |= SC_REF;
846 /* The expression type is the symbol type */
849 /* Check for legal symbol types */
850 if ((Sym->Flags & SC_CONST) == SC_CONST) {
851 /* Enum or some other numeric constant */
852 E->Flags = E_LOC_ABS | E_RTYPE_RVAL;
853 E->Val = Sym->V.ConstVal;
854 } else if ((Sym->Flags & SC_FUNC) == SC_FUNC) {
856 E->Flags = E_LOC_GLOBAL | E_RTYPE_LVAL;
857 E->Name = (unsigned long) Sym->Name;
858 } else if ((Sym->Flags & SC_AUTO) == SC_AUTO) {
859 /* Local variable. If this is a parameter for a variadic
860 * function, we have to add some address calculations, and the
861 * address is not const.
863 if ((Sym->Flags & SC_PARAM) == SC_PARAM && F_IsVariadic (CurrentFunc)) {
864 /* Variadic parameter */
865 g_leavariadic (Sym->V.Offs - F_GetParamSize (CurrentFunc));
866 E->Flags = E_LOC_EXPR | E_RTYPE_LVAL;
868 /* Normal parameter */
869 E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
870 E->Val = Sym->V.Offs;
872 } else if ((Sym->Flags & SC_REGISTER) == SC_REGISTER) {
873 /* Register variable, zero page based */
874 E->Flags = E_LOC_REGISTER | E_RTYPE_LVAL;
875 E->Name = Sym->V.R.RegOffs;
876 } else if ((Sym->Flags & SC_STATIC) == SC_STATIC) {
877 /* Static variable */
878 if (Sym->Flags & (SC_EXTERN | SC_STORAGE)) {
879 E->Flags = E_LOC_GLOBAL | E_RTYPE_LVAL;
880 E->Name = (unsigned long) Sym->Name;
882 E->Flags = E_LOC_STATIC | E_RTYPE_LVAL;
883 E->Name = Sym->V.Label;
886 /* Local static variable */
887 E->Flags = E_LOC_STATIC | E_RTYPE_LVAL;
888 E->Name = Sym->V.Offs;
891 /* We've made all variables lvalues above. However, this is
892 * not always correct: An array is actually the address of its
893 * first element, which is a rvalue, and a function is a
894 * rvalue, too, because we cannot store anything in a function.
895 * So fix the flags depending on the type.
897 if (IsTypeArray (E->Type) || IsTypeFunc (E->Type)) {
903 /* We did not find the symbol. Remember the name, then skip it */
905 strcpy (Ident, CurTok.Ident);
908 /* IDENT is either an auto-declared function or an undefined variable. */
909 if (CurTok.Tok == TOK_LPAREN) {
910 /* Declare a function returning int. For that purpose, prepare a
911 * function signature for a function having an empty param list
914 Warning ("Function call without a prototype");
915 Sym = AddGlobalSym (Ident, GetImplicitFuncType(), SC_EXTERN | SC_REF | SC_FUNC);
917 E->Flags = E_LOC_GLOBAL | E_RTYPE_RVAL;
918 E->Name = (unsigned long) Sym->Name;
920 /* Undeclared Variable */
921 Sym = AddLocalSym (Ident, type_int, SC_AUTO | SC_REF, 0);
922 E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
924 Error ("Undefined symbol: `%s'", Ident);
932 E->Flags = E_LOC_LITERAL | E_RTYPE_RVAL;
933 E->Val = CurTok.IVal;
934 E->Type = GetCharArrayType (GetLiteralPoolOffs () - CurTok.IVal);
941 E->Flags = E_LOC_EXPR | E_RTYPE_RVAL;
946 /* Register pseudo variable */
947 E->Type = type_uchar;
948 E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
953 /* Register pseudo variable */
955 E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
960 /* Register pseudo variable */
961 E->Type = type_ulong;
962 E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
967 /* Illegal primary. */
968 Error ("Expression expected");
969 ED_MakeConstAbsInt (E, 1);
976 static void ArrayRef (ExprDesc* Expr)
977 /* Handle an array reference */
987 /* Skip the bracket */
990 /* Get the type of left side */
993 /* We can apply a special treatment for arrays that have a const base
994 * address. This is true for most arrays and will produce a lot better
995 * code. Check if this is a const base address.
997 ConstBaseAddr = (ED_IsLocConst (Expr) || ED_IsLocStack (Expr));
999 /* If we have a constant base, we delay the address fetch */
1000 Mark1 = GetCodePos ();
1001 Mark2 = 0; /* Silence gcc */
1002 if (!ConstBaseAddr) {
1003 /* Get a pointer to the array into the primary */
1004 ExprLoad (CF_NONE, Expr);
1006 /* Get the array pointer on stack. Do not push more than 16
1007 * bit, even if this value is greater, since we cannot handle
1008 * other than 16bit stuff when doing indexing.
1010 Mark2 = GetCodePos ();
1014 /* TOS now contains ptr to array elements. Get the subscript. */
1015 ExprWithCheck (hie0, &SubScript);
1017 /* Check the types of array and subscript. We can either have a
1018 * pointer/array to the left, in which case the subscript must be of an
1019 * integer type, or we have an integer to the left, in which case the
1020 * subscript must be a pointer/array.
1021 * Since we do the necessary checking here, we can rely later on the
1024 if (IsClassPtr (Expr->Type)) {
1025 if (!IsClassInt (SubScript.Type)) {
1026 Error ("Array subscript is not an integer");
1027 /* To avoid any compiler errors, make the expression a valid int */
1028 ED_MakeConstAbsInt (&SubScript, 0);
1030 ElementType = Indirect (Expr->Type);
1031 } else if (IsClassInt (Expr->Type)) {
1032 if (!IsClassPtr (SubScript.Type)) {
1033 Error ("Subscripted value is neither array nor pointer");
1034 /* To avoid compiler errors, make the subscript a char[] at
1037 ED_MakeConstAbs (&SubScript, 0, GetCharArrayType (1));
1039 ElementType = Indirect (SubScript.Type);
1041 Error ("Cannot subscript");
1042 /* To avoid compiler errors, fake both the array and the subscript, so
1043 * we can just proceed.
1045 ED_MakeConstAbs (Expr, 0, GetCharArrayType (1));
1046 ED_MakeConstAbsInt (&SubScript, 0);
1047 ElementType = Indirect (Expr->Type);
1050 /* Check if the subscript is constant absolute value */
1051 if (ED_IsConstAbs (&SubScript)) {
1053 /* The array subscript is a numeric constant. If we had pushed the
1054 * array base address onto the stack before, we can remove this value,
1055 * since we can generate expression+offset.
1057 if (!ConstBaseAddr) {
1061 /* Get an array pointer into the primary */
1062 ExprLoad (CF_NONE, Expr);
1065 if (IsClassPtr (Expr->Type)) {
1067 /* Lhs is pointer/array. Scale the subscript value according to
1070 SubScript.Val *= CheckedSizeOf (ElementType);
1072 /* Remove the address load code */
1075 /* In case of an array, we can adjust the offset of the expression
1076 * already in Expr. If the base address was a constant, we can even
1077 * remove the code that loaded the address into the primary.
1079 if (IsTypeArray (Expr->Type)) {
1081 /* Adjust the offset */
1082 Expr->Val += SubScript.Val;
1086 /* It's a pointer, so we do have to load it into the primary
1087 * first (if it's not already there).
1089 if (ConstBaseAddr) {
1090 ExprLoad (CF_NONE, Expr);
1091 ED_MakeRValExpr (Expr);
1094 /* Use the offset */
1095 Expr->Val = SubScript.Val;
1100 /* Scale the rhs value according to the element type */
1101 g_scale (TypeOf (tptr1), CheckedSizeOf (ElementType));
1103 /* Add the subscript. Since arrays are indexed by integers,
1104 * we will ignore the true type of the subscript here and
1105 * use always an int. #### Use offset but beware of ExprLoad!
1107 g_inc (CF_INT | CF_CONST, SubScript.Val);
1113 /* Array subscript is not constant. Load it into the primary */
1114 Mark2 = GetCodePos ();
1115 ExprLoad (CF_NONE, &SubScript);
1118 if (IsClassPtr (Expr->Type)) {
1120 /* Indexing is based on unsigneds, so we will just use the integer
1121 * portion of the index (which is in (e)ax, so there's no further
1124 g_scale (CF_INT | CF_UNSIGNED, CheckedSizeOf (ElementType));
1128 /* Get the int value on top. If we come here, we're sure, both
1129 * values are 16 bit (the first one was truncated if necessary
1130 * and the second one is a pointer). Note: If ConstBaseAddr is
1131 * true, we don't have a value on stack, so to "swap" both, just
1132 * push the subscript.
1134 if (ConstBaseAddr) {
1136 ExprLoad (CF_NONE, Expr);
1143 g_scale (TypeOf (tptr1), CheckedSizeOf (ElementType));
1147 /* The offset is now in the primary register. It we didn't have a
1148 * constant base address for the lhs, the lhs address is already
1149 * on stack, and we must add the offset. If the base address was
1150 * constant, we call special functions to add the address to the
1153 if (!ConstBaseAddr) {
1155 /* The array base address is on stack and the subscript is in the
1156 * primary. Add both.
1158 g_add (CF_INT | CF_UNSIGNED, 0);
1162 /* The subscript is in the primary, and the array base address is
1163 * in Expr. If the subscript has itself a constant address, it is
1164 * often a better idea to reverse again the order of the
1165 * evaluation. This will generate better code if the subscript is
1166 * a byte sized variable. But beware: This is only possible if the
1167 * subscript was not scaled, that is, if this was a byte array
1170 if ((ED_IsLocConst (&SubScript) || ED_IsLocStack (&SubScript)) &&
1171 CheckedSizeOf (ElementType) == SIZEOF_CHAR) {
1175 /* Reverse the order of evaluation */
1176 if (CheckedSizeOf (SubScript.Type) == SIZEOF_CHAR) {
1183 /* Get a pointer to the array into the primary. */
1184 ExprLoad (CF_NONE, Expr);
1186 /* Add the variable */
1187 if (ED_IsLocStack (&SubScript)) {
1188 g_addlocal (Flags, SubScript.Val);
1190 Flags |= GlobalModeFlags (SubScript.Flags);
1191 g_addstatic (Flags, SubScript.Name, SubScript.Val);
1194 if (ED_IsLocAbs (Expr)) {
1195 /* Constant numeric address. Just add it */
1196 g_inc (CF_INT | CF_UNSIGNED, Expr->Val);
1197 } else if (ED_IsLocStack (Expr)) {
1198 /* Base address is a local variable address */
1199 if (IsTypeArray (Expr->Type)) {
1200 g_addaddr_local (CF_INT, Expr->Val);
1202 g_addlocal (CF_PTR, Expr->Val);
1205 /* Base address is a static variable address */
1206 unsigned Flags = CF_INT | GlobalModeFlags (Expr->Flags);
1207 if (IsTypeArray (Expr->Type)) {
1208 g_addaddr_static (Flags, Expr->Name, Expr->Val);
1210 g_addstatic (Flags, Expr->Name, Expr->Val);
1218 /* The result is an expression in the primary */
1219 ED_MakeRValExpr (Expr);
1223 /* Result is of element type */
1224 Expr->Type = ElementType;
1226 /* An array element is actually a variable. So the rules for variables
1227 * with respect to the reference type apply: If it's an array, it is
1228 * a rvalue, otherwise it's an lvalue. (A function would also be a rvalue,
1229 * but an array cannot contain functions).
1231 if (IsTypeArray (Expr->Type)) {
1237 /* Consume the closing bracket */
1243 static void StructRef (ExprDesc* Expr)
1244 /* Process struct field after . or ->. */
1249 /* Skip the token and check for an identifier */
1251 if (CurTok.Tok != TOK_IDENT) {
1252 Error ("Identifier expected");
1253 Expr->Type = type_int;
1257 /* Get the symbol table entry and check for a struct field */
1258 strcpy (Ident, CurTok.Ident);
1260 Field = FindStructField (Expr->Type, Ident);
1262 Error ("Struct/union has no field named `%s'", Ident);
1263 Expr->Type = type_int;
1267 /* If we have a struct pointer that is not already in the primary, load
1270 if (IsTypePtr (Expr->Type)) {
1272 /* Load into the primary */
1273 ExprLoad (CF_NONE, Expr);
1275 /* Make it an lvalue expression */
1276 ED_MakeLValExpr (Expr);
1279 /* Set the struct field offset */
1280 Expr->Val += Field->V.Offs;
1282 /* The type is now the type of the field */
1283 Expr->Type = Field->Type;
1285 /* An struct member is actually a variable. So the rules for variables
1286 * with respect to the reference type apply: If it's an array, it is
1287 * a rvalue, otherwise it's an lvalue. (A function would also be a rvalue,
1288 * but a struct field cannot be a function).
1290 if (IsTypeArray (Expr->Type)) {
1299 static void hie11 (ExprDesc *Expr)
1300 /* Handle compound types (structs and arrays) */
1302 /* Evaluate the lhs */
1305 /* Check for a rhs */
1306 while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN ||
1307 CurTok.Tok == TOK_DOT || CurTok.Tok == TOK_PTR_REF) {
1309 switch (CurTok.Tok) {
1312 /* Array reference */
1317 /* Function call. */
1318 if (!IsTypeFunc (Expr->Type) && !IsTypeFuncPtr (Expr->Type)) {
1319 /* Not a function */
1320 Error ("Illegal function call");
1321 /* Force the type to be a implicitly defined function, one
1322 * returning an int and taking any number of arguments.
1323 * Since we don't have a name, place it at absolute address
1326 ED_MakeConstAbs (Expr, 0, GetImplicitFuncType ());
1328 /* Call the function */
1329 FunctionCall (Expr);
1333 if (!IsClassStruct (Expr->Type)) {
1334 Error ("Struct expected");
1340 /* If we have an array, convert it to pointer to first element */
1341 if (IsTypeArray (Expr->Type)) {
1342 Expr->Type = ArrayToPtr (Expr->Type);
1344 if (!IsClassPtr (Expr->Type) || !IsClassStruct (Indirect (Expr->Type))) {
1345 Error ("Struct pointer expected");
1351 Internal ("Invalid token in hie11: %d", CurTok.Tok);
1359 void Store (ExprDesc* Expr, const type* StoreType)
1360 /* Store the primary register into the location denoted by Expr. If StoreType
1361 * is given, use this type when storing instead of Expr->Type. If StoreType
1362 * is NULL, use Expr->Type instead.
1367 /* If StoreType was not given, use Expr->Type instead */
1368 if (StoreType == 0) {
1369 StoreType = Expr->Type;
1372 /* Prepare the code generator flags */
1373 Flags = TypeOf (StoreType);
1375 /* Testing the value */
1379 /* Do the store depending on the location */
1380 switch (ED_GetLoc (Expr)) {
1383 /* Absolute: numeric address or const */
1384 g_putstatic (Flags | CF_ABSOLUTE, Expr->Val, 0);
1388 /* Global variable */
1389 g_putstatic (Flags | CF_EXTERNAL, Expr->Name, Expr->Val);
1393 /* Static variable */
1394 g_putstatic (Flags | CF_STATIC, Expr->Name, Expr->Val);
1397 case E_LOC_REGISTER:
1398 /* Register variable */
1399 g_putstatic (Flags | CF_REGVAR, Expr->Name, Expr->Val);
1403 /* Value on the stack */
1404 g_putlocal (Flags, Expr->Val, 0);
1408 /* The primary register (value is already there) */
1409 /* ### Do we need a test here if the flag is set? */
1413 /* An expression in the primary register */
1414 g_putind (Flags, Expr->Val);
1418 /* Literal in the literal pool */
1419 g_putstatic (Flags | CF_STATIC, LiteralPoolLabel, Expr->Val);
1423 Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
1426 /* Assume that each one of the stores will invalidate CC */
1427 Expr->Test &= ~E_CC;
1432 static void PreInc (ExprDesc* Expr)
1433 /* Handle the preincrement operators */
1438 /* Skip the operator token */
1441 /* Evaluate the expression and check that it is an lvalue */
1443 if (!ED_IsLVal (Expr)) {
1444 Error ("Invalid lvalue");
1448 /* Get the data type */
1449 Flags = TypeOf (Expr->Type) | CF_FORCECHAR | CF_CONST;
1451 /* Get the increment value in bytes */
1452 Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1454 /* Check the location of the data */
1455 switch (ED_GetLoc (Expr)) {
1458 /* Absolute: numeric address or const */
1459 g_addeqstatic (Flags | CF_ABSOLUTE, Expr->Val, 0, Val);
1463 /* Global variable */
1464 g_addeqstatic (Flags | CF_EXTERNAL, Expr->Name, Expr->Val, Val);
1468 /* Static variable */
1469 g_addeqstatic (Flags | CF_STATIC, Expr->Name, Expr->Val, Val);
1472 case E_LOC_REGISTER:
1473 /* Register variable */
1474 g_addeqstatic (Flags | CF_REGVAR, Expr->Name, Expr->Val, Val);
1478 /* Value on the stack */
1479 g_addeqlocal (Flags, Expr->Val, Val);
1483 /* The primary register */
1488 /* An expression in the primary register */
1489 g_addeqind (Flags, Expr->Val, Val);
1493 /* Literal in the literal pool */
1494 g_addeqstatic (Flags | CF_STATIC, LiteralPoolLabel, Expr->Val, Val);
1498 Internal ("Invalid location in PreInc(): 0x%04X", ED_GetLoc (Expr));
1501 /* Result is an expression, no reference */
1502 ED_MakeRValExpr (Expr);
1507 static void PreDec (ExprDesc* Expr)
1508 /* Handle the predecrement operators */
1513 /* Skip the operator token */
1516 /* Evaluate the expression and check that it is an lvalue */
1518 if (!ED_IsLVal (Expr)) {
1519 Error ("Invalid lvalue");
1523 /* Get the data type */
1524 Flags = TypeOf (Expr->Type) | CF_FORCECHAR | CF_CONST;
1526 /* Get the increment value in bytes */
1527 Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1529 /* Check the location of the data */
1530 switch (ED_GetLoc (Expr)) {
1533 /* Absolute: numeric address or const */
1534 g_subeqstatic (Flags | CF_ABSOLUTE, Expr->Val, 0, Val);
1538 /* Global variable */
1539 g_subeqstatic (Flags | CF_EXTERNAL, Expr->Name, Expr->Val, Val);
1543 /* Static variable */
1544 g_subeqstatic (Flags | CF_STATIC, Expr->Name, Expr->Val, Val);
1547 case E_LOC_REGISTER:
1548 /* Register variable */
1549 g_subeqstatic (Flags | CF_REGVAR, Expr->Name, Expr->Val, Val);
1553 /* Value on the stack */
1554 g_subeqlocal (Flags, Expr->Val, Val);
1558 /* The primary register */
1563 /* An expression in the primary register */
1564 g_subeqind (Flags, Expr->Val, Val);
1568 /* Literal in the literal pool */
1569 g_subeqstatic (Flags | CF_STATIC, LiteralPoolLabel, Expr->Val, Val);
1573 Internal ("Invalid location in PreDec(): 0x%04X", ED_GetLoc (Expr));
1576 /* Result is an expression, no reference */
1577 ED_MakeRValExpr (Expr);
1582 static void PostIncDec (ExprDesc* Expr, void (*inc) (unsigned, unsigned long))
1583 /* Handle i-- and i++ */
1589 /* The expression to increment must be an lvalue */
1590 if (!ED_IsLVal (Expr)) {
1591 Error ("Invalid lvalue");
1595 /* Get the data type */
1596 Flags = TypeOf (Expr->Type);
1598 /* Push the address if needed */
1601 /* Fetch the value and save it (since it's the result of the expression) */
1602 ExprLoad (CF_NONE, Expr);
1603 g_save (Flags | CF_FORCECHAR);
1605 /* If we have a pointer expression, increment by the size of the type */
1606 if (IsTypePtr (Expr->Type)) {
1607 inc (Flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (Expr->Type + 1));
1609 inc (Flags | CF_CONST | CF_FORCECHAR, 1);
1612 /* Store the result back */
1615 /* Restore the original value in the primary register */
1616 g_restore (Flags | CF_FORCECHAR);
1618 /* The result is always an expression, no reference */
1619 ED_MakeRValExpr (Expr);
1624 static void UnaryOp (ExprDesc* Expr)
1625 /* Handle unary -/+ and ~ */
1629 /* Remember the operator token and skip it */
1630 token_t Tok = CurTok.Tok;
1633 /* Get the expression */
1636 /* We can only handle integer types */
1637 if (!IsClassInt (Expr->Type)) {
1638 Error ("Argument must have integer type");
1639 ED_MakeConstAbsInt (Expr, 1);
1642 /* Check for a constant expression */
1643 if (ED_IsConstAbs (Expr)) {
1644 /* Value is constant */
1646 case TOK_MINUS: Expr->Val = -Expr->Val; break;
1647 case TOK_PLUS: break;
1648 case TOK_COMP: Expr->Val = ~Expr->Val; break;
1649 default: Internal ("Unexpected token: %d", Tok);
1652 /* Value is not constant */
1653 ExprLoad (CF_NONE, Expr);
1655 /* Get the type of the expression */
1656 Flags = TypeOf (Expr->Type);
1658 /* Handle the operation */
1660 case TOK_MINUS: g_neg (Flags); break;
1661 case TOK_PLUS: break;
1662 case TOK_COMP: g_com (Flags); break;
1663 default: Internal ("Unexpected token: %d", Tok);
1666 /* The result is a rvalue in the primary */
1667 ED_MakeRValExpr (Expr);
1673 void hie10 (ExprDesc* Expr)
1674 /* Handle ++, --, !, unary - etc. */
1678 switch (CurTok.Tok) {
1696 if (evalexpr (CF_NONE, hie10, Expr) == 0) {
1697 /* Constant expression */
1698 Expr->Val = !Expr->Val;
1700 g_bneg (TypeOf (Expr->Type));
1701 ED_MakeRValExpr (Expr);
1702 Expr->Test |= E_CC; /* bneg will set cc */
1708 if (evalexpr (CF_NONE, hie10, Expr) != 0) {
1709 /* Expression is not const, indirect value loaded into primary */
1710 ED_MakeRValExpr (Expr);
1712 /* If the expression is already a pointer to function, the
1713 * additional dereferencing operator must be ignored.
1715 if (IsTypeFuncPtr (Expr->Type)) {
1716 /* Expression not storable */
1719 if (IsClassPtr (Expr->Type)) {
1720 Expr->Type = Indirect (Expr->Type);
1722 Error ("Illegal indirection");
1731 /* The & operator may be applied to any lvalue, and it may be
1732 * applied to functions, even if they're no lvalues.
1734 if (ED_IsRVal (Expr) && !IsTypeFunc (Expr->Type)) {
1735 /* Allow the & operator with an array */
1736 if (!IsTypeArray (Expr->Type)) {
1737 Error ("Illegal address");
1740 Expr->Type = PointerTo (Expr->Type);
1747 if (TypeSpecAhead ()) {
1748 type Type[MAXTYPELEN];
1750 Size = CheckedSizeOf (ParseType (Type));
1753 /* Remember the output queue pointer */
1754 CodeMark Mark = GetCodePos ();
1756 Size = CheckedSizeOf (Expr->Type);
1757 /* Remove any generated code */
1760 ED_MakeConstAbs (Expr, Size, type_size_t);
1761 Expr->Test &= ~E_CC;
1765 if (TypeSpecAhead ()) {
1775 /* Handle post increment */
1776 if (CurTok.Tok == TOK_INC) {
1777 PostIncDec (Expr, g_inc);
1778 } else if (CurTok.Tok == TOK_DEC) {
1779 PostIncDec (Expr, g_dec);
1789 static void hie_internal (const GenDesc* Ops, /* List of generators */
1791 void (*hienext) (ExprDesc*),
1793 /* Helper function */
1799 token_t Tok; /* The operator token */
1800 unsigned ltype, type;
1801 int rconst; /* Operand is a constant */
1807 while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
1809 /* Tell the caller that we handled it's ops */
1812 /* All operators that call this function expect an int on the lhs */
1813 if (!IsClassInt (Expr->Type)) {
1814 Error ("Integer expression expected");
1817 /* Remember the operator token, then skip it */
1821 /* Get the lhs on stack */
1822 Mark1 = GetCodePos ();
1823 ltype = TypeOf (Expr->Type);
1824 if (ED_IsConstAbs (Expr)) {
1825 /* Constant value */
1826 Mark2 = GetCodePos ();
1827 g_push (ltype | CF_CONST, Expr->Val);
1829 /* Value not constant */
1830 ExprLoad (CF_NONE, Expr);
1831 Mark2 = GetCodePos ();
1835 /* Get the right hand side */
1836 rconst = (evalexpr (CF_NONE, hienext, &Expr2) == 0);
1838 /* Check the type of the rhs */
1839 if (!IsClassInt (Expr2.Type)) {
1840 Error ("Integer expression expected");
1843 /* Check for const operands */
1844 if (ED_IsConstAbs (Expr) && rconst) {
1846 /* Both operands are constant, remove the generated code */
1850 /* Evaluate the result */
1851 Expr->Val = kcalc (Tok, Expr->Val, Expr2.Val);
1853 /* Get the type of the result */
1854 Expr->Type = promoteint (Expr->Type, Expr2.Type);
1858 /* If the right hand side is constant, and the generator function
1859 * expects the lhs in the primary, remove the push of the primary
1862 unsigned rtype = TypeOf (Expr2.Type);
1865 /* Second value is constant - check for div */
1868 if (Tok == TOK_DIV && Expr2.Val == 0) {
1869 Error ("Division by zero");
1870 } else if (Tok == TOK_MOD && Expr2.Val == 0) {
1871 Error ("Modulo operation with zero");
1873 if ((Gen->Flags & GEN_NOPUSH) != 0) {
1876 ltype |= CF_REG; /* Value is in register */
1880 /* Determine the type of the operation result. */
1881 type |= g_typeadjust (ltype, rtype);
1882 Expr->Type = promoteint (Expr->Type, Expr2.Type);
1885 Gen->Func (type, Expr2.Val);
1887 /* We have a rvalue in the primary now */
1888 ED_MakeRValExpr (Expr);
1895 static void hie_compare (const GenDesc* Ops, /* List of generators */
1897 void (*hienext) (ExprDesc*))
1898 /* Helper function for the compare operators */
1904 token_t tok; /* The operator token */
1906 int rconst; /* Operand is a constant */
1911 while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
1913 /* Remember the operator token, then skip it */
1917 /* Get the lhs on stack */
1918 Mark1 = GetCodePos ();
1919 ltype = TypeOf (Expr->Type);
1920 if (ED_IsConstAbs (Expr)) {
1921 /* Constant value */
1922 Mark2 = GetCodePos ();
1923 g_push (ltype | CF_CONST, Expr->Val);
1925 /* Value not constant */
1926 ExprLoad (CF_NONE, Expr);
1927 Mark2 = GetCodePos ();
1931 /* Get the right hand side */
1932 rconst = (evalexpr (CF_NONE, hienext, &Expr2) == 0);
1934 /* Make sure, the types are compatible */
1935 if (IsClassInt (Expr->Type)) {
1936 if (!IsClassInt (Expr2.Type) && !(IsClassPtr(Expr2.Type) && ED_IsNullPtr(Expr))) {
1937 Error ("Incompatible types");
1939 } else if (IsClassPtr (Expr->Type)) {
1940 if (IsClassPtr (Expr2.Type)) {
1941 /* Both pointers are allowed in comparison if they point to
1942 * the same type, or if one of them is a void pointer.
1944 type* left = Indirect (Expr->Type);
1945 type* right = Indirect (Expr2.Type);
1946 if (TypeCmp (left, right) < TC_EQUAL && *left != T_VOID && *right != T_VOID) {
1947 /* Incomatible pointers */
1948 Error ("Incompatible types");
1950 } else if (!ED_IsNullPtr (&Expr2)) {
1951 Error ("Incompatible types");
1955 /* Check for const operands */
1956 if (ED_IsConstAbs (Expr) && rconst) {
1958 /* Both operands are constant, remove the generated code */
1962 /* Evaluate the result */
1963 Expr->Val = kcalc (tok, Expr->Val, Expr2.Val);
1967 /* If the right hand side is constant, and the generator function
1968 * expects the lhs in the primary, remove the push of the primary
1974 if ((Gen->Flags & GEN_NOPUSH) != 0) {
1977 ltype |= CF_REG; /* Value is in register */
1981 /* Determine the type of the operation result. If the left
1982 * operand is of type char and the right is a constant, or
1983 * if both operands are of type char, we will encode the
1984 * operation as char operation. Otherwise the default
1985 * promotions are used.
1987 if (IsTypeChar (Expr->Type) && (IsTypeChar (Expr2.Type) || rconst)) {
1989 if (IsSignUnsigned (Expr->Type) || IsSignUnsigned (Expr2.Type)) {
1990 flags |= CF_UNSIGNED;
1993 flags |= CF_FORCECHAR;
1996 unsigned rtype = TypeOf (Expr2.Type) | (flags & CF_CONST);
1997 flags |= g_typeadjust (ltype, rtype);
2001 Gen->Func (flags, Expr2.Val);
2003 /* The result is an rvalue in the primary */
2004 ED_MakeRValExpr (Expr);
2007 /* Result type is always int */
2008 Expr->Type = type_int;
2010 /* Condition codes are set */
2017 static void hie9 (ExprDesc *Expr)
2018 /* Process * and / operators. */
2020 static const GenDesc hie9_ops[] = {
2021 { TOK_STAR, GEN_NOPUSH, g_mul },
2022 { TOK_DIV, GEN_NOPUSH, g_div },
2023 { TOK_MOD, GEN_NOPUSH, g_mod },
2024 { TOK_INVALID, 0, 0 }
2028 hie_internal (hie9_ops, Expr, hie10, &UsedGen);
2033 static void parseadd (ExprDesc* Expr)
2034 /* Parse an expression with the binary plus operator. Expr contains the
2035 * unprocessed left hand side of the expression and will contain the
2036 * result of the expression on return.
2040 unsigned flags; /* Operation flags */
2041 CodeMark Mark; /* Remember code position */
2042 type* lhst; /* Type of left hand side */
2043 type* rhst; /* Type of right hand side */
2046 /* Skip the PLUS token */
2049 /* Get the left hand side type, initialize operation flags */
2053 /* Check for constness on both sides */
2054 if (ED_IsConst (Expr)) {
2056 /* The left hand side is a constant of some sort. Good. Get rhs */
2058 if (ED_IsConstAbs (&Expr2)) {
2060 /* Right hand side is a constant numeric value. Get the rhs type */
2063 /* Both expressions are constants. Check for pointer arithmetic */
2064 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2065 /* Left is pointer, right is int, must scale rhs */
2066 Expr->Val += Expr2.Val * CheckedPSizeOf (lhst);
2067 /* Result type is a pointer */
2068 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2069 /* Left is int, right is pointer, must scale lhs */
2070 Expr->Val = Expr->Val * CheckedPSizeOf (rhst) + Expr2.Val;
2071 /* Result type is a pointer */
2072 Expr->Type = Expr2.Type;
2073 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2074 /* Integer addition */
2075 Expr->Val += Expr2.Val;
2076 typeadjust (Expr, &Expr2, 1);
2079 Error ("Invalid operands for binary operator `+'");
2084 /* lhs is a constant and rhs is not constant. Load rhs into
2087 ExprLoad (CF_NONE, &Expr2);
2089 /* Beware: The check above (for lhs) lets not only pass numeric
2090 * constants, but also constant addresses (labels), maybe even
2091 * with an offset. We have to check for that here.
2094 /* First, get the rhs type. */
2098 if (ED_IsLocAbs (Expr)) {
2099 /* A numerical constant */
2102 /* Constant address label */
2103 flags |= GlobalModeFlags (Expr->Flags) | CF_CONSTADDR;
2106 /* Check for pointer arithmetic */
2107 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2108 /* Left is pointer, right is int, must scale rhs */
2109 g_scale (CF_INT, CheckedPSizeOf (lhst));
2110 /* Operate on pointers, result type is a pointer */
2112 /* Generate the code for the add */
2113 if (ED_GetLoc (Expr) == E_LOC_ABS) {
2114 /* Numeric constant */
2115 g_inc (flags, Expr->Val);
2117 /* Constant address */
2118 g_addaddr_static (flags, Expr->Name, Expr->Val);
2120 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2122 /* Left is int, right is pointer, must scale lhs. */
2123 unsigned ScaleFactor = CheckedPSizeOf (rhst);
2125 /* Operate on pointers, result type is a pointer */
2127 Expr->Type = Expr2.Type;
2129 /* Since we do already have rhs in the primary, if lhs is
2130 * not a numeric constant, and the scale factor is not one
2131 * (no scaling), we must take the long way over the stack.
2133 if (ED_IsLocAbs (Expr)) {
2134 /* Numeric constant, scale lhs */
2135 Expr->Val *= ScaleFactor;
2136 /* Generate the code for the add */
2137 g_inc (flags, Expr->Val);
2138 } else if (ScaleFactor == 1) {
2139 /* Constant address but no need to scale */
2140 g_addaddr_static (flags, Expr->Name, Expr->Val);
2142 /* Constant address that must be scaled */
2143 g_push (TypeOf (Expr2.Type), 0); /* rhs --> stack */
2144 g_getimmed (flags, Expr->Name, Expr->Val);
2145 g_scale (CF_PTR, ScaleFactor);
2148 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2149 /* Integer addition */
2150 flags |= typeadjust (Expr, &Expr2, 1);
2151 /* Generate the code for the add */
2152 if (ED_IsLocAbs (Expr)) {
2153 /* Numeric constant */
2154 g_inc (flags, Expr->Val);
2156 /* Constant address */
2157 g_addaddr_static (flags, Expr->Name, Expr->Val);
2161 Error ("Invalid operands for binary operator `+'");
2164 /* Result is a rvalue in primary register */
2165 ED_MakeRValExpr (Expr);
2170 /* Left hand side is not constant. Get the value onto the stack. */
2171 ExprLoad (CF_NONE, Expr); /* --> primary register */
2172 Mark = GetCodePos ();
2173 g_push (TypeOf (Expr->Type), 0); /* --> stack */
2175 /* Evaluate the rhs */
2176 if (evalexpr (CF_NONE, hie9, &Expr2) == 0) {
2178 /* Right hand side is a constant. Get the rhs type */
2181 /* Remove pushed value from stack */
2183 pop (TypeOf (Expr->Type));
2185 /* Check for pointer arithmetic */
2186 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2187 /* Left is pointer, right is int, must scale rhs */
2188 Expr2.Val *= CheckedPSizeOf (lhst);
2189 /* Operate on pointers, result type is a pointer */
2191 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2192 /* Left is int, right is pointer, must scale lhs (ptr only) */
2193 g_scale (CF_INT | CF_CONST, CheckedPSizeOf (rhst));
2194 /* Operate on pointers, result type is a pointer */
2196 Expr->Type = Expr2.Type;
2197 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2198 /* Integer addition */
2199 flags = typeadjust (Expr, &Expr2, 1);
2202 Error ("Invalid operands for binary operator `+'");
2205 /* Generate code for the add */
2206 g_inc (flags | CF_CONST, Expr2.Val);
2210 /* lhs and rhs are not constant. Get the rhs type. */
2213 /* Check for pointer arithmetic */
2214 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2215 /* Left is pointer, right is int, must scale rhs */
2216 g_scale (CF_INT, CheckedPSizeOf (lhst));
2217 /* Operate on pointers, result type is a pointer */
2219 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2220 /* Left is int, right is pointer, must scale lhs */
2221 g_tosint (TypeOf (rhst)); /* Make sure, TOS is int */
2222 g_swap (CF_INT); /* Swap TOS and primary */
2223 g_scale (CF_INT, CheckedPSizeOf (rhst));
2224 /* Operate on pointers, result type is a pointer */
2226 Expr->Type = Expr2.Type;
2227 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2228 /* Integer addition. Note: Result is never constant.
2229 * Problem here is that typeadjust does not know if the
2230 * variable is an rvalue or lvalue, so if both operands
2231 * are dereferenced constant numeric addresses, typeadjust
2232 * thinks the operation works on constants. Removing
2233 * CF_CONST here means handling the symptoms, however, the
2234 * whole parser is such a mess that I fear to break anything
2235 * when trying to apply another solution.
2237 flags = typeadjust (Expr, &Expr2, 0) & ~CF_CONST;
2240 Error ("Invalid operands for binary operator `+'");
2243 /* Generate code for the add */
2248 /* Result is a rvalue in primary register */
2249 ED_MakeRValExpr (Expr);
2252 /* Condition codes not set */
2253 Expr->Test &= ~E_CC;
2259 static void parsesub (ExprDesc* Expr)
2260 /* Parse an expression with the binary minus operator. Expr contains the
2261 * unprocessed left hand side of the expression and will contain the
2262 * result of the expression on return.
2266 unsigned flags; /* Operation flags */
2267 type* lhst; /* Type of left hand side */
2268 type* rhst; /* Type of right hand side */
2269 CodeMark Mark1; /* Save position of output queue */
2270 CodeMark Mark2; /* Another position in the queue */
2271 int rscale; /* Scale factor for the result */
2274 /* Skip the MINUS token */
2277 /* Get the left hand side type, initialize operation flags */
2280 rscale = 1; /* Scale by 1, that is, don't scale */
2282 /* Remember the output queue position, then bring the value onto the stack */
2283 Mark1 = GetCodePos ();
2284 ExprLoad (CF_NONE, Expr); /* --> primary register */
2285 Mark2 = GetCodePos ();
2286 g_push (TypeOf (lhst), 0); /* --> stack */
2288 /* Parse the right hand side */
2289 if (evalexpr (CF_NONE, hie9, &Expr2) == 0) {
2291 /* The right hand side is constant. Get the rhs type. */
2294 /* Check left hand side */
2295 if (ED_IsConstAbs (Expr)) {
2297 /* Both sides are constant, remove generated code */
2299 pop (TypeOf (lhst)); /* Clean up the stack */
2301 /* Check for pointer arithmetic */
2302 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2303 /* Left is pointer, right is int, must scale rhs */
2304 Expr->Val -= Expr2.Val * CheckedPSizeOf (lhst);
2305 /* Operate on pointers, result type is a pointer */
2306 } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2307 /* Left is pointer, right is pointer, must scale result */
2308 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2309 Error ("Incompatible pointer types");
2311 Expr->Val = (Expr->Val - Expr2.Val) /
2312 CheckedPSizeOf (lhst);
2314 /* Operate on pointers, result type is an integer */
2315 Expr->Type = type_int;
2316 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2317 /* Integer subtraction */
2318 typeadjust (Expr, &Expr2, 1);
2319 Expr->Val -= Expr2.Val;
2322 Error ("Invalid operands for binary operator `-'");
2325 /* Result is constant, condition codes not set */
2326 Expr->Test &= ~E_CC;
2330 /* Left hand side is not constant, right hand side is.
2331 * Remove pushed value from stack.
2334 pop (TypeOf (lhst));
2336 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2337 /* Left is pointer, right is int, must scale rhs */
2338 Expr2.Val *= CheckedPSizeOf (lhst);
2339 /* Operate on pointers, result type is a pointer */
2341 } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2342 /* Left is pointer, right is pointer, must scale result */
2343 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2344 Error ("Incompatible pointer types");
2346 rscale = CheckedPSizeOf (lhst);
2348 /* Operate on pointers, result type is an integer */
2350 Expr->Type = type_int;
2351 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2352 /* Integer subtraction */
2353 flags = typeadjust (Expr, &Expr2, 1);
2356 Error ("Invalid operands for binary operator `-'");
2359 /* Do the subtraction */
2360 g_dec (flags | CF_CONST, Expr2.Val);
2362 /* If this was a pointer subtraction, we must scale the result */
2364 g_scale (flags, -rscale);
2367 /* Result is a rvalue in the primary register */
2368 ED_MakeRValExpr (Expr);
2369 Expr->Test &= ~E_CC;
2375 /* Right hand side is not constant. Get the rhs type. */
2378 /* Check for pointer arithmetic */
2379 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2380 /* Left is pointer, right is int, must scale rhs */
2381 g_scale (CF_INT, CheckedPSizeOf (lhst));
2382 /* Operate on pointers, result type is a pointer */
2384 } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2385 /* Left is pointer, right is pointer, must scale result */
2386 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2387 Error ("Incompatible pointer types");
2389 rscale = CheckedPSizeOf (lhst);
2391 /* Operate on pointers, result type is an integer */
2393 Expr->Type = type_int;
2394 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2395 /* Integer subtraction. If the left hand side descriptor says that
2396 * the lhs is const, we have to remove this mark, since this is no
2397 * longer true, lhs is on stack instead.
2399 if (ED_IsLocAbs (Expr)) {
2400 ED_MakeRValExpr (Expr);
2402 /* Adjust operand types */
2403 flags = typeadjust (Expr, &Expr2, 0);
2406 Error ("Invalid operands for binary operator `-'");
2409 /* Generate code for the sub (the & is a hack here) */
2410 g_sub (flags & ~CF_CONST, 0);
2412 /* If this was a pointer subtraction, we must scale the result */
2414 g_scale (flags, -rscale);
2417 /* Result is a rvalue in the primary register */
2418 ED_MakeRValExpr (Expr);
2419 Expr->Test &= ~E_CC;
2425 static void hie8 (ExprDesc* Expr)
2426 /* Process + and - binary operators. */
2429 while (CurTok.Tok == TOK_PLUS || CurTok.Tok == TOK_MINUS) {
2430 if (CurTok.Tok == TOK_PLUS) {
2440 static void hie7 (ExprDesc* Expr)
2441 /* Parse << and >>. */
2443 static const GenDesc hie7_ops [] = {
2444 { TOK_SHL, GEN_NOPUSH, g_asl },
2445 { TOK_SHR, GEN_NOPUSH, g_asr },
2446 { TOK_INVALID, 0, 0 }
2450 hie_internal (hie7_ops, Expr, hie8, &UsedGen);
2455 static void hie6 (ExprDesc* Expr)
2456 /* Handle greater-than type comparators */
2458 static const GenDesc hie6_ops [] = {
2459 { TOK_LT, GEN_NOPUSH, g_lt },
2460 { TOK_LE, GEN_NOPUSH, g_le },
2461 { TOK_GE, GEN_NOPUSH, g_ge },
2462 { TOK_GT, GEN_NOPUSH, g_gt },
2463 { TOK_INVALID, 0, 0 }
2465 hie_compare (hie6_ops, Expr, hie7);
2470 static void hie5 (ExprDesc* Expr)
2471 /* Handle == and != */
2473 static const GenDesc hie5_ops[] = {
2474 { TOK_EQ, GEN_NOPUSH, g_eq },
2475 { TOK_NE, GEN_NOPUSH, g_ne },
2476 { TOK_INVALID, 0, 0 }
2478 hie_compare (hie5_ops, Expr, hie6);
2483 static void hie4 (ExprDesc* Expr)
2484 /* Handle & (bitwise and) */
2486 static const GenDesc hie4_ops[] = {
2487 { TOK_AND, GEN_NOPUSH, g_and },
2488 { TOK_INVALID, 0, 0 }
2492 hie_internal (hie4_ops, Expr, hie5, &UsedGen);
2497 static void hie3 (ExprDesc* Expr)
2498 /* Handle ^ (bitwise exclusive or) */
2500 static const GenDesc hie3_ops[] = {
2501 { TOK_XOR, GEN_NOPUSH, g_xor },
2502 { TOK_INVALID, 0, 0 }
2506 hie_internal (hie3_ops, Expr, hie4, &UsedGen);
2511 static void hie2 (ExprDesc* Expr)
2512 /* Handle | (bitwise or) */
2514 static const GenDesc hie2_ops[] = {
2515 { TOK_OR, GEN_NOPUSH, g_or },
2516 { TOK_INVALID, 0, 0 }
2520 hie_internal (hie2_ops, Expr, hie3, &UsedGen);
2525 static void hieAndPP (ExprDesc* Expr)
2526 /* Process "exp && exp" in preprocessor mode (that is, when the parser is
2527 * called recursively from the preprocessor.
2532 ConstAbsIntExpr (hie2, Expr);
2533 while (CurTok.Tok == TOK_BOOL_AND) {
2539 ConstAbsIntExpr (hie2, &Expr2);
2541 /* Combine the two */
2542 Expr->Val = (Expr->Val && Expr2.Val);
2548 static void hieOrPP (ExprDesc *Expr)
2549 /* Process "exp || exp" in preprocessor mode (that is, when the parser is
2550 * called recursively from the preprocessor.
2555 ConstAbsIntExpr (hieAndPP, Expr);
2556 while (CurTok.Tok == TOK_BOOL_OR) {
2562 ConstAbsIntExpr (hieAndPP, &Expr2);
2564 /* Combine the two */
2565 Expr->Val = (Expr->Val || Expr2.Val);
2571 static void hieAnd (ExprDesc* Expr, unsigned TrueLab, int* BoolOp)
2572 /* Process "exp && exp" */
2578 if (CurTok.Tok == TOK_BOOL_AND) {
2580 /* Tell our caller that we're evaluating a boolean */
2583 /* Get a label that we will use for false expressions */
2584 lab = GetLocalLabel ();
2586 /* If the expr hasn't set condition codes, set the force-test flag */
2587 if ((Expr->Test & E_CC) == 0) {
2588 Expr->Test |= E_FORCETEST;
2591 /* Load the value */
2592 ExprLoad (CF_FORCECHAR, Expr);
2594 /* Generate the jump */
2595 g_falsejump (CF_NONE, lab);
2597 /* Parse more boolean and's */
2598 while (CurTok.Tok == TOK_BOOL_AND) {
2605 if ((Expr2.Test & E_CC) == 0) {
2606 Expr2.Test |= E_FORCETEST;
2608 ExprLoad (CF_FORCECHAR, &Expr2);
2610 /* Do short circuit evaluation */
2611 if (CurTok.Tok == TOK_BOOL_AND) {
2612 g_falsejump (CF_NONE, lab);
2614 /* Last expression - will evaluate to true */
2615 g_truejump (CF_NONE, TrueLab);
2619 /* Define the false jump label here */
2620 g_defcodelabel (lab);
2622 /* The result is an rvalue in primary */
2623 ED_MakeRValExpr (Expr);
2624 Expr->Test |= E_CC; /* Condition codes are set */
2630 static void hieOr (ExprDesc *Expr)
2631 /* Process "exp || exp". */
2634 int BoolOp = 0; /* Did we have a boolean op? */
2635 int AndOp; /* Did we have a && operation? */
2636 unsigned TrueLab; /* Jump to this label if true */
2640 TrueLab = GetLocalLabel ();
2642 /* Call the next level parser */
2643 hieAnd (Expr, TrueLab, &BoolOp);
2645 /* Any boolean or's? */
2646 if (CurTok.Tok == TOK_BOOL_OR) {
2648 /* If the expr hasn't set condition codes, set the force-test flag */
2649 if ((Expr->Test & E_CC) == 0) {
2650 Expr->Test |= E_FORCETEST;
2653 /* Get first expr */
2654 ExprLoad (CF_FORCECHAR, Expr);
2656 /* For each expression jump to TrueLab if true. Beware: If we
2657 * had && operators, the jump is already in place!
2660 g_truejump (CF_NONE, TrueLab);
2663 /* Remember that we had a boolean op */
2666 /* while there's more expr */
2667 while (CurTok.Tok == TOK_BOOL_OR) {
2674 hieAnd (&Expr2, TrueLab, &AndOp);
2675 if ((Expr2.Test & E_CC) == 0) {
2676 Expr2.Test |= E_FORCETEST;
2678 ExprLoad (CF_FORCECHAR, &Expr2);
2680 /* If there is more to come, add shortcut boolean eval. */
2681 g_truejump (CF_NONE, TrueLab);
2685 /* The result is an rvalue in primary */
2686 ED_MakeRValExpr (Expr);
2687 Expr->Test |= E_CC; /* Condition codes are set */
2690 /* If we really had boolean ops, generate the end sequence */
2692 DoneLab = GetLocalLabel ();
2693 g_getimmed (CF_INT | CF_CONST, 0, 0); /* Load FALSE */
2694 g_falsejump (CF_NONE, DoneLab);
2695 g_defcodelabel (TrueLab);
2696 g_getimmed (CF_INT | CF_CONST, 1, 0); /* Load TRUE */
2697 g_defcodelabel (DoneLab);
2703 static void hieQuest (ExprDesc* Expr)
2704 /* Parse the ternary operator */
2708 ExprDesc Expr2; /* Expression 2 */
2709 ExprDesc Expr3; /* Expression 3 */
2710 int Expr2IsNULL; /* Expression 2 is a NULL pointer */
2711 int Expr3IsNULL; /* Expression 3 is a NULL pointer */
2712 type* ResultType; /* Type of result */
2715 /* Call the lower level eval routine */
2716 if (Preprocessing) {
2722 /* Check if it's a ternary expression */
2723 if (CurTok.Tok == TOK_QUEST) {
2725 if ((Expr->Test & E_CC) == 0) {
2726 /* Condition codes not set, force a test */
2727 Expr->Test |= E_FORCETEST;
2729 ExprLoad (CF_NONE, Expr);
2730 labf = GetLocalLabel ();
2731 g_falsejump (CF_NONE, labf);
2733 /* Parse second expression. Remember for later if it is a NULL pointer
2734 * expression, then load it into the primary.
2736 ExprWithCheck (hie1, &Expr2);
2737 Expr2IsNULL = ED_IsNullPtr (&Expr2);
2738 if (!IsTypeVoid (Expr2.Type)) {
2739 /* Load it into the primary */
2740 ExprLoad (CF_NONE, &Expr2);
2741 ED_MakeRValExpr (&Expr2);
2743 labt = GetLocalLabel ();
2747 /* Jump here if the first expression was false */
2748 g_defcodelabel (labf);
2750 /* Parse second expression. Remember for later if it is a NULL pointer
2751 * expression, then load it into the primary.
2753 ExprWithCheck (hie1, &Expr3);
2754 Expr3IsNULL = ED_IsNullPtr (&Expr3);
2755 if (!IsTypeVoid (Expr3.Type)) {
2756 /* Load it into the primary */
2757 ExprLoad (CF_NONE, &Expr3);
2758 ED_MakeRValExpr (&Expr3);
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 (Expr2.Type) && IsClassInt (Expr3.Type)) {
2776 /* Get common type */
2777 ResultType = promoteint (Expr2.Type, Expr3.Type);
2779 /* Convert the third expression to this type if needed */
2780 TypeConversion (&Expr3, ResultType);
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 g_jump (labf); /* Jump around code */
2788 /* The jump for expr2 goes here */
2789 g_defcodelabel (labt);
2791 /* Create the typecast code for expr2 */
2792 TypeConversion (&Expr2, ResultType);
2794 /* Jump here around the typecase code. */
2795 g_defcodelabel (labf);
2796 labt = 0; /* Mark other label as invalid */
2798 } else if (IsClassPtr (Expr2.Type) && IsClassPtr (Expr3.Type)) {
2799 /* Must point to same type */
2800 if (TypeCmp (Indirect (Expr2.Type), Indirect (Expr3.Type)) < TC_EQUAL) {
2801 Error ("Incompatible pointer types");
2803 /* Result has the common type */
2804 ResultType = Expr2.Type;
2805 } else if (IsClassPtr (Expr2.Type) && Expr3IsNULL) {
2806 /* Result type is pointer, no cast needed */
2807 ResultType = Expr2.Type;
2808 } else if (Expr2IsNULL && IsClassPtr (Expr3.Type)) {
2809 /* Result type is pointer, no cast needed */
2810 ResultType = Expr3.Type;
2811 } else if (IsTypeVoid (Expr2.Type) && IsTypeVoid (Expr3.Type)) {
2812 /* Result type is void */
2813 ResultType = Expr3.Type;
2815 Error ("Incompatible types");
2816 ResultType = Expr2.Type; /* Doesn't matter here */
2819 /* If we don't have the label defined until now, do it */
2821 g_defcodelabel (labt);
2824 /* Setup the target expression */
2825 ED_MakeRValExpr (Expr);
2826 Expr->Type = ResultType;
2832 static void opeq (const GenDesc* Gen, ExprDesc* Expr)
2833 /* Process "op=" operators. */
2840 /* op= can only be used with lvalues */
2841 if (!ED_IsLVal (Expr)) {
2842 Error ("Invalid lvalue in assignment");
2846 /* There must be an integer or pointer on the left side */
2847 if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
2848 Error ("Invalid left operand type");
2849 /* Continue. Wrong code will be generated, but the compiler won't
2850 * break, so this is the best error recovery.
2854 /* Skip the operator token */
2857 /* Determine the type of the lhs */
2858 flags = TypeOf (Expr->Type);
2859 MustScale = (Gen->Func == g_add || Gen->Func == g_sub) && IsTypePtr (Expr->Type);
2861 /* Get the lhs address on stack (if needed) */
2864 /* Fetch the lhs into the primary register if needed */
2865 ExprLoad (CF_NONE, Expr);
2867 /* Bring the lhs on stack */
2868 Mark = GetCodePos ();
2871 /* Evaluate the rhs */
2872 if (evalexpr (CF_NONE, hie1, &Expr2) == 0) {
2873 /* The resulting value is a constant. If the generator has the NOPUSH
2874 * flag set, don't push the lhs.
2876 if (Gen->Flags & GEN_NOPUSH) {
2881 /* lhs is a pointer, scale rhs */
2882 Expr2.Val *= CheckedSizeOf (Expr->Type+1);
2885 /* If the lhs is character sized, the operation may be later done
2888 if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
2889 flags |= CF_FORCECHAR;
2892 /* Special handling for add and sub - some sort of a hack, but short code */
2893 if (Gen->Func == g_add) {
2894 g_inc (flags | CF_CONST, Expr2.Val);
2895 } else if (Gen->Func == g_sub) {
2896 g_dec (flags | CF_CONST, Expr2.Val);
2898 Gen->Func (flags | CF_CONST, Expr2.Val);
2901 /* rhs is not constant and already in the primary register */
2903 /* lhs is a pointer, scale rhs */
2904 g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Expr->Type+1));
2907 /* If the lhs is character sized, the operation may be later done
2910 if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
2911 flags |= CF_FORCECHAR;
2914 /* Adjust the types of the operands if needed */
2915 Gen->Func (g_typeadjust (flags, TypeOf (Expr2.Type)), 0);
2918 ED_MakeRValExpr (Expr);
2923 static void addsubeq (const GenDesc* Gen, ExprDesc *Expr)
2924 /* Process the += and -= operators */
2932 /* We're currently only able to handle some adressing modes */
2933 if (ED_GetLoc (Expr) == E_LOC_EXPR || ED_GetLoc (Expr) == E_LOC_PRIMARY) {
2934 /* Use generic routine */
2939 /* We must have an lvalue */
2940 if (ED_IsRVal (Expr)) {
2941 Error ("Invalid lvalue in assignment");
2945 /* There must be an integer or pointer on the left side */
2946 if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
2947 Error ("Invalid left operand type");
2948 /* Continue. Wrong code will be generated, but the compiler won't
2949 * break, so this is the best error recovery.
2953 /* Skip the operator */
2956 /* Check if we have a pointer expression and must scale rhs */
2957 MustScale = IsTypePtr (Expr->Type);
2959 /* Initialize the code generator flags */
2963 /* Evaluate the rhs */
2965 if (ED_IsConstAbs (&Expr2)) {
2966 /* The resulting value is a constant. Scale it. */
2968 Expr2.Val *= CheckedSizeOf (Indirect (Expr->Type));
2973 /* Not constant, load into the primary */
2974 ExprLoad (CF_NONE, &Expr2);
2976 /* lhs is a pointer, scale rhs */
2977 g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Indirect (Expr->Type)));
2981 /* Setup the code generator flags */
2982 lflags |= TypeOf (Expr->Type) | CF_FORCECHAR;
2983 rflags |= TypeOf (Expr2.Type);
2985 /* Convert the type of the lhs to that of the rhs */
2986 g_typecast (lflags, rflags);
2988 /* Output apropriate code depending on the location */
2989 switch (ED_GetLoc (Expr)) {
2992 /* Absolute: numeric address or const */
2993 lflags |= CF_ABSOLUTE;
2994 if (Gen->Tok == TOK_PLUS_ASSIGN) {
2995 g_addeqstatic (lflags, Expr->Name, Expr->Val, Expr2.Val);
2997 g_subeqstatic (lflags, Expr->Name, Expr->Val, Expr2.Val);
3002 /* Global variable */
3003 lflags |= CF_EXTERNAL;
3004 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3005 g_addeqstatic (lflags, Expr->Name, Expr->Val, Expr2.Val);
3007 g_subeqstatic (lflags, Expr->Name, Expr->Val, Expr2.Val);
3012 /* Static variable */
3013 lflags |= CF_STATIC;
3014 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3015 g_addeqstatic (lflags, Expr->Name, Expr->Val, Expr2.Val);
3017 g_subeqstatic (lflags, Expr->Name, Expr->Val, Expr2.Val);
3021 case E_LOC_REGISTER:
3022 /* Register variable */
3023 lflags |= CF_REGVAR;
3024 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3025 g_addeqstatic (lflags, Expr->Name, Expr->Val, Expr2.Val);
3027 g_subeqstatic (lflags, Expr->Name, Expr->Val, Expr2.Val);
3032 /* Value on the stack */
3033 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3034 g_addeqlocal (lflags, Expr->Val, Expr2.Val);
3036 g_subeqlocal (lflags, Expr->Val, Expr2.Val);
3041 /* Literal in the literal pool */
3042 lflags |= CF_STATIC;
3043 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3044 g_addeqstatic (lflags, LiteralPoolLabel, Expr->Val, Expr2.Val);
3046 g_subeqstatic (lflags, LiteralPoolLabel, Expr->Val, Expr2.Val);
3051 Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
3054 /* Expression is a rvalue in the primary now */
3055 ED_MakeRValExpr (Expr);
3060 void hie1 (ExprDesc* Expr)
3061 /* Parse first level of expression hierarchy. */
3064 switch (CurTok.Tok) {
3070 case TOK_PLUS_ASSIGN:
3071 addsubeq (&GenPASGN, Expr);
3074 case TOK_MINUS_ASSIGN:
3075 addsubeq (&GenSASGN, Expr);
3078 case TOK_MUL_ASSIGN:
3079 opeq (&GenMASGN, Expr);
3082 case TOK_DIV_ASSIGN:
3083 opeq (&GenDASGN, Expr);
3086 case TOK_MOD_ASSIGN:
3087 opeq (&GenMOASGN, Expr);
3090 case TOK_SHL_ASSIGN:
3091 opeq (&GenSLASGN, Expr);
3094 case TOK_SHR_ASSIGN:
3095 opeq (&GenSRASGN, Expr);
3098 case TOK_AND_ASSIGN:
3099 opeq (&GenAASGN, Expr);
3102 case TOK_XOR_ASSIGN:
3103 opeq (&GenXOASGN, Expr);
3107 opeq (&GenOASGN, Expr);
3117 void hie0 (ExprDesc *Expr)
3118 /* Parse comma operator. */
3121 while (CurTok.Tok == TOK_COMMA) {
3129 int evalexpr (unsigned Flags, void (*Func) (ExprDesc*), ExprDesc* Expr)
3130 /* Will evaluate an expression via the given function. If the result is a
3131 * constant, 0 is returned and the value is put in the Expr struct. If the
3132 * result is not constant, ExprLoad is called to bring the value into the
3133 * primary register and 1 is returned.
3137 ExprWithCheck (Func, Expr);
3139 /* Check for a constant expression */
3140 if (ED_IsConstAbs (Expr)) {
3141 /* Constant expression */
3144 /* Not constant, load into the primary */
3145 ExprLoad (Flags, Expr);
3152 void Expression0 (ExprDesc* Expr)
3153 /* Evaluate an expression via hie0 and put the result into the primary register */
3155 ExprWithCheck (hie0, Expr);
3156 ExprLoad (CF_NONE, Expr);
3161 void ConstExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3162 /* Will evaluate an expression via the given function. If the result is not
3163 * a constant of some sort, a diagnostic will be printed, and the value is
3164 * replaced by a constant one to make sure there are no internal errors that
3165 * result from this input error.
3168 ExprWithCheck (Func, Expr);
3169 if (!ED_IsConst (Expr)) {
3170 Error ("Constant expression expected");
3171 /* To avoid any compiler errors, make the expression a valid const */
3172 ED_MakeConstAbsInt (Expr, 1);
3178 void BoolExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3179 /* Will evaluate an expression via the given function. If the result is not
3180 * something that may be evaluated in a boolean context, a diagnostic will be
3181 * printed, and the value is replaced by a constant one to make sure there
3182 * are no internal errors that result from this input error.
3185 ExprWithCheck (Func, Expr);
3186 if (!ED_IsBool (Expr)) {
3187 Error ("Boolean expression expected");
3188 /* To avoid any compiler errors, make the expression a valid int */
3189 ED_MakeConstAbsInt (Expr, 1);
3195 void ConstAbsIntExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3196 /* Will evaluate an expression via the given function. If the result is not
3197 * a constant numeric integer value, a diagnostic will be printed, and the
3198 * value is replaced by a constant one to make sure there are no internal
3199 * errors that result from this input error.
3202 ExprWithCheck (Func, Expr);
3203 if (!ED_IsConstAbsInt (Expr)) {
3204 Error ("Constant integer expression expected");
3205 /* To avoid any compiler errors, make the expression a valid const */
3206 ED_MakeConstAbsInt (Expr, 1);