3 * Ullrich von Bassewitz, 21.06.1998
13 #include "debugflag.h"
20 #include "assignment.h"
32 #include "shiftexpr.h"
43 /*****************************************************************************/
45 /*****************************************************************************/
49 /* Generator attributes */
50 #define GEN_NOPUSH 0x01 /* Don't push lhs */
51 #define GEN_COMM 0x02 /* Operator is commutative */
53 /* Map a generator function and its attributes to a token */
55 token_t Tok; /* Token to map to */
56 unsigned Flags; /* Flags for generator function */
57 void (*Func) (unsigned, unsigned long); /* Generator func */
60 /* Descriptors for the operations */
61 static GenDesc GenPASGN = { TOK_PLUS_ASSIGN, GEN_NOPUSH, g_add };
62 static GenDesc GenSASGN = { TOK_MINUS_ASSIGN, GEN_NOPUSH, g_sub };
63 static GenDesc GenMASGN = { TOK_MUL_ASSIGN, GEN_NOPUSH, g_mul };
64 static GenDesc GenDASGN = { TOK_DIV_ASSIGN, GEN_NOPUSH, g_div };
65 static GenDesc GenMOASGN = { TOK_MOD_ASSIGN, GEN_NOPUSH, g_mod };
66 static GenDesc GenSLASGN = { TOK_SHL_ASSIGN, GEN_NOPUSH, g_asl };
67 static GenDesc GenSRASGN = { TOK_SHR_ASSIGN, GEN_NOPUSH, g_asr };
68 static GenDesc GenAASGN = { TOK_AND_ASSIGN, GEN_NOPUSH, g_and };
69 static GenDesc GenXOASGN = { TOK_XOR_ASSIGN, GEN_NOPUSH, g_xor };
70 static GenDesc GenOASGN = { TOK_OR_ASSIGN, GEN_NOPUSH, g_or };
74 /*****************************************************************************/
75 /* Helper functions */
76 /*****************************************************************************/
80 static unsigned GlobalModeFlags (const ExprDesc* Expr)
81 /* Return the addressing mode flags for the given expression */
83 switch (ED_GetLoc (Expr)) {
84 case E_LOC_ABS: return CF_ABSOLUTE;
85 case E_LOC_GLOBAL: return CF_EXTERNAL;
86 case E_LOC_STATIC: return CF_STATIC;
87 case E_LOC_REGISTER: return CF_REGVAR;
88 case E_LOC_STACK: return CF_NONE;
89 case E_LOC_PRIMARY: return CF_NONE;
90 case E_LOC_EXPR: return CF_NONE;
91 case E_LOC_LITERAL: return CF_STATIC; /* Same as static */
93 Internal ("GlobalModeFlags: Invalid location flags value: 0x%04X", Expr->Flags);
101 void ExprWithCheck (void (*Func) (ExprDesc*), ExprDesc* Expr)
102 /* Call an expression function with checks. */
104 /* Remember the stack pointer */
105 int OldSP = StackPtr;
107 /* Call the expression function */
110 /* Do some checks if code generation is still constistent */
111 if (StackPtr != OldSP) {
113 Error ("Code generation messed up: "
114 "StackPtr is %d, should be %d",
117 Internal ("Code generation messed up: "
118 "StackPtr is %d, should be %d",
126 void MarkedExprWithCheck (void (*Func) (ExprDesc*), ExprDesc* Expr)
127 /* Call an expression function with checks and record start and end of the
133 ExprWithCheck (Func, Expr);
135 ED_SetCodeRange (Expr, &Start, &End);
140 static Type* promoteint (Type* lhst, Type* rhst)
141 /* In an expression with two ints, return the type of the result */
143 /* Rules for integer types:
144 * - If one of the values is a long, the result is long.
145 * - If one of the values is unsigned, the result is also unsigned.
146 * - Otherwise the result is an int.
148 if (IsTypeLong (lhst) || IsTypeLong (rhst)) {
149 if (IsSignUnsigned (lhst) || IsSignUnsigned (rhst)) {
155 if (IsSignUnsigned (lhst) || IsSignUnsigned (rhst)) {
165 static unsigned typeadjust (ExprDesc* lhs, ExprDesc* rhs, int NoPush)
166 /* Adjust the two values for a binary operation. lhs is expected on stack or
167 * to be constant, rhs is expected to be in the primary register or constant.
168 * The function will put the type of the result into lhs and return the
169 * code generator flags for the operation.
170 * If NoPush is given, it is assumed that the operation does not expect the lhs
171 * to be on stack, and that lhs is in a register instead.
172 * Beware: The function does only accept int types.
175 unsigned ltype, rtype;
178 /* Get the type strings */
179 Type* lhst = lhs->Type;
180 Type* rhst = rhs->Type;
182 /* Generate type adjustment code if needed */
183 ltype = TypeOf (lhst);
184 if (ED_IsLocAbs (lhs)) {
188 /* Value is in primary register*/
191 rtype = TypeOf (rhst);
192 if (ED_IsLocAbs (rhs)) {
195 flags = g_typeadjust (ltype, rtype);
197 /* Set the type of the result */
198 lhs->Type = promoteint (lhst, rhst);
200 /* Return the code generator flags */
206 static const GenDesc* FindGen (token_t Tok, const GenDesc* Table)
207 /* Find a token in a generator table */
209 while (Table->Tok != TOK_INVALID) {
210 if (Table->Tok == Tok) {
220 static int TypeSpecAhead (void)
221 /* Return true if some sort of type is waiting (helper for cast and sizeof()
227 /* There's a type waiting if:
229 * We have an opening paren, and
230 * a. the next token is a type, or
231 * b. the next token is a type qualifier, or
232 * c. the next token is a typedef'd type
234 return CurTok.Tok == TOK_LPAREN && (
235 TokIsType (&NextTok) ||
236 TokIsTypeQual (&NextTok) ||
237 (NextTok.Tok == TOK_IDENT &&
238 (Entry = FindSym (NextTok.Ident)) != 0 &&
239 SymIsTypeDef (Entry)));
244 void PushAddr (const ExprDesc* Expr)
245 /* If the expression contains an address that was somehow evaluated,
246 * push this address on the stack. This is a helper function for all
247 * sorts of implicit or explicit assignment functions where the lvalue
248 * must be saved if it's not constant, before evaluating the rhs.
251 /* Get the address on stack if needed */
252 if (ED_IsLocExpr (Expr)) {
253 /* Push the address (always a pointer) */
260 static void WarnConstCompareResult (void)
261 /* If the result of a comparison is constant, this is suspicious when not in
265 if (!Preprocessing && IS_Get (&WarnConstComparison) != 0) {
266 Warning ("Result of comparison is constant");
272 /*****************************************************************************/
274 /*****************************************************************************/
278 static unsigned FunctionParamList (FuncDesc* Func, int IsFastcall)
279 /* Parse a function parameter list and pass the parameters to the called
280 * function. Depending on several criteria this may be done by just pushing
281 * each parameter separately, or creating the parameter frame once and then
282 * storing into this frame.
283 * The function returns the size of the parameters pushed.
288 /* Initialize variables */
289 SymEntry* Param = 0; /* Keep gcc silent */
290 unsigned ParamSize = 0; /* Size of parameters pushed */
291 unsigned ParamCount = 0; /* Number of parameters pushed */
292 unsigned FrameSize = 0; /* Size of parameter frame */
293 unsigned FrameParams = 0; /* Number of params in frame */
294 int FrameOffs = 0; /* Offset into parameter frame */
295 int Ellipsis = 0; /* Function is variadic */
297 /* As an optimization, we may allocate the complete parameter frame at
298 * once instead of pushing each parameter as it comes. We may do that,
301 * - optimizations that increase code size are enabled (allocating the
302 * stack frame at once gives usually larger code).
303 * - we have more than one parameter to push (don't count the last param
304 * for __fastcall__ functions).
306 * The FrameSize variable will contain a value > 0 if storing into a frame
307 * (instead of pushing) is enabled.
310 if (IS_Get (&CodeSizeFactor) >= 200) {
312 /* Calculate the number and size of the parameters */
313 FrameParams = Func->ParamCount;
314 FrameSize = Func->ParamSize;
315 if (FrameParams > 0 && IsFastcall) {
316 /* Last parameter is not pushed */
317 FrameSize -= CheckedSizeOf (Func->LastParam->Type);
321 /* Do we have more than one parameter in the frame? */
322 if (FrameParams > 1) {
323 /* Okeydokey, setup the frame */
324 FrameOffs = StackPtr;
326 StackPtr -= FrameSize;
328 /* Don't use a preallocated frame */
333 /* Parse the actual parameter list */
334 while (CurTok.Tok != TOK_RPAREN) {
338 /* Count arguments */
341 /* Fetch the pointer to the next argument, check for too many args */
342 if (ParamCount <= Func->ParamCount) {
343 /* Beware: If there are parameters with identical names, they
344 * cannot go into the same symbol table, which means that in this
345 * case of errorneous input, the number of nodes in the symbol
346 * table and ParamCount are NOT equal. We have to handle this case
347 * below to avoid segmentation violations. Since we know that this
348 * problem can only occur if there is more than one parameter,
349 * we will just use the last one.
351 if (ParamCount == 1) {
353 Param = Func->SymTab->SymHead;
354 } else if (Param->NextSym != 0) {
356 Param = Param->NextSym;
357 CHECK ((Param->Flags & SC_PARAM) != 0);
359 } else if (!Ellipsis) {
360 /* Too many arguments. Do we have an open param list? */
361 if ((Func->Flags & FD_VARIADIC) == 0) {
362 /* End of param list reached, no ellipsis */
363 Error ("Too many arguments in function call");
365 /* Assume an ellipsis even in case of errors to avoid an error
366 * message for each other argument.
371 /* Evaluate the parameter expression */
374 /* If we don't have an argument spec, accept anything, otherwise
375 * convert the actual argument to the type needed.
380 /* Convert the argument to the parameter type if needed */
381 TypeConversion (&Expr, Param->Type);
383 /* If we have a prototype, chars may be pushed as chars */
384 Flags |= CF_FORCECHAR;
388 /* No prototype available. Convert array to "pointer to first
389 * element", and function to "pointer to function".
391 Expr.Type = PtrConversion (Expr.Type);
395 /* Load the value into the primary if it is not already there */
396 LoadExpr (Flags, &Expr);
398 /* Use the type of the argument for the push */
399 Flags |= TypeOf (Expr.Type);
401 /* If this is a fastcall function, don't push the last argument */
402 if (ParamCount != Func->ParamCount || !IsFastcall) {
403 unsigned ArgSize = sizeofarg (Flags);
405 /* We have the space already allocated, store in the frame.
406 * Because of invalid type conversions (that have produced an
407 * error before), we can end up here with a non aligned stack
408 * frame. Since no output will be generated anyway, handle
409 * these cases gracefully instead of doing a CHECK.
411 if (FrameSize >= ArgSize) {
412 FrameSize -= ArgSize;
416 FrameOffs -= ArgSize;
418 g_putlocal (Flags | CF_NOKEEP, FrameOffs, Expr.IVal);
420 /* Push the argument */
421 g_push (Flags, Expr.IVal);
424 /* Calculate total parameter size */
425 ParamSize += ArgSize;
428 /* Check for end of argument list */
429 if (CurTok.Tok != TOK_COMMA) {
435 /* Check if we had enough parameters */
436 if (ParamCount < Func->ParamCount) {
437 Error ("Too few arguments in function call");
440 /* The function returns the size of all parameters pushed onto the stack.
441 * However, if there are parameters missing (which is an error and was
442 * flagged by the compiler) AND a stack frame was preallocated above,
443 * we would loose track of the stackpointer and generate an internal error
444 * later. So we correct the value by the parameters that should have been
445 * pushed to avoid an internal compiler error. Since an error was
446 * generated before, no code will be output anyway.
448 return ParamSize + FrameSize;
453 static void FunctionCall (ExprDesc* Expr)
454 /* Perform a function call. */
456 FuncDesc* Func; /* Function descriptor */
457 int IsFuncPtr; /* Flag */
458 unsigned ParamSize; /* Number of parameter bytes */
460 int PtrOffs = 0; /* Offset of function pointer on stack */
461 int IsFastcall = 0; /* True if it's a fast call function */
462 int PtrOnStack = 0; /* True if a pointer copy is on stack */
464 /* Skip the left paren */
467 /* Get a pointer to the function descriptor from the type string */
468 Func = GetFuncDesc (Expr->Type);
470 /* Handle function pointers transparently */
471 IsFuncPtr = IsTypeFuncPtr (Expr->Type);
474 /* Check wether it's a fastcall function that has parameters */
475 IsFastcall = IsQualFastcall (Expr->Type + 1) && (Func->ParamCount > 0);
477 /* Things may be difficult, depending on where the function pointer
478 * resides. If the function pointer is an expression of some sort
479 * (not a local or global variable), we have to evaluate this
480 * expression now and save the result for later. Since calls to
481 * function pointers may be nested, we must save it onto the stack.
482 * For fastcall functions we do also need to place a copy of the
483 * pointer on stack, since we cannot use a/x.
485 PtrOnStack = IsFastcall || !ED_IsConst (Expr);
488 /* Not a global or local variable, or a fastcall function. Load
489 * the pointer into the primary and mark it as an expression.
491 LoadExpr (CF_NONE, Expr);
492 ED_MakeRValExpr (Expr);
494 /* Remember the code position */
497 /* Push the pointer onto the stack and remember the offset */
503 /* Check function attributes */
504 if (Expr->Sym && SymHasAttr (Expr->Sym, atNoReturn)) {
505 /* For now, handle as if a return statement was encountered */
506 F_ReturnFound (CurrentFunc);
509 /* Check for known standard functions and inline them */
510 if (Expr->Name != 0) {
511 int StdFunc = FindStdFunc ((const char*) Expr->Name);
513 /* Inline this function */
514 HandleStdFunc (StdFunc, Func, Expr);
519 /* If we didn't inline the function, get fastcall info */
520 IsFastcall = IsQualFastcall (Expr->Type);
523 /* Parse the parameter list */
524 ParamSize = FunctionParamList (Func, IsFastcall);
526 /* We need the closing paren here */
529 /* Special handling for function pointers */
532 /* If the function is not a fastcall function, load the pointer to
533 * the function into the primary.
537 /* Not a fastcall function - we may use the primary */
539 /* If we have no parameters, the pointer is still in the
540 * primary. Remove the code to push it and correct the
543 if (ParamSize == 0) {
547 /* Load from the saved copy */
548 g_getlocal (CF_PTR, PtrOffs);
551 /* Load from original location */
552 LoadExpr (CF_NONE, Expr);
555 /* Call the function */
556 g_callind (TypeOf (Expr->Type+1), ParamSize, PtrOffs);
560 /* Fastcall function. We cannot use the primary for the function
561 * pointer and must therefore use an offset to the stack location.
562 * Since fastcall functions may never be variadic, we can use the
563 * index register for this purpose.
565 g_callind (CF_LOCAL, ParamSize, PtrOffs);
568 /* If we have a pointer on stack, remove it */
579 /* Normal function */
580 g_call (TypeOf (Expr->Type), (const char*) Expr->Name, ParamSize);
584 /* The function result is an rvalue in the primary register */
585 ED_MakeRValExpr (Expr);
586 Expr->Type = GetFuncReturn (Expr->Type);
591 static void Primary (ExprDesc* E)
592 /* This is the lowest level of the expression parser. */
596 /* Initialize fields in the expression stucture */
599 /* Character and integer constants. */
600 if (CurTok.Tok == TOK_ICONST || CurTok.Tok == TOK_CCONST) {
601 E->IVal = CurTok.IVal;
602 E->Flags = E_LOC_ABS | E_RTYPE_RVAL;
603 E->Type = CurTok.Type;
608 /* Floating point constant */
609 if (CurTok.Tok == TOK_FCONST) {
610 E->FVal = CurTok.FVal;
611 E->Flags = E_LOC_ABS | E_RTYPE_RVAL;
612 E->Type = CurTok.Type;
617 /* Process parenthesized subexpression by calling the whole parser
620 if (CurTok.Tok == TOK_LPAREN) {
627 /* If we run into an identifier in preprocessing mode, we assume that this
628 * is an undefined macro and replace it by a constant value of zero.
630 if (Preprocessing && CurTok.Tok == TOK_IDENT) {
632 ED_MakeConstAbsInt (E, 0);
636 /* All others may only be used if the expression evaluation is not called
637 * recursively by the preprocessor.
640 /* Illegal expression in PP mode */
641 Error ("Preprocessor expression expected");
642 ED_MakeConstAbsInt (E, 1);
646 switch (CurTok.Tok) {
649 /* Identifier. Get a pointer to the symbol table entry */
650 Sym = E->Sym = FindSym (CurTok.Ident);
652 /* Is the symbol known? */
655 /* We found the symbol - skip the name token */
658 /* Check for illegal symbol types */
659 CHECK ((Sym->Flags & SC_LABEL) != SC_LABEL);
660 if (Sym->Flags & SC_TYPE) {
661 /* Cannot use type symbols */
662 Error ("Variable identifier expected");
663 /* Assume an int type to make E valid */
664 E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
669 /* Mark the symbol as referenced */
670 Sym->Flags |= SC_REF;
672 /* The expression type is the symbol type */
675 /* Check for legal symbol types */
676 if ((Sym->Flags & SC_CONST) == SC_CONST) {
677 /* Enum or some other numeric constant */
678 E->Flags = E_LOC_ABS | E_RTYPE_RVAL;
679 E->IVal = Sym->V.ConstVal;
680 } else if ((Sym->Flags & SC_FUNC) == SC_FUNC) {
682 E->Flags = E_LOC_GLOBAL | E_RTYPE_LVAL;
683 E->Name = (unsigned long) Sym->Name;
684 } else if ((Sym->Flags & SC_AUTO) == SC_AUTO) {
685 /* Local variable. If this is a parameter for a variadic
686 * function, we have to add some address calculations, and the
687 * address is not const.
689 if ((Sym->Flags & SC_PARAM) == SC_PARAM && F_IsVariadic (CurrentFunc)) {
690 /* Variadic parameter */
691 g_leavariadic (Sym->V.Offs - F_GetParamSize (CurrentFunc));
692 E->Flags = E_LOC_EXPR | E_RTYPE_LVAL;
694 /* Normal parameter */
695 E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
696 E->IVal = Sym->V.Offs;
698 } else if ((Sym->Flags & SC_REGISTER) == SC_REGISTER) {
699 /* Register variable, zero page based */
700 E->Flags = E_LOC_REGISTER | E_RTYPE_LVAL;
701 E->Name = Sym->V.R.RegOffs;
702 } else if ((Sym->Flags & SC_STATIC) == SC_STATIC) {
703 /* Static variable */
704 if (Sym->Flags & (SC_EXTERN | SC_STORAGE)) {
705 E->Flags = E_LOC_GLOBAL | E_RTYPE_LVAL;
706 E->Name = (unsigned long) Sym->Name;
708 E->Flags = E_LOC_STATIC | E_RTYPE_LVAL;
709 E->Name = Sym->V.Label;
712 /* Local static variable */
713 E->Flags = E_LOC_STATIC | E_RTYPE_LVAL;
714 E->Name = Sym->V.Offs;
717 /* We've made all variables lvalues above. However, this is
718 * not always correct: An array is actually the address of its
719 * first element, which is a rvalue, and a function is a
720 * rvalue, too, because we cannot store anything in a function.
721 * So fix the flags depending on the type.
723 if (IsTypeArray (E->Type) || IsTypeFunc (E->Type)) {
729 /* We did not find the symbol. Remember the name, then skip it */
731 strcpy (Ident, CurTok.Ident);
734 /* IDENT is either an auto-declared function or an undefined variable. */
735 if (CurTok.Tok == TOK_LPAREN) {
736 /* C99 doesn't allow calls to undefined functions, so
737 * generate an error and otherwise a warning. Declare a
738 * function returning int. For that purpose, prepare a
739 * function signature for a function having an empty param
740 * list and returning int.
742 if (IS_Get (&Standard) >= STD_C99) {
743 Error ("Call to undefined function `%s'", Ident);
745 Warning ("Call to undefined function `%s'", Ident);
747 Sym = AddGlobalSym (Ident, GetImplicitFuncType(), SC_EXTERN | SC_REF | SC_FUNC);
749 E->Flags = E_LOC_GLOBAL | E_RTYPE_RVAL;
750 E->Name = (unsigned long) Sym->Name;
752 /* Undeclared Variable */
753 Sym = AddLocalSym (Ident, type_int, SC_AUTO | SC_REF, 0);
754 E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
756 Error ("Undefined symbol: `%s'", Ident);
765 E->LVal = UseLiteral (CurTok.SVal);
766 E->Type = GetCharArrayType (GetLiteralSize (CurTok.SVal));
767 E->Flags = E_LOC_LITERAL | E_RTYPE_RVAL;
769 E->Name = GetLiteralLabel (CurTok.SVal);
776 E->Flags = E_LOC_EXPR | E_RTYPE_RVAL;
781 /* Register pseudo variable */
782 E->Type = type_uchar;
783 E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
788 /* Register pseudo variable */
790 E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
795 /* Register pseudo variable */
796 E->Type = type_ulong;
797 E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
802 /* Illegal primary. Be sure to skip the token to avoid endless
805 Error ("Expression expected");
807 ED_MakeConstAbsInt (E, 1);
814 static void ArrayRef (ExprDesc* Expr)
815 /* Handle an array reference. This function needs a rewrite. */
826 /* Skip the bracket */
829 /* Get the type of left side */
832 /* We can apply a special treatment for arrays that have a const base
833 * address. This is true for most arrays and will produce a lot better
834 * code. Check if this is a const base address.
836 ConstBaseAddr = ED_IsRVal (Expr) &&
837 (ED_IsLocConst (Expr) || ED_IsLocStack (Expr));
839 /* If we have a constant base, we delay the address fetch */
841 if (!ConstBaseAddr) {
842 /* Get a pointer to the array into the primary */
843 LoadExpr (CF_NONE, Expr);
845 /* Get the array pointer on stack. Do not push more than 16
846 * bit, even if this value is greater, since we cannot handle
847 * other than 16bit stuff when doing indexing.
853 /* TOS now contains ptr to array elements. Get the subscript. */
854 MarkedExprWithCheck (hie0, &Subscript);
856 /* Check the types of array and subscript. We can either have a
857 * pointer/array to the left, in which case the subscript must be of an
858 * integer type, or we have an integer to the left, in which case the
859 * subscript must be a pointer/array.
860 * Since we do the necessary checking here, we can rely later on the
863 Qualifiers = T_QUAL_NONE;
864 if (IsClassPtr (Expr->Type)) {
865 if (!IsClassInt (Subscript.Type)) {
866 Error ("Array subscript is not an integer");
867 /* To avoid any compiler errors, make the expression a valid int */
868 ED_MakeConstAbsInt (&Subscript, 0);
870 if (IsTypeArray (Expr->Type)) {
871 Qualifiers = GetQualifier (Expr->Type);
873 ElementType = Indirect (Expr->Type);
874 } else if (IsClassInt (Expr->Type)) {
875 if (!IsClassPtr (Subscript.Type)) {
876 Error ("Subscripted value is neither array nor pointer");
877 /* To avoid compiler errors, make the subscript a char[] at
880 ED_MakeConstAbs (&Subscript, 0, GetCharArrayType (1));
881 } else if (IsTypeArray (Subscript.Type)) {
882 Qualifiers = GetQualifier (Subscript.Type);
884 ElementType = Indirect (Subscript.Type);
886 Error ("Cannot subscript");
887 /* To avoid compiler errors, fake both the array and the subscript, so
888 * we can just proceed.
890 ED_MakeConstAbs (Expr, 0, GetCharArrayType (1));
891 ED_MakeConstAbsInt (&Subscript, 0);
892 ElementType = Indirect (Expr->Type);
895 /* The element type has the combined qualifiers from itself and the array,
896 * it is a member of (if any).
898 if (GetQualifier (ElementType) != (GetQualifier (ElementType) | Qualifiers)) {
899 ElementType = TypeDup (ElementType);
900 ElementType->C |= Qualifiers;
903 /* If the subscript is a bit-field, load it and make it an rvalue */
904 if (ED_IsBitField (&Subscript)) {
905 LoadExpr (CF_NONE, &Subscript);
906 ED_MakeRValExpr (&Subscript);
909 /* Check if the subscript is constant absolute value */
910 if (ED_IsConstAbs (&Subscript) && ED_CodeRangeIsEmpty (&Subscript)) {
912 /* The array subscript is a numeric constant. If we had pushed the
913 * array base address onto the stack before, we can remove this value,
914 * since we can generate expression+offset.
916 if (!ConstBaseAddr) {
919 /* Get an array pointer into the primary */
920 LoadExpr (CF_NONE, Expr);
923 if (IsClassPtr (Expr->Type)) {
925 /* Lhs is pointer/array. Scale the subscript value according to
928 Subscript.IVal *= CheckedSizeOf (ElementType);
930 /* Remove the address load code */
933 /* In case of an array, we can adjust the offset of the expression
934 * already in Expr. If the base address was a constant, we can even
935 * remove the code that loaded the address into the primary.
937 if (IsTypeArray (Expr->Type)) {
939 /* Adjust the offset */
940 Expr->IVal += Subscript.IVal;
944 /* It's a pointer, so we do have to load it into the primary
945 * first (if it's not already there).
947 if (ConstBaseAddr || ED_IsLVal (Expr)) {
948 LoadExpr (CF_NONE, Expr);
949 ED_MakeRValExpr (Expr);
953 Expr->IVal = Subscript.IVal;
958 /* Scale the rhs value according to the element type */
959 g_scale (TypeOf (tptr1), CheckedSizeOf (ElementType));
961 /* Add the subscript. Since arrays are indexed by integers,
962 * we will ignore the true type of the subscript here and
963 * use always an int. #### Use offset but beware of LoadExpr!
965 g_inc (CF_INT | CF_CONST, Subscript.IVal);
971 /* Array subscript is not constant. Load it into the primary */
973 LoadExpr (CF_NONE, &Subscript);
976 if (IsClassPtr (Expr->Type)) {
978 /* Indexing is based on unsigneds, so we will just use the integer
979 * portion of the index (which is in (e)ax, so there's no further
982 g_scale (CF_INT, CheckedSizeOf (ElementType));
986 /* Get the int value on top. If we come here, we're sure, both
987 * values are 16 bit (the first one was truncated if necessary
988 * and the second one is a pointer). Note: If ConstBaseAddr is
989 * true, we don't have a value on stack, so to "swap" both, just
990 * push the subscript.
994 LoadExpr (CF_NONE, Expr);
1001 g_scale (TypeOf (tptr1), CheckedSizeOf (ElementType));
1005 /* The offset is now in the primary register. It we didn't have a
1006 * constant base address for the lhs, the lhs address is already
1007 * on stack, and we must add the offset. If the base address was
1008 * constant, we call special functions to add the address to the
1011 if (!ConstBaseAddr) {
1013 /* The array base address is on stack and the subscript is in the
1014 * primary. Add both.
1020 /* The subscript is in the primary, and the array base address is
1021 * in Expr. If the subscript has itself a constant address, it is
1022 * often a better idea to reverse again the order of the
1023 * evaluation. This will generate better code if the subscript is
1024 * a byte sized variable. But beware: This is only possible if the
1025 * subscript was not scaled, that is, if this was a byte array
1028 if ((ED_IsLocConst (&Subscript) || ED_IsLocStack (&Subscript)) &&
1029 CheckedSizeOf (ElementType) == SIZEOF_CHAR) {
1033 /* Reverse the order of evaluation */
1034 if (CheckedSizeOf (Subscript.Type) == SIZEOF_CHAR) {
1039 RemoveCode (&Mark2);
1041 /* Get a pointer to the array into the primary. */
1042 LoadExpr (CF_NONE, Expr);
1044 /* Add the variable */
1045 if (ED_IsLocStack (&Subscript)) {
1046 g_addlocal (Flags, Subscript.IVal);
1048 Flags |= GlobalModeFlags (&Subscript);
1049 g_addstatic (Flags, Subscript.Name, Subscript.IVal);
1053 if (ED_IsLocAbs (Expr)) {
1054 /* Constant numeric address. Just add it */
1055 g_inc (CF_INT, Expr->IVal);
1056 } else if (ED_IsLocStack (Expr)) {
1057 /* Base address is a local variable address */
1058 if (IsTypeArray (Expr->Type)) {
1059 g_addaddr_local (CF_INT, Expr->IVal);
1061 g_addlocal (CF_PTR, Expr->IVal);
1064 /* Base address is a static variable address */
1065 unsigned Flags = CF_INT | GlobalModeFlags (Expr);
1066 if (ED_IsRVal (Expr)) {
1067 /* Add the address of the location */
1068 g_addaddr_static (Flags, Expr->Name, Expr->IVal);
1070 /* Add the contents of the location */
1071 g_addstatic (Flags, Expr->Name, Expr->IVal);
1079 /* The result is an expression in the primary */
1080 ED_MakeRValExpr (Expr);
1084 /* Result is of element type */
1085 Expr->Type = ElementType;
1087 /* An array element is actually a variable. So the rules for variables
1088 * with respect to the reference type apply: If it's an array, it is
1089 * a rvalue, otherwise it's an lvalue. (A function would also be a rvalue,
1090 * but an array cannot contain functions).
1092 if (IsTypeArray (Expr->Type)) {
1098 /* Consume the closing bracket */
1104 static void StructRef (ExprDesc* Expr)
1105 /* Process struct field after . or ->. */
1112 /* Skip the token and check for an identifier */
1114 if (CurTok.Tok != TOK_IDENT) {
1115 Error ("Identifier expected");
1116 /* Make the expression an integer at address zero */
1117 ED_MakeConstAbs (Expr, 0, type_int);
1121 /* Get the symbol table entry and check for a struct field */
1122 strcpy (Ident, CurTok.Ident);
1124 Field = FindStructField (Expr->Type, Ident);
1126 Error ("Struct/union has no field named `%s'", Ident);
1127 /* Make the expression an integer at address zero */
1128 ED_MakeConstAbs (Expr, 0, type_int);
1132 /* If we have a struct pointer that is an lvalue and not already in the
1133 * primary, load it now.
1135 if (ED_IsLVal (Expr) && IsTypePtr (Expr->Type)) {
1137 /* Load into the primary */
1138 LoadExpr (CF_NONE, Expr);
1140 /* Make it an lvalue expression */
1141 ED_MakeLValExpr (Expr);
1144 /* The type is the type of the field plus any qualifiers from the struct */
1145 if (IsClassStruct (Expr->Type)) {
1146 Q = GetQualifier (Expr->Type);
1148 Q = GetQualifier (Indirect (Expr->Type));
1150 if (GetQualifier (Field->Type) == (GetQualifier (Field->Type) | Q)) {
1151 FinalType = Field->Type;
1153 FinalType = TypeDup (Field->Type);
1157 /* A struct is usually an lvalue. If not, it is a struct in the primary
1160 if (ED_IsRVal (Expr) && ED_IsLocExpr (Expr) && !IsTypePtr (Expr->Type)) {
1165 /* Get the size of the type */
1166 unsigned Size = SizeOf (Expr->Type);
1169 CHECK (Field->V.Offs + Size <= SIZEOF_LONG);
1171 /* The type of the operation depends on the type of the struct */
1173 case 1: Flags = CF_CHAR | CF_UNSIGNED | CF_CONST; break;
1174 case 2: Flags = CF_INT | CF_UNSIGNED | CF_CONST; break;
1175 case 3: /* FALLTHROUGH */
1176 case 4: Flags = CF_LONG | CF_UNSIGNED | CF_CONST; break;
1177 default: Internal ("Invalid struct size: %u", Size); break;
1180 /* Generate a shift to get the field in the proper position in the
1181 * primary. For bit fields, mask the value.
1183 BitOffs = Field->V.Offs * CHAR_BITS;
1184 if (SymIsBitField (Field)) {
1185 BitOffs += Field->V.B.BitOffs;
1186 g_asr (Flags, BitOffs);
1187 /* Mask the value. This is unnecessary if the shift executed above
1188 * moved only zeroes into the value.
1190 if (BitOffs + Field->V.B.BitWidth != Size * CHAR_BITS) {
1191 g_and (CF_INT | CF_UNSIGNED | CF_CONST,
1192 (0x0001U << Field->V.B.BitWidth) - 1U);
1195 g_asr (Flags, BitOffs);
1198 /* Use the new type */
1199 Expr->Type = FinalType;
1203 /* Set the struct field offset */
1204 Expr->IVal += Field->V.Offs;
1206 /* Use the new type */
1207 Expr->Type = FinalType;
1209 /* An struct member is actually a variable. So the rules for variables
1210 * with respect to the reference type apply: If it's an array, it is
1211 * a rvalue, otherwise it's an lvalue. (A function would also be a rvalue,
1212 * but a struct field cannot be a function).
1214 if (IsTypeArray (Expr->Type)) {
1220 /* Make the expression a bit field if necessary */
1221 if (SymIsBitField (Field)) {
1222 ED_MakeBitField (Expr, Field->V.B.BitOffs, Field->V.B.BitWidth);
1230 static void hie11 (ExprDesc *Expr)
1231 /* Handle compound types (structs and arrays) */
1233 /* Name value used in invalid function calls */
1234 static const char IllegalFunc[] = "illegal_function_call";
1236 /* Evaluate the lhs */
1239 /* Check for a rhs */
1240 while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN ||
1241 CurTok.Tok == TOK_DOT || CurTok.Tok == TOK_PTR_REF) {
1243 switch (CurTok.Tok) {
1246 /* Array reference */
1251 /* Function call. */
1252 if (!IsTypeFunc (Expr->Type) && !IsTypeFuncPtr (Expr->Type)) {
1253 /* Not a function */
1254 Error ("Illegal function call");
1255 /* Force the type to be a implicitly defined function, one
1256 * returning an int and taking any number of arguments.
1257 * Since we don't have a name, invent one.
1259 ED_MakeConstAbs (Expr, 0, GetImplicitFuncType ());
1260 Expr->Name = (long) IllegalFunc;
1262 /* Call the function */
1263 FunctionCall (Expr);
1267 if (!IsClassStruct (Expr->Type)) {
1268 Error ("Struct expected");
1274 /* If we have an array, convert it to pointer to first element */
1275 if (IsTypeArray (Expr->Type)) {
1276 Expr->Type = ArrayToPtr (Expr->Type);
1278 if (!IsClassPtr (Expr->Type) || !IsClassStruct (Indirect (Expr->Type))) {
1279 Error ("Struct pointer expected");
1285 Internal ("Invalid token in hie11: %d", CurTok.Tok);
1293 void Store (ExprDesc* Expr, const Type* StoreType)
1294 /* Store the primary register into the location denoted by Expr. If StoreType
1295 * is given, use this type when storing instead of Expr->Type. If StoreType
1296 * is NULL, use Expr->Type instead.
1301 /* If StoreType was not given, use Expr->Type instead */
1302 if (StoreType == 0) {
1303 StoreType = Expr->Type;
1306 /* Prepare the code generator flags */
1307 Flags = TypeOf (StoreType) | GlobalModeFlags (Expr);
1309 /* Do the store depending on the location */
1310 switch (ED_GetLoc (Expr)) {
1313 /* Absolute: numeric address or const */
1314 g_putstatic (Flags, Expr->IVal, 0);
1318 /* Global variable */
1319 g_putstatic (Flags, Expr->Name, Expr->IVal);
1324 /* Static variable or literal in the literal pool */
1325 g_putstatic (Flags, Expr->Name, Expr->IVal);
1328 case E_LOC_REGISTER:
1329 /* Register variable */
1330 g_putstatic (Flags, Expr->Name, Expr->IVal);
1334 /* Value on the stack */
1335 g_putlocal (Flags, Expr->IVal, 0);
1339 /* The primary register (value is already there) */
1343 /* An expression in the primary register */
1344 g_putind (Flags, Expr->IVal);
1348 Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
1351 /* Assume that each one of the stores will invalidate CC */
1352 ED_MarkAsUntested (Expr);
1357 static void PreInc (ExprDesc* Expr)
1358 /* Handle the preincrement operators */
1363 /* Skip the operator token */
1366 /* Evaluate the expression and check that it is an lvalue */
1368 if (!ED_IsLVal (Expr)) {
1369 Error ("Invalid lvalue");
1373 /* We cannot modify const values */
1374 if (IsQualConst (Expr->Type)) {
1375 Error ("Increment of read-only variable");
1378 /* Get the data type */
1379 Flags = TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR | CF_CONST;
1381 /* Get the increment value in bytes */
1382 Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1384 /* Check the location of the data */
1385 switch (ED_GetLoc (Expr)) {
1388 /* Absolute: numeric address or const */
1389 g_addeqstatic (Flags, Expr->IVal, 0, Val);
1393 /* Global variable */
1394 g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1399 /* Static variable or literal in the literal pool */
1400 g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1403 case E_LOC_REGISTER:
1404 /* Register variable */
1405 g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1409 /* Value on the stack */
1410 g_addeqlocal (Flags, Expr->IVal, Val);
1414 /* The primary register */
1419 /* An expression in the primary register */
1420 g_addeqind (Flags, Expr->IVal, Val);
1424 Internal ("Invalid location in PreInc(): 0x%04X", ED_GetLoc (Expr));
1427 /* Result is an expression, no reference */
1428 ED_MakeRValExpr (Expr);
1433 static void PreDec (ExprDesc* Expr)
1434 /* Handle the predecrement operators */
1439 /* Skip the operator token */
1442 /* Evaluate the expression and check that it is an lvalue */
1444 if (!ED_IsLVal (Expr)) {
1445 Error ("Invalid lvalue");
1449 /* We cannot modify const values */
1450 if (IsQualConst (Expr->Type)) {
1451 Error ("Decrement of read-only variable");
1454 /* Get the data type */
1455 Flags = TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR | CF_CONST;
1457 /* Get the increment value in bytes */
1458 Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1460 /* Check the location of the data */
1461 switch (ED_GetLoc (Expr)) {
1464 /* Absolute: numeric address or const */
1465 g_subeqstatic (Flags, Expr->IVal, 0, Val);
1469 /* Global variable */
1470 g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1475 /* Static variable or literal in the literal pool */
1476 g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1479 case E_LOC_REGISTER:
1480 /* Register variable */
1481 g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1485 /* Value on the stack */
1486 g_subeqlocal (Flags, Expr->IVal, Val);
1490 /* The primary register */
1495 /* An expression in the primary register */
1496 g_subeqind (Flags, Expr->IVal, Val);
1500 Internal ("Invalid location in PreDec(): 0x%04X", ED_GetLoc (Expr));
1503 /* Result is an expression, no reference */
1504 ED_MakeRValExpr (Expr);
1509 static void PostInc (ExprDesc* Expr)
1510 /* Handle the postincrement operator */
1516 /* The expression to increment must be an lvalue */
1517 if (!ED_IsLVal (Expr)) {
1518 Error ("Invalid lvalue");
1522 /* We cannot modify const values */
1523 if (IsQualConst (Expr->Type)) {
1524 Error ("Increment of read-only variable");
1527 /* Get the data type */
1528 Flags = TypeOf (Expr->Type);
1530 /* Push the address if needed */
1533 /* Fetch the value and save it (since it's the result of the expression) */
1534 LoadExpr (CF_NONE, Expr);
1535 g_save (Flags | CF_FORCECHAR);
1537 /* If we have a pointer expression, increment by the size of the type */
1538 if (IsTypePtr (Expr->Type)) {
1539 g_inc (Flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (Expr->Type + 1));
1541 g_inc (Flags | CF_CONST | CF_FORCECHAR, 1);
1544 /* Store the result back */
1547 /* Restore the original value in the primary register */
1548 g_restore (Flags | CF_FORCECHAR);
1550 /* The result is always an expression, no reference */
1551 ED_MakeRValExpr (Expr);
1556 static void PostDec (ExprDesc* Expr)
1557 /* Handle the postdecrement operator */
1563 /* The expression to increment must be an lvalue */
1564 if (!ED_IsLVal (Expr)) {
1565 Error ("Invalid lvalue");
1569 /* We cannot modify const values */
1570 if (IsQualConst (Expr->Type)) {
1571 Error ("Decrement of read-only variable");
1574 /* Get the data type */
1575 Flags = TypeOf (Expr->Type);
1577 /* Push the address if needed */
1580 /* Fetch the value and save it (since it's the result of the expression) */
1581 LoadExpr (CF_NONE, Expr);
1582 g_save (Flags | CF_FORCECHAR);
1584 /* If we have a pointer expression, increment by the size of the type */
1585 if (IsTypePtr (Expr->Type)) {
1586 g_dec (Flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (Expr->Type + 1));
1588 g_dec (Flags | CF_CONST | CF_FORCECHAR, 1);
1591 /* Store the result back */
1594 /* Restore the original value in the primary register */
1595 g_restore (Flags | CF_FORCECHAR);
1597 /* The result is always an expression, no reference */
1598 ED_MakeRValExpr (Expr);
1603 static void UnaryOp (ExprDesc* Expr)
1604 /* Handle unary -/+ and ~ */
1608 /* Remember the operator token and skip it */
1609 token_t Tok = CurTok.Tok;
1612 /* Get the expression */
1615 /* We can only handle integer types */
1616 if (!IsClassInt (Expr->Type)) {
1617 Error ("Argument must have integer type");
1618 ED_MakeConstAbsInt (Expr, 1);
1621 /* Check for a constant expression */
1622 if (ED_IsConstAbs (Expr)) {
1623 /* Value is constant */
1625 case TOK_MINUS: Expr->IVal = -Expr->IVal; break;
1626 case TOK_PLUS: break;
1627 case TOK_COMP: Expr->IVal = ~Expr->IVal; break;
1628 default: Internal ("Unexpected token: %d", Tok);
1631 /* Value is not constant */
1632 LoadExpr (CF_NONE, Expr);
1634 /* Get the type of the expression */
1635 Flags = TypeOf (Expr->Type);
1637 /* Handle the operation */
1639 case TOK_MINUS: g_neg (Flags); break;
1640 case TOK_PLUS: break;
1641 case TOK_COMP: g_com (Flags); break;
1642 default: Internal ("Unexpected token: %d", Tok);
1645 /* The result is a rvalue in the primary */
1646 ED_MakeRValExpr (Expr);
1652 void hie10 (ExprDesc* Expr)
1653 /* Handle ++, --, !, unary - etc. */
1657 switch (CurTok.Tok) {
1675 if (evalexpr (CF_NONE, hie10, Expr) == 0) {
1676 /* Constant expression */
1677 Expr->IVal = !Expr->IVal;
1679 g_bneg (TypeOf (Expr->Type));
1680 ED_MakeRValExpr (Expr);
1681 ED_TestDone (Expr); /* bneg will set cc */
1687 ExprWithCheck (hie10, Expr);
1688 if (ED_IsLVal (Expr) || !(ED_IsLocConst (Expr) || ED_IsLocStack (Expr))) {
1689 /* Not a const, load it into the primary and make it a
1692 LoadExpr (CF_NONE, Expr);
1693 ED_MakeRValExpr (Expr);
1695 /* If the expression is already a pointer to function, the
1696 * additional dereferencing operator must be ignored. A function
1697 * itself is represented as "pointer to function", so any number
1698 * of dereference operators is legal, since the result will
1699 * always be converted to "pointer to function".
1701 if (IsTypeFuncPtr (Expr->Type) || IsTypeFunc (Expr->Type)) {
1702 /* Expression not storable */
1705 if (IsClassPtr (Expr->Type)) {
1706 Expr->Type = Indirect (Expr->Type);
1708 Error ("Illegal indirection");
1710 /* The * operator yields an lvalue */
1717 ExprWithCheck (hie10, Expr);
1718 /* The & operator may be applied to any lvalue, and it may be
1719 * applied to functions, even if they're no lvalues.
1721 if (ED_IsRVal (Expr) && !IsTypeFunc (Expr->Type) && !IsTypeArray (Expr->Type)) {
1722 Error ("Illegal address");
1724 if (ED_IsBitField (Expr)) {
1725 Error ("Cannot take address of bit-field");
1726 /* Do it anyway, just to avoid further warnings */
1727 Expr->Flags &= ~E_BITFIELD;
1729 Expr->Type = PointerTo (Expr->Type);
1730 /* The & operator yields an rvalue */
1737 if (TypeSpecAhead ()) {
1740 Size = CheckedSizeOf (ParseType (T));
1743 /* Remember the output queue pointer */
1747 Size = CheckedSizeOf (Expr->Type);
1748 /* Remove any generated code */
1751 ED_MakeConstAbs (Expr, Size, type_size_t);
1752 ED_MarkAsUntested (Expr);
1756 if (TypeSpecAhead ()) {
1766 /* Handle post increment */
1767 switch (CurTok.Tok) {
1768 case TOK_INC: PostInc (Expr); break;
1769 case TOK_DEC: PostDec (Expr); break;
1780 static void hie_internal (const GenDesc* Ops, /* List of generators */
1782 void (*hienext) (ExprDesc*),
1784 /* Helper function */
1790 token_t Tok; /* The operator token */
1791 unsigned ltype, type;
1792 int lconst; /* Left operand is a constant */
1793 int rconst; /* Right operand is a constant */
1796 ExprWithCheck (hienext, Expr);
1799 while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
1801 /* Tell the caller that we handled it's ops */
1804 /* All operators that call this function expect an int on the lhs */
1805 if (!IsClassInt (Expr->Type)) {
1806 Error ("Integer expression expected");
1807 /* To avoid further errors, make Expr a valid int expression */
1808 ED_MakeConstAbsInt (Expr, 1);
1811 /* Remember the operator token, then skip it */
1815 /* Get the lhs on stack */
1816 GetCodePos (&Mark1);
1817 ltype = TypeOf (Expr->Type);
1818 lconst = ED_IsConstAbs (Expr);
1820 /* Constant value */
1821 GetCodePos (&Mark2);
1822 /* If the operator is commutative, don't push the left side, if
1823 * it's a constant, since we will exchange both operands.
1825 if ((Gen->Flags & GEN_COMM) == 0) {
1826 g_push (ltype | CF_CONST, Expr->IVal);
1829 /* Value not constant */
1830 LoadExpr (CF_NONE, Expr);
1831 GetCodePos (&Mark2);
1835 /* Get the right hand side */
1836 MarkedExprWithCheck (hienext, &Expr2);
1838 /* Check for a constant expression */
1839 rconst = (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2));
1841 /* Not constant, load into the primary */
1842 LoadExpr (CF_NONE, &Expr2);
1845 /* Check the type of the rhs */
1846 if (!IsClassInt (Expr2.Type)) {
1847 Error ("Integer expression expected");
1850 /* Check for const operands */
1851 if (lconst && rconst) {
1853 /* Both operands are constant, remove the generated code */
1854 RemoveCode (&Mark1);
1856 /* Get the type of the result */
1857 Expr->Type = promoteint (Expr->Type, Expr2.Type);
1859 /* Handle the op differently for signed and unsigned types */
1860 if (IsSignSigned (Expr->Type)) {
1862 /* Evaluate the result for signed operands */
1863 signed long Val1 = Expr->IVal;
1864 signed long Val2 = Expr2.IVal;
1867 Expr->IVal = (Val1 | Val2);
1870 Expr->IVal = (Val1 ^ Val2);
1873 Expr->IVal = (Val1 & Val2);
1876 Expr->IVal = (Val1 * Val2);
1880 Error ("Division by zero");
1881 Expr->IVal = 0x7FFFFFFF;
1883 Expr->IVal = (Val1 / Val2);
1888 Error ("Modulo operation with zero");
1891 Expr->IVal = (Val1 % Val2);
1895 Internal ("hie_internal: got token 0x%X\n", Tok);
1899 /* Evaluate the result for unsigned operands */
1900 unsigned long Val1 = Expr->IVal;
1901 unsigned long Val2 = Expr2.IVal;
1904 Expr->IVal = (Val1 | Val2);
1907 Expr->IVal = (Val1 ^ Val2);
1910 Expr->IVal = (Val1 & Val2);
1913 Expr->IVal = (Val1 * Val2);
1917 Error ("Division by zero");
1918 Expr->IVal = 0xFFFFFFFF;
1920 Expr->IVal = (Val1 / Val2);
1925 Error ("Modulo operation with zero");
1928 Expr->IVal = (Val1 % Val2);
1932 Internal ("hie_internal: got token 0x%X\n", Tok);
1936 } else if (lconst && (Gen->Flags & GEN_COMM) && !rconst) {
1938 /* The left side is constant, the right side is not, and the
1939 * operator allows swapping the operands. We haven't pushed the
1940 * left side onto the stack in this case, and will reverse the
1941 * operation because this allows for better code.
1943 unsigned rtype = ltype | CF_CONST;
1944 ltype = TypeOf (Expr2.Type); /* Expr2 is now left */
1946 if ((Gen->Flags & GEN_NOPUSH) == 0) {
1948 ltype |= CF_REG; /* Value is in register */
1951 /* Determine the type of the operation result. */
1952 type |= g_typeadjust (ltype, rtype);
1953 Expr->Type = promoteint (Expr->Type, Expr2.Type);
1956 Gen->Func (type, Expr->IVal);
1958 /* We have a rvalue in the primary now */
1959 ED_MakeRValExpr (Expr);
1963 /* If the right hand side is constant, and the generator function
1964 * expects the lhs in the primary, remove the push of the primary
1967 unsigned rtype = TypeOf (Expr2.Type);
1970 /* Second value is constant - check for div */
1973 if (Tok == TOK_DIV && Expr2.IVal == 0) {
1974 Error ("Division by zero");
1975 } else if (Tok == TOK_MOD && Expr2.IVal == 0) {
1976 Error ("Modulo operation with zero");
1978 if ((Gen->Flags & GEN_NOPUSH) != 0) {
1979 RemoveCode (&Mark2);
1980 ltype |= CF_REG; /* Value is in register */
1984 /* Determine the type of the operation result. */
1985 type |= g_typeadjust (ltype, rtype);
1986 Expr->Type = promoteint (Expr->Type, Expr2.Type);
1989 Gen->Func (type, Expr2.IVal);
1991 /* We have a rvalue in the primary now */
1992 ED_MakeRValExpr (Expr);
1999 static void hie_compare (const GenDesc* Ops, /* List of generators */
2001 void (*hienext) (ExprDesc*))
2002 /* Helper function for the compare operators */
2009 token_t Tok; /* The operator token */
2011 int rconst; /* Operand is a constant */
2014 GetCodePos (&Mark0);
2015 ExprWithCheck (hienext, Expr);
2017 while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
2019 /* Remember the generator function */
2020 void (*GenFunc) (unsigned, unsigned long) = Gen->Func;
2022 /* Remember the operator token, then skip it */
2026 /* Get the lhs on stack */
2027 GetCodePos (&Mark1);
2028 ltype = TypeOf (Expr->Type);
2029 if (ED_IsConstAbs (Expr)) {
2030 /* Constant value */
2031 GetCodePos (&Mark2);
2032 g_push (ltype | CF_CONST, Expr->IVal);
2034 /* Value not constant */
2035 LoadExpr (CF_NONE, Expr);
2036 GetCodePos (&Mark2);
2040 /* Get the right hand side */
2041 MarkedExprWithCheck (hienext, &Expr2);
2043 /* Check for a constant expression */
2044 rconst = (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2));
2046 /* Not constant, load into the primary */
2047 LoadExpr (CF_NONE, &Expr2);
2050 /* Make sure, the types are compatible */
2051 if (IsClassInt (Expr->Type)) {
2052 if (!IsClassInt (Expr2.Type) && !(IsClassPtr(Expr2.Type) && ED_IsNullPtr(Expr))) {
2053 Error ("Incompatible types");
2055 } else if (IsClassPtr (Expr->Type)) {
2056 if (IsClassPtr (Expr2.Type)) {
2057 /* Both pointers are allowed in comparison if they point to
2058 * the same type, or if one of them is a void pointer.
2060 Type* left = Indirect (Expr->Type);
2061 Type* right = Indirect (Expr2.Type);
2062 if (TypeCmp (left, right) < TC_EQUAL && left->C != T_VOID && right->C != T_VOID) {
2063 /* Incomatible pointers */
2064 Error ("Incompatible types");
2066 } else if (!ED_IsNullPtr (&Expr2)) {
2067 Error ("Incompatible types");
2071 /* Check for const operands */
2072 if (ED_IsConstAbs (Expr) && rconst) {
2074 /* If the result is constant, this is suspicious when not in
2075 * preprocessor mode.
2077 WarnConstCompareResult ();
2079 /* Both operands are constant, remove the generated code */
2080 RemoveCode (&Mark1);
2082 /* Determine if this is a signed or unsigned compare */
2083 if (IsClassInt (Expr->Type) && IsSignSigned (Expr->Type) &&
2084 IsClassInt (Expr2.Type) && IsSignSigned (Expr2.Type)) {
2086 /* Evaluate the result for signed operands */
2087 signed long Val1 = Expr->IVal;
2088 signed long Val2 = Expr2.IVal;
2090 case TOK_EQ: Expr->IVal = (Val1 == Val2); break;
2091 case TOK_NE: Expr->IVal = (Val1 != Val2); break;
2092 case TOK_LT: Expr->IVal = (Val1 < Val2); break;
2093 case TOK_LE: Expr->IVal = (Val1 <= Val2); break;
2094 case TOK_GE: Expr->IVal = (Val1 >= Val2); break;
2095 case TOK_GT: Expr->IVal = (Val1 > Val2); break;
2096 default: Internal ("hie_compare: got token 0x%X\n", Tok);
2101 /* Evaluate the result for unsigned operands */
2102 unsigned long Val1 = Expr->IVal;
2103 unsigned long Val2 = Expr2.IVal;
2105 case TOK_EQ: Expr->IVal = (Val1 == Val2); break;
2106 case TOK_NE: Expr->IVal = (Val1 != Val2); break;
2107 case TOK_LT: Expr->IVal = (Val1 < Val2); break;
2108 case TOK_LE: Expr->IVal = (Val1 <= Val2); break;
2109 case TOK_GE: Expr->IVal = (Val1 >= Val2); break;
2110 case TOK_GT: Expr->IVal = (Val1 > Val2); break;
2111 default: Internal ("hie_compare: got token 0x%X\n", Tok);
2117 /* Determine the signedness of the operands */
2118 int LeftSigned = IsSignSigned (Expr->Type);
2119 int RightSigned = IsSignSigned (Expr2.Type);
2121 /* If the right hand side is constant, and the generator function
2122 * expects the lhs in the primary, remove the push of the primary
2128 if ((Gen->Flags & GEN_NOPUSH) != 0) {
2129 RemoveCode (&Mark2);
2130 ltype |= CF_REG; /* Value is in register */
2134 /* Determine the type of the operation. */
2135 if (IsTypeChar (Expr->Type) && rconst) {
2137 /* Left side is unsigned char, right side is constant.
2138 * Determine the minimum and maximum values
2140 int LeftMin, LeftMax;
2148 /* An integer value is always represented as a signed in the
2149 * ExprDesc structure. This may lead to false results below,
2150 * if it is actually unsigned, but interpreted as signed
2151 * because of the representation. Fortunately, in this case,
2152 * the actual value doesn't matter, since it's always greater
2153 * than what can be represented in a char. So correct the
2154 * value accordingly.
2156 if (!RightSigned && Expr2.IVal < 0) {
2157 /* Correct the value so it is an unsigned. It will then
2158 * anyway match one of the cases below.
2160 Expr2.IVal = LeftMax + 1;
2163 /* Comparing a char against a constant may have a constant
2164 * result. Please note: It is not possible to remove the code
2165 * for the compare alltogether, because it may have side
2171 if (Expr2.IVal < LeftMin || Expr2.IVal > LeftMax) {
2172 ED_MakeConstAbsInt (Expr, 0);
2173 WarnConstCompareResult ();
2179 if (Expr2.IVal < LeftMin || Expr2.IVal > LeftMax) {
2180 ED_MakeConstAbsInt (Expr, 1);
2181 WarnConstCompareResult ();
2187 if (Expr2.IVal <= LeftMin || Expr2.IVal > LeftMax) {
2188 ED_MakeConstAbsInt (Expr, Expr2.IVal > LeftMax);
2189 WarnConstCompareResult ();
2195 if (Expr2.IVal < LeftMin || Expr2.IVal >= LeftMax) {
2196 ED_MakeConstAbsInt (Expr, Expr2.IVal >= LeftMax);
2197 WarnConstCompareResult ();
2203 if (Expr2.IVal <= LeftMin || Expr2.IVal > LeftMax) {
2204 ED_MakeConstAbsInt (Expr, Expr2.IVal <= LeftMin);
2205 WarnConstCompareResult ();
2211 if (Expr2.IVal < LeftMin || Expr2.IVal >= LeftMax) {
2212 ED_MakeConstAbsInt (Expr, Expr2.IVal < LeftMin);
2213 WarnConstCompareResult ();
2219 Internal ("hie_compare: got token 0x%X\n", Tok);
2222 /* If the result is not already constant (as evaluated in the
2223 * switch above), we can execute the operation as a char op,
2224 * since the right side constant is in a valid range.
2226 flags |= (CF_CHAR | CF_FORCECHAR);
2228 flags |= CF_UNSIGNED;
2231 } else if (IsTypeChar (Expr->Type) && IsTypeChar (Expr2.Type) &&
2232 GetSignedness (Expr->Type) == GetSignedness (Expr2.Type)) {
2234 /* Both are chars with the same signedness. We can encode the
2235 * operation as a char operation.
2239 flags |= CF_FORCECHAR;
2242 flags |= CF_UNSIGNED;
2245 unsigned rtype = TypeOf (Expr2.Type) | (flags & CF_CONST);
2246 flags |= g_typeadjust (ltype, rtype);
2249 /* If the left side is an unsigned and the right is a constant,
2250 * we may be able to change the compares to something more
2253 if (!LeftSigned && rconst) {
2258 if (Expr2.IVal == 1) {
2259 /* An unsigned compare to one means that the value
2268 if (Expr2.IVal == 0) {
2269 /* An unsigned compare to zero means that the value
2277 if (Expr2.IVal == 1) {
2278 /* An unsigned compare to one means that the value
2287 if (Expr2.IVal == 0) {
2288 /* An unsigned compare to zero means that the value
2303 GenFunc (flags, Expr2.IVal);
2305 /* The result is an rvalue in the primary */
2306 ED_MakeRValExpr (Expr);
2309 /* Result type is always int */
2310 Expr->Type = type_int;
2312 Done: /* Condition codes are set */
2319 static void hie9 (ExprDesc *Expr)
2320 /* Process * and / operators. */
2322 static const GenDesc hie9_ops[] = {
2323 { TOK_STAR, GEN_NOPUSH | GEN_COMM, g_mul },
2324 { TOK_DIV, GEN_NOPUSH, g_div },
2325 { TOK_MOD, GEN_NOPUSH, g_mod },
2326 { TOK_INVALID, 0, 0 }
2330 hie_internal (hie9_ops, Expr, hie10, &UsedGen);
2335 static void parseadd (ExprDesc* Expr)
2336 /* Parse an expression with the binary plus operator. Expr contains the
2337 * unprocessed left hand side of the expression and will contain the
2338 * result of the expression on return.
2342 unsigned flags; /* Operation flags */
2343 CodeMark Mark; /* Remember code position */
2344 Type* lhst; /* Type of left hand side */
2345 Type* rhst; /* Type of right hand side */
2348 /* Skip the PLUS token */
2351 /* Get the left hand side type, initialize operation flags */
2355 /* Check for constness on both sides */
2356 if (ED_IsConst (Expr)) {
2358 /* The left hand side is a constant of some sort. Good. Get rhs */
2359 ExprWithCheck (hie9, &Expr2);
2360 if (ED_IsConstAbs (&Expr2)) {
2362 /* Right hand side is a constant numeric value. Get the rhs type */
2365 /* Both expressions are constants. Check for pointer arithmetic */
2366 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2367 /* Left is pointer, right is int, must scale rhs */
2368 Expr->IVal += Expr2.IVal * CheckedPSizeOf (lhst);
2369 /* Result type is a pointer */
2370 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2371 /* Left is int, right is pointer, must scale lhs */
2372 Expr->IVal = Expr->IVal * CheckedPSizeOf (rhst) + Expr2.IVal;
2373 /* Result type is a pointer */
2374 Expr->Type = Expr2.Type;
2375 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2376 /* Integer addition */
2377 Expr->IVal += Expr2.IVal;
2378 typeadjust (Expr, &Expr2, 1);
2381 Error ("Invalid operands for binary operator `+'");
2386 /* lhs is a constant and rhs is not constant. Load rhs into
2389 LoadExpr (CF_NONE, &Expr2);
2391 /* Beware: The check above (for lhs) lets not only pass numeric
2392 * constants, but also constant addresses (labels), maybe even
2393 * with an offset. We have to check for that here.
2396 /* First, get the rhs type. */
2400 if (ED_IsLocAbs (Expr)) {
2401 /* A numerical constant */
2404 /* Constant address label */
2405 flags |= GlobalModeFlags (Expr) | CF_CONSTADDR;
2408 /* Check for pointer arithmetic */
2409 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2410 /* Left is pointer, right is int, must scale rhs */
2411 g_scale (CF_INT, CheckedPSizeOf (lhst));
2412 /* Operate on pointers, result type is a pointer */
2414 /* Generate the code for the add */
2415 if (ED_GetLoc (Expr) == E_LOC_ABS) {
2416 /* Numeric constant */
2417 g_inc (flags, Expr->IVal);
2419 /* Constant address */
2420 g_addaddr_static (flags, Expr->Name, Expr->IVal);
2422 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2424 /* Left is int, right is pointer, must scale lhs. */
2425 unsigned ScaleFactor = CheckedPSizeOf (rhst);
2427 /* Operate on pointers, result type is a pointer */
2429 Expr->Type = Expr2.Type;
2431 /* Since we do already have rhs in the primary, if lhs is
2432 * not a numeric constant, and the scale factor is not one
2433 * (no scaling), we must take the long way over the stack.
2435 if (ED_IsLocAbs (Expr)) {
2436 /* Numeric constant, scale lhs */
2437 Expr->IVal *= ScaleFactor;
2438 /* Generate the code for the add */
2439 g_inc (flags, Expr->IVal);
2440 } else if (ScaleFactor == 1) {
2441 /* Constant address but no need to scale */
2442 g_addaddr_static (flags, Expr->Name, Expr->IVal);
2444 /* Constant address that must be scaled */
2445 g_push (TypeOf (Expr2.Type), 0); /* rhs --> stack */
2446 g_getimmed (flags, Expr->Name, Expr->IVal);
2447 g_scale (CF_PTR, ScaleFactor);
2450 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2451 /* Integer addition */
2452 flags |= typeadjust (Expr, &Expr2, 1);
2453 /* Generate the code for the add */
2454 if (ED_IsLocAbs (Expr)) {
2455 /* Numeric constant */
2456 g_inc (flags, Expr->IVal);
2458 /* Constant address */
2459 g_addaddr_static (flags, Expr->Name, Expr->IVal);
2463 Error ("Invalid operands for binary operator `+'");
2467 /* Result is a rvalue in primary register */
2468 ED_MakeRValExpr (Expr);
2473 /* Left hand side is not constant. Get the value onto the stack. */
2474 LoadExpr (CF_NONE, Expr); /* --> primary register */
2476 g_push (TypeOf (Expr->Type), 0); /* --> stack */
2478 /* Evaluate the rhs */
2479 MarkedExprWithCheck (hie9, &Expr2);
2481 /* Check for a constant rhs expression */
2482 if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) {
2484 /* Right hand side is a constant. Get the rhs type */
2487 /* Remove pushed value from stack */
2490 /* Check for pointer arithmetic */
2491 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2492 /* Left is pointer, right is int, must scale rhs */
2493 Expr2.IVal *= CheckedPSizeOf (lhst);
2494 /* Operate on pointers, result type is a pointer */
2496 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2497 /* Left is int, right is pointer, must scale lhs (ptr only) */
2498 g_scale (CF_INT | CF_CONST, CheckedPSizeOf (rhst));
2499 /* Operate on pointers, result type is a pointer */
2501 Expr->Type = Expr2.Type;
2502 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2503 /* Integer addition */
2504 flags = typeadjust (Expr, &Expr2, 1);
2507 Error ("Invalid operands for binary operator `+'");
2511 /* Generate code for the add */
2512 g_inc (flags | CF_CONST, Expr2.IVal);
2516 /* Not constant, load into the primary */
2517 LoadExpr (CF_NONE, &Expr2);
2519 /* lhs and rhs are not constant. Get the rhs type. */
2522 /* Check for pointer arithmetic */
2523 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2524 /* Left is pointer, right is int, must scale rhs */
2525 g_scale (CF_INT, CheckedPSizeOf (lhst));
2526 /* Operate on pointers, result type is a pointer */
2528 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2529 /* Left is int, right is pointer, must scale lhs */
2530 g_tosint (TypeOf (rhst)); /* Make sure, TOS is int */
2531 g_swap (CF_INT); /* Swap TOS and primary */
2532 g_scale (CF_INT, CheckedPSizeOf (rhst));
2533 /* Operate on pointers, result type is a pointer */
2535 Expr->Type = Expr2.Type;
2536 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2537 /* Integer addition. Note: Result is never constant.
2538 * Problem here is that typeadjust does not know if the
2539 * variable is an rvalue or lvalue, so if both operands
2540 * are dereferenced constant numeric addresses, typeadjust
2541 * thinks the operation works on constants. Removing
2542 * CF_CONST here means handling the symptoms, however, the
2543 * whole parser is such a mess that I fear to break anything
2544 * when trying to apply another solution.
2546 flags = typeadjust (Expr, &Expr2, 0) & ~CF_CONST;
2549 Error ("Invalid operands for binary operator `+'");
2553 /* Generate code for the add */
2558 /* Result is a rvalue in primary register */
2559 ED_MakeRValExpr (Expr);
2562 /* Condition codes not set */
2563 ED_MarkAsUntested (Expr);
2569 static void parsesub (ExprDesc* Expr)
2570 /* Parse an expression with the binary minus operator. Expr contains the
2571 * unprocessed left hand side of the expression and will contain the
2572 * result of the expression on return.
2576 unsigned flags; /* Operation flags */
2577 Type* lhst; /* Type of left hand side */
2578 Type* rhst; /* Type of right hand side */
2579 CodeMark Mark1; /* Save position of output queue */
2580 CodeMark Mark2; /* Another position in the queue */
2581 int rscale; /* Scale factor for the result */
2584 /* Skip the MINUS token */
2587 /* Get the left hand side type, initialize operation flags */
2589 rscale = 1; /* Scale by 1, that is, don't scale */
2591 /* Remember the output queue position, then bring the value onto the stack */
2592 GetCodePos (&Mark1);
2593 LoadExpr (CF_NONE, Expr); /* --> primary register */
2594 GetCodePos (&Mark2);
2595 g_push (TypeOf (lhst), 0); /* --> stack */
2597 /* Parse the right hand side */
2598 MarkedExprWithCheck (hie9, &Expr2);
2600 /* Check for a constant rhs expression */
2601 if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) {
2603 /* The right hand side is constant. Get the rhs type. */
2606 /* Check left hand side */
2607 if (ED_IsConstAbs (Expr)) {
2609 /* Both sides are constant, remove generated code */
2610 RemoveCode (&Mark1);
2612 /* Check for pointer arithmetic */
2613 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2614 /* Left is pointer, right is int, must scale rhs */
2615 Expr->IVal -= Expr2.IVal * CheckedPSizeOf (lhst);
2616 /* Operate on pointers, result type is a pointer */
2617 } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2618 /* Left is pointer, right is pointer, must scale result */
2619 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2620 Error ("Incompatible pointer types");
2622 Expr->IVal = (Expr->IVal - Expr2.IVal) /
2623 CheckedPSizeOf (lhst);
2625 /* Operate on pointers, result type is an integer */
2626 Expr->Type = type_int;
2627 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2628 /* Integer subtraction */
2629 typeadjust (Expr, &Expr2, 1);
2630 Expr->IVal -= Expr2.IVal;
2633 Error ("Invalid operands for binary operator `-'");
2636 /* Result is constant, condition codes not set */
2637 ED_MarkAsUntested (Expr);
2641 /* Left hand side is not constant, right hand side is.
2642 * Remove pushed value from stack.
2644 RemoveCode (&Mark2);
2646 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2647 /* Left is pointer, right is int, must scale rhs */
2648 Expr2.IVal *= CheckedPSizeOf (lhst);
2649 /* Operate on pointers, result type is a pointer */
2651 } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2652 /* Left is pointer, right is pointer, must scale result */
2653 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2654 Error ("Incompatible pointer types");
2656 rscale = CheckedPSizeOf (lhst);
2658 /* Operate on pointers, result type is an integer */
2660 Expr->Type = type_int;
2661 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2662 /* Integer subtraction */
2663 flags = typeadjust (Expr, &Expr2, 1);
2666 Error ("Invalid operands for binary operator `-'");
2670 /* Do the subtraction */
2671 g_dec (flags | CF_CONST, Expr2.IVal);
2673 /* If this was a pointer subtraction, we must scale the result */
2675 g_scale (flags, -rscale);
2678 /* Result is a rvalue in the primary register */
2679 ED_MakeRValExpr (Expr);
2680 ED_MarkAsUntested (Expr);
2686 /* Not constant, load into the primary */
2687 LoadExpr (CF_NONE, &Expr2);
2689 /* Right hand side is not constant. Get the rhs type. */
2692 /* Check for pointer arithmetic */
2693 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2694 /* Left is pointer, right is int, must scale rhs */
2695 g_scale (CF_INT, CheckedPSizeOf (lhst));
2696 /* Operate on pointers, result type is a pointer */
2698 } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2699 /* Left is pointer, right is pointer, must scale result */
2700 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2701 Error ("Incompatible pointer types");
2703 rscale = CheckedPSizeOf (lhst);
2705 /* Operate on pointers, result type is an integer */
2707 Expr->Type = type_int;
2708 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2709 /* Integer subtraction. If the left hand side descriptor says that
2710 * the lhs is const, we have to remove this mark, since this is no
2711 * longer true, lhs is on stack instead.
2713 if (ED_IsLocAbs (Expr)) {
2714 ED_MakeRValExpr (Expr);
2716 /* Adjust operand types */
2717 flags = typeadjust (Expr, &Expr2, 0);
2720 Error ("Invalid operands for binary operator `-'");
2724 /* Generate code for the sub (the & is a hack here) */
2725 g_sub (flags & ~CF_CONST, 0);
2727 /* If this was a pointer subtraction, we must scale the result */
2729 g_scale (flags, -rscale);
2732 /* Result is a rvalue in the primary register */
2733 ED_MakeRValExpr (Expr);
2734 ED_MarkAsUntested (Expr);
2740 void hie8 (ExprDesc* Expr)
2741 /* Process + and - binary operators. */
2743 ExprWithCheck (hie9, Expr);
2744 while (CurTok.Tok == TOK_PLUS || CurTok.Tok == TOK_MINUS) {
2745 if (CurTok.Tok == TOK_PLUS) {
2755 static void hie6 (ExprDesc* Expr)
2756 /* Handle greater-than type comparators */
2758 static const GenDesc hie6_ops [] = {
2759 { TOK_LT, GEN_NOPUSH, g_lt },
2760 { TOK_LE, GEN_NOPUSH, g_le },
2761 { TOK_GE, GEN_NOPUSH, g_ge },
2762 { TOK_GT, GEN_NOPUSH, g_gt },
2763 { TOK_INVALID, 0, 0 }
2765 hie_compare (hie6_ops, Expr, ShiftExpr);
2770 static void hie5 (ExprDesc* Expr)
2771 /* Handle == and != */
2773 static const GenDesc hie5_ops[] = {
2774 { TOK_EQ, GEN_NOPUSH, g_eq },
2775 { TOK_NE, GEN_NOPUSH, g_ne },
2776 { TOK_INVALID, 0, 0 }
2778 hie_compare (hie5_ops, Expr, hie6);
2783 static void hie4 (ExprDesc* Expr)
2784 /* Handle & (bitwise and) */
2786 static const GenDesc hie4_ops[] = {
2787 { TOK_AND, GEN_NOPUSH | GEN_COMM, g_and },
2788 { TOK_INVALID, 0, 0 }
2792 hie_internal (hie4_ops, Expr, hie5, &UsedGen);
2797 static void hie3 (ExprDesc* Expr)
2798 /* Handle ^ (bitwise exclusive or) */
2800 static const GenDesc hie3_ops[] = {
2801 { TOK_XOR, GEN_NOPUSH | GEN_COMM, g_xor },
2802 { TOK_INVALID, 0, 0 }
2806 hie_internal (hie3_ops, Expr, hie4, &UsedGen);
2811 static void hie2 (ExprDesc* Expr)
2812 /* Handle | (bitwise or) */
2814 static const GenDesc hie2_ops[] = {
2815 { TOK_OR, GEN_NOPUSH | GEN_COMM, g_or },
2816 { TOK_INVALID, 0, 0 }
2820 hie_internal (hie2_ops, Expr, hie3, &UsedGen);
2825 static void hieAndPP (ExprDesc* Expr)
2826 /* Process "exp && exp" in preprocessor mode (that is, when the parser is
2827 * called recursively from the preprocessor.
2832 ConstAbsIntExpr (hie2, Expr);
2833 while (CurTok.Tok == TOK_BOOL_AND) {
2839 ConstAbsIntExpr (hie2, &Expr2);
2841 /* Combine the two */
2842 Expr->IVal = (Expr->IVal && Expr2.IVal);
2848 static void hieOrPP (ExprDesc *Expr)
2849 /* Process "exp || exp" in preprocessor mode (that is, when the parser is
2850 * called recursively from the preprocessor.
2855 ConstAbsIntExpr (hieAndPP, Expr);
2856 while (CurTok.Tok == TOK_BOOL_OR) {
2862 ConstAbsIntExpr (hieAndPP, &Expr2);
2864 /* Combine the two */
2865 Expr->IVal = (Expr->IVal || Expr2.IVal);
2871 static void hieAnd (ExprDesc* Expr, unsigned TrueLab, int* BoolOp)
2872 /* Process "exp && exp" */
2877 ExprWithCheck (hie2, Expr);
2878 if (CurTok.Tok == TOK_BOOL_AND) {
2880 /* Tell our caller that we're evaluating a boolean */
2883 /* Get a label that we will use for false expressions */
2884 FalseLab = GetLocalLabel ();
2886 /* If the expr hasn't set condition codes, set the force-test flag */
2887 if (!ED_IsTested (Expr)) {
2888 ED_MarkForTest (Expr);
2891 /* Load the value */
2892 LoadExpr (CF_FORCECHAR, Expr);
2894 /* Generate the jump */
2895 g_falsejump (CF_NONE, FalseLab);
2897 /* Parse more boolean and's */
2898 while (CurTok.Tok == TOK_BOOL_AND) {
2905 if (!ED_IsTested (&Expr2)) {
2906 ED_MarkForTest (&Expr2);
2908 LoadExpr (CF_FORCECHAR, &Expr2);
2910 /* Do short circuit evaluation */
2911 if (CurTok.Tok == TOK_BOOL_AND) {
2912 g_falsejump (CF_NONE, FalseLab);
2914 /* Last expression - will evaluate to true */
2915 g_truejump (CF_NONE, TrueLab);
2919 /* Define the false jump label here */
2920 g_defcodelabel (FalseLab);
2922 /* The result is an rvalue in primary */
2923 ED_MakeRValExpr (Expr);
2924 ED_TestDone (Expr); /* Condition codes are set */
2930 static void hieOr (ExprDesc *Expr)
2931 /* Process "exp || exp". */
2934 int BoolOp = 0; /* Did we have a boolean op? */
2935 int AndOp; /* Did we have a && operation? */
2936 unsigned TrueLab; /* Jump to this label if true */
2940 TrueLab = GetLocalLabel ();
2942 /* Call the next level parser */
2943 hieAnd (Expr, TrueLab, &BoolOp);
2945 /* Any boolean or's? */
2946 if (CurTok.Tok == TOK_BOOL_OR) {
2948 /* If the expr hasn't set condition codes, set the force-test flag */
2949 if (!ED_IsTested (Expr)) {
2950 ED_MarkForTest (Expr);
2953 /* Get first expr */
2954 LoadExpr (CF_FORCECHAR, Expr);
2956 /* For each expression jump to TrueLab if true. Beware: If we
2957 * had && operators, the jump is already in place!
2960 g_truejump (CF_NONE, TrueLab);
2963 /* Remember that we had a boolean op */
2966 /* while there's more expr */
2967 while (CurTok.Tok == TOK_BOOL_OR) {
2974 hieAnd (&Expr2, TrueLab, &AndOp);
2975 if (!ED_IsTested (&Expr2)) {
2976 ED_MarkForTest (&Expr2);
2978 LoadExpr (CF_FORCECHAR, &Expr2);
2980 /* If there is more to come, add shortcut boolean eval. */
2981 g_truejump (CF_NONE, TrueLab);
2985 /* The result is an rvalue in primary */
2986 ED_MakeRValExpr (Expr);
2987 ED_TestDone (Expr); /* Condition codes are set */
2990 /* If we really had boolean ops, generate the end sequence */
2992 DoneLab = GetLocalLabel ();
2993 g_getimmed (CF_INT | CF_CONST, 0, 0); /* Load FALSE */
2994 g_falsejump (CF_NONE, DoneLab);
2995 g_defcodelabel (TrueLab);
2996 g_getimmed (CF_INT | CF_CONST, 1, 0); /* Load TRUE */
2997 g_defcodelabel (DoneLab);
3003 static void hieQuest (ExprDesc* Expr)
3004 /* Parse the ternary operator */
3008 CodeMark TrueCodeEnd;
3009 ExprDesc Expr2; /* Expression 2 */
3010 ExprDesc Expr3; /* Expression 3 */
3011 int Expr2IsNULL; /* Expression 2 is a NULL pointer */
3012 int Expr3IsNULL; /* Expression 3 is a NULL pointer */
3013 Type* ResultType; /* Type of result */
3016 /* Call the lower level eval routine */
3017 if (Preprocessing) {
3018 ExprWithCheck (hieOrPP, Expr);
3020 ExprWithCheck (hieOr, Expr);
3023 /* Check if it's a ternary expression */
3024 if (CurTok.Tok == TOK_QUEST) {
3026 if (!ED_IsTested (Expr)) {
3027 /* Condition codes not set, request a test */
3028 ED_MarkForTest (Expr);
3030 LoadExpr (CF_NONE, Expr);
3031 FalseLab = GetLocalLabel ();
3032 g_falsejump (CF_NONE, FalseLab);
3034 /* Parse second expression. Remember for later if it is a NULL pointer
3035 * expression, then load it into the primary.
3037 ExprWithCheck (hie1, &Expr2);
3038 Expr2IsNULL = ED_IsNullPtr (&Expr2);
3039 if (!IsTypeVoid (Expr2.Type)) {
3040 /* Load it into the primary */
3041 LoadExpr (CF_NONE, &Expr2);
3042 ED_MakeRValExpr (&Expr2);
3043 Expr2.Type = PtrConversion (Expr2.Type);
3046 /* Remember the current code position */
3047 GetCodePos (&TrueCodeEnd);
3049 /* Jump around the evaluation of the third expression */
3050 TrueLab = GetLocalLabel ();
3054 /* Jump here if the first expression was false */
3055 g_defcodelabel (FalseLab);
3057 /* Parse third expression. Remember for later if it is a NULL pointer
3058 * expression, then load it into the primary.
3060 ExprWithCheck (hie1, &Expr3);
3061 Expr3IsNULL = ED_IsNullPtr (&Expr3);
3062 if (!IsTypeVoid (Expr3.Type)) {
3063 /* Load it into the primary */
3064 LoadExpr (CF_NONE, &Expr3);
3065 ED_MakeRValExpr (&Expr3);
3066 Expr3.Type = PtrConversion (Expr3.Type);
3069 /* Check if any conversions are needed, if so, do them.
3070 * Conversion rules for ?: expression are:
3071 * - if both expressions are int expressions, default promotion
3072 * rules for ints apply.
3073 * - if both expressions are pointers of the same type, the
3074 * result of the expression is of this type.
3075 * - if one of the expressions is a pointer and the other is
3076 * a zero constant, the resulting type is that of the pointer
3078 * - if both expressions are void expressions, the result is of
3080 * - all other cases are flagged by an error.
3082 if (IsClassInt (Expr2.Type) && IsClassInt (Expr3.Type)) {
3084 CodeMark CvtCodeStart;
3085 CodeMark CvtCodeEnd;
3088 /* Get common type */
3089 ResultType = promoteint (Expr2.Type, Expr3.Type);
3091 /* Convert the third expression to this type if needed */
3092 TypeConversion (&Expr3, ResultType);
3094 /* Emit conversion code for the second expression, but remember
3095 * where it starts end ends.
3097 GetCodePos (&CvtCodeStart);
3098 TypeConversion (&Expr2, ResultType);
3099 GetCodePos (&CvtCodeEnd);
3101 /* If we had conversion code, move it to the right place */
3102 if (!CodeRangeIsEmpty (&CvtCodeStart, &CvtCodeEnd)) {
3103 MoveCode (&CvtCodeStart, &CvtCodeEnd, &TrueCodeEnd);
3106 } else if (IsClassPtr (Expr2.Type) && IsClassPtr (Expr3.Type)) {
3107 /* Must point to same type */
3108 if (TypeCmp (Indirect (Expr2.Type), Indirect (Expr3.Type)) < TC_EQUAL) {
3109 Error ("Incompatible pointer types");
3111 /* Result has the common type */
3112 ResultType = Expr2.Type;
3113 } else if (IsClassPtr (Expr2.Type) && Expr3IsNULL) {
3114 /* Result type is pointer, no cast needed */
3115 ResultType = Expr2.Type;
3116 } else if (Expr2IsNULL && IsClassPtr (Expr3.Type)) {
3117 /* Result type is pointer, no cast needed */
3118 ResultType = Expr3.Type;
3119 } else if (IsTypeVoid (Expr2.Type) && IsTypeVoid (Expr3.Type)) {
3120 /* Result type is void */
3121 ResultType = Expr3.Type;
3123 Error ("Incompatible types");
3124 ResultType = Expr2.Type; /* Doesn't matter here */
3127 /* Define the final label */
3128 g_defcodelabel (TrueLab);
3130 /* Setup the target expression */
3131 ED_MakeRValExpr (Expr);
3132 Expr->Type = ResultType;
3138 static void opeq (const GenDesc* Gen, ExprDesc* Expr, const char* Op)
3139 /* Process "op=" operators. */
3146 /* op= can only be used with lvalues */
3147 if (!ED_IsLVal (Expr)) {
3148 Error ("Invalid lvalue in assignment");
3152 /* The left side must not be const qualified */
3153 if (IsQualConst (Expr->Type)) {
3154 Error ("Assignment to const");
3157 /* There must be an integer or pointer on the left side */
3158 if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
3159 Error ("Invalid left operand type");
3160 /* Continue. Wrong code will be generated, but the compiler won't
3161 * break, so this is the best error recovery.
3165 /* Skip the operator token */
3168 /* Determine the type of the lhs */
3169 flags = TypeOf (Expr->Type);
3170 MustScale = (Gen->Func == g_add || Gen->Func == g_sub) && IsTypePtr (Expr->Type);
3172 /* Get the lhs address on stack (if needed) */
3175 /* Fetch the lhs into the primary register if needed */
3176 LoadExpr (CF_NONE, Expr);
3178 /* Bring the lhs on stack */
3182 /* Evaluate the rhs */
3183 MarkedExprWithCheck (hie1, &Expr2);
3185 /* The rhs must be an integer (or a float, but we don't support that yet */
3186 if (!IsClassInt (Expr2.Type)) {
3187 Error ("Invalid right operand for binary operator `%s'", Op);
3188 /* Continue. Wrong code will be generated, but the compiler won't
3189 * break, so this is the best error recovery.
3193 /* Check for a constant expression */
3194 if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) {
3195 /* The resulting value is a constant. If the generator has the NOPUSH
3196 * flag set, don't push the lhs.
3198 if (Gen->Flags & GEN_NOPUSH) {
3202 /* lhs is a pointer, scale rhs */
3203 Expr2.IVal *= CheckedSizeOf (Expr->Type+1);
3206 /* If the lhs is character sized, the operation may be later done
3209 if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
3210 flags |= CF_FORCECHAR;
3213 /* Special handling for add and sub - some sort of a hack, but short code */
3214 if (Gen->Func == g_add) {
3215 g_inc (flags | CF_CONST, Expr2.IVal);
3216 } else if (Gen->Func == g_sub) {
3217 g_dec (flags | CF_CONST, Expr2.IVal);
3219 if (Expr2.IVal == 0) {
3220 /* Check for div by zero/mod by zero */
3221 if (Gen->Func == g_div) {
3222 Error ("Division by zero");
3223 } else if (Gen->Func == g_mod) {
3224 Error ("Modulo operation with zero");
3227 Gen->Func (flags | CF_CONST, Expr2.IVal);
3231 /* rhs is not constant. Load into the primary */
3232 LoadExpr (CF_NONE, &Expr2);
3234 /* lhs is a pointer, scale rhs */
3235 g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Expr->Type+1));
3238 /* If the lhs is character sized, the operation may be later done
3241 if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
3242 flags |= CF_FORCECHAR;
3245 /* Adjust the types of the operands if needed */
3246 Gen->Func (g_typeadjust (flags, TypeOf (Expr2.Type)), 0);
3249 ED_MakeRValExpr (Expr);
3254 static void addsubeq (const GenDesc* Gen, ExprDesc *Expr, const char* Op)
3255 /* Process the += and -= operators */
3263 /* We're currently only able to handle some adressing modes */
3264 if (ED_GetLoc (Expr) == E_LOC_EXPR || ED_GetLoc (Expr) == E_LOC_PRIMARY) {
3265 /* Use generic routine */
3266 opeq (Gen, Expr, Op);
3270 /* We must have an lvalue */
3271 if (ED_IsRVal (Expr)) {
3272 Error ("Invalid lvalue in assignment");
3276 /* The left side must not be const qualified */
3277 if (IsQualConst (Expr->Type)) {
3278 Error ("Assignment to const");
3281 /* There must be an integer or pointer on the left side */
3282 if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
3283 Error ("Invalid left operand type");
3284 /* Continue. Wrong code will be generated, but the compiler won't
3285 * break, so this is the best error recovery.
3289 /* Skip the operator */
3292 /* Check if we have a pointer expression and must scale rhs */
3293 MustScale = IsTypePtr (Expr->Type);
3295 /* Initialize the code generator flags */
3299 /* Evaluate the rhs. We expect an integer here, since float is not
3303 if (!IsClassInt (Expr2.Type)) {
3304 Error ("Invalid right operand for binary operator `%s'", Op);
3305 /* Continue. Wrong code will be generated, but the compiler won't
3306 * break, so this is the best error recovery.
3309 if (ED_IsConstAbs (&Expr2)) {
3310 /* The resulting value is a constant. Scale it. */
3312 Expr2.IVal *= CheckedSizeOf (Indirect (Expr->Type));
3317 /* Not constant, load into the primary */
3318 LoadExpr (CF_NONE, &Expr2);
3320 /* lhs is a pointer, scale rhs */
3321 g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Indirect (Expr->Type)));
3325 /* Setup the code generator flags */
3326 lflags |= TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR;
3327 rflags |= TypeOf (Expr2.Type) | CF_FORCECHAR;
3329 /* Convert the type of the lhs to that of the rhs */
3330 g_typecast (lflags, rflags);
3332 /* Output apropriate code depending on the location */
3333 switch (ED_GetLoc (Expr)) {
3336 /* Absolute: numeric address or const */
3337 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3338 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3340 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3345 /* Global variable */
3346 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3347 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3349 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3355 /* Static variable or literal in the literal pool */
3356 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3357 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3359 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3363 case E_LOC_REGISTER:
3364 /* Register variable */
3365 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3366 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3368 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3373 /* Value on the stack */
3374 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3375 g_addeqlocal (lflags, Expr->IVal, Expr2.IVal);
3377 g_subeqlocal (lflags, Expr->IVal, Expr2.IVal);
3382 Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
3385 /* Expression is a rvalue in the primary now */
3386 ED_MakeRValExpr (Expr);
3391 void hie1 (ExprDesc* Expr)
3392 /* Parse first level of expression hierarchy. */
3395 switch (CurTok.Tok) {
3401 case TOK_PLUS_ASSIGN:
3402 addsubeq (&GenPASGN, Expr, "+=");
3405 case TOK_MINUS_ASSIGN:
3406 addsubeq (&GenSASGN, Expr, "-=");
3409 case TOK_MUL_ASSIGN:
3410 opeq (&GenMASGN, Expr, "*=");
3413 case TOK_DIV_ASSIGN:
3414 opeq (&GenDASGN, Expr, "/=");
3417 case TOK_MOD_ASSIGN:
3418 opeq (&GenMOASGN, Expr, "%=");
3421 case TOK_SHL_ASSIGN:
3422 opeq (&GenSLASGN, Expr, "<<=");
3425 case TOK_SHR_ASSIGN:
3426 opeq (&GenSRASGN, Expr, ">>=");
3429 case TOK_AND_ASSIGN:
3430 opeq (&GenAASGN, Expr, "&=");
3433 case TOK_XOR_ASSIGN:
3434 opeq (&GenXOASGN, Expr, "^=");
3438 opeq (&GenOASGN, Expr, "|=");
3448 void hie0 (ExprDesc *Expr)
3449 /* Parse comma operator. */
3452 while (CurTok.Tok == TOK_COMMA) {
3460 int evalexpr (unsigned Flags, void (*Func) (ExprDesc*), ExprDesc* Expr)
3461 /* Will evaluate an expression via the given function. If the result is a
3462 * constant, 0 is returned and the value is put in the Expr struct. If the
3463 * result is not constant, LoadExpr is called to bring the value into the
3464 * primary register and 1 is returned.
3468 ExprWithCheck (Func, Expr);
3470 /* Check for a constant expression */
3471 if (ED_IsConstAbs (Expr)) {
3472 /* Constant expression */
3475 /* Not constant, load into the primary */
3476 LoadExpr (Flags, Expr);
3483 void Expression0 (ExprDesc* Expr)
3484 /* Evaluate an expression via hie0 and put the result into the primary register */
3486 ExprWithCheck (hie0, Expr);
3487 LoadExpr (CF_NONE, Expr);
3492 void ConstExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3493 /* Will evaluate an expression via the given function. If the result is not
3494 * a constant of some sort, a diagnostic will be printed, and the value is
3495 * replaced by a constant one to make sure there are no internal errors that
3496 * result from this input error.
3499 ExprWithCheck (Func, Expr);
3500 if (!ED_IsConst (Expr)) {
3501 Error ("Constant expression expected");
3502 /* To avoid any compiler errors, make the expression a valid const */
3503 ED_MakeConstAbsInt (Expr, 1);
3509 void BoolExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3510 /* Will evaluate an expression via the given function. If the result is not
3511 * something that may be evaluated in a boolean context, a diagnostic will be
3512 * printed, and the value is replaced by a constant one to make sure there
3513 * are no internal errors that result from this input error.
3516 ExprWithCheck (Func, Expr);
3517 if (!ED_IsBool (Expr)) {
3518 Error ("Boolean expression expected");
3519 /* To avoid any compiler errors, make the expression a valid int */
3520 ED_MakeConstAbsInt (Expr, 1);
3526 void ConstAbsIntExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3527 /* Will evaluate an expression via the given function. If the result is not
3528 * a constant numeric integer value, a diagnostic will be printed, and the
3529 * value is replaced by a constant one to make sure there are no internal
3530 * errors that result from this input error.
3533 ExprWithCheck (Func, Expr);
3534 if (!ED_IsConstAbsInt (Expr)) {
3535 Error ("Constant integer expression expected");
3536 /* To avoid any compiler errors, make the expression a valid const */
3537 ED_MakeConstAbsInt (Expr, 1);