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 */
52 /* Map a generator function and its attributes to a token */
54 token_t Tok; /* Token to map to */
55 unsigned Flags; /* Flags for generator function */
56 void (*Func) (unsigned, unsigned long); /* Generator func */
59 /* Descriptors for the operations */
60 static GenDesc GenPASGN = { TOK_PLUS_ASSIGN, GEN_NOPUSH, g_add };
61 static GenDesc GenSASGN = { TOK_MINUS_ASSIGN, GEN_NOPUSH, g_sub };
62 static GenDesc GenMASGN = { TOK_MUL_ASSIGN, GEN_NOPUSH, g_mul };
63 static GenDesc GenDASGN = { TOK_DIV_ASSIGN, GEN_NOPUSH, g_div };
64 static GenDesc GenMOASGN = { TOK_MOD_ASSIGN, GEN_NOPUSH, g_mod };
65 static GenDesc GenSLASGN = { TOK_SHL_ASSIGN, GEN_NOPUSH, g_asl };
66 static GenDesc GenSRASGN = { TOK_SHR_ASSIGN, GEN_NOPUSH, g_asr };
67 static GenDesc GenAASGN = { TOK_AND_ASSIGN, GEN_NOPUSH, g_and };
68 static GenDesc GenXOASGN = { TOK_XOR_ASSIGN, GEN_NOPUSH, g_xor };
69 static GenDesc GenOASGN = { TOK_OR_ASSIGN, GEN_NOPUSH, g_or };
73 /*****************************************************************************/
74 /* Helper functions */
75 /*****************************************************************************/
79 static unsigned GlobalModeFlags (const ExprDesc* Expr)
80 /* Return the addressing mode flags for the given expression */
82 switch (ED_GetLoc (Expr)) {
83 case E_LOC_ABS: return CF_ABSOLUTE;
84 case E_LOC_GLOBAL: return CF_EXTERNAL;
85 case E_LOC_STATIC: return CF_STATIC;
86 case E_LOC_REGISTER: return CF_REGVAR;
87 case E_LOC_STACK: return CF_NONE;
88 case E_LOC_PRIMARY: return CF_NONE;
89 case E_LOC_EXPR: return CF_NONE;
90 case E_LOC_LITERAL: return CF_STATIC; /* Same as static */
92 Internal ("GlobalModeFlags: Invalid location flags value: 0x%04X", Expr->Flags);
100 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 void MarkedExprWithCheck (void (*Func) (ExprDesc*), ExprDesc* Expr)
125 /* Call an expression function with checks and record start and end of the
131 ExprWithCheck (Func, Expr);
133 ED_SetCodeRange (Expr, &Start, &End);
138 static Type* promoteint (Type* lhst, Type* rhst)
139 /* In an expression with two ints, return the type of the result */
141 /* Rules for integer types:
142 * - If one of the values is a long, the result is long.
143 * - If one of the values is unsigned, the result is also unsigned.
144 * - Otherwise the result is an int.
146 if (IsTypeLong (lhst) || IsTypeLong (rhst)) {
147 if (IsSignUnsigned (lhst) || IsSignUnsigned (rhst)) {
153 if (IsSignUnsigned (lhst) || IsSignUnsigned (rhst)) {
163 static unsigned typeadjust (ExprDesc* lhs, ExprDesc* rhs, int NoPush)
164 /* Adjust the two values for a binary operation. lhs is expected on stack or
165 * to be constant, rhs is expected to be in the primary register or constant.
166 * The function will put the type of the result into lhs and return the
167 * code generator flags for the operation.
168 * If NoPush is given, it is assumed that the operation does not expect the lhs
169 * to be on stack, and that lhs is in a register instead.
170 * Beware: The function does only accept int types.
173 unsigned ltype, rtype;
176 /* Get the type strings */
177 Type* lhst = lhs->Type;
178 Type* rhst = rhs->Type;
180 /* Generate type adjustment code if needed */
181 ltype = TypeOf (lhst);
182 if (ED_IsLocAbs (lhs)) {
186 /* Value is in primary register*/
189 rtype = TypeOf (rhst);
190 if (ED_IsLocAbs (rhs)) {
193 flags = g_typeadjust (ltype, rtype);
195 /* Set the type of the result */
196 lhs->Type = promoteint (lhst, rhst);
198 /* Return the code generator flags */
204 static const GenDesc* FindGen (token_t Tok, const GenDesc* Table)
205 /* Find a token in a generator table */
207 while (Table->Tok != TOK_INVALID) {
208 if (Table->Tok == Tok) {
218 static int TypeSpecAhead (void)
219 /* Return true if some sort of type is waiting (helper for cast and sizeof()
225 /* There's a type waiting if:
227 * We have an opening paren, and
228 * a. the next token is a type, or
229 * b. the next token is a type qualifier, or
230 * c. the next token is a typedef'd type
232 return CurTok.Tok == TOK_LPAREN && (
233 TokIsType (&NextTok) ||
234 TokIsTypeQual (&NextTok) ||
235 (NextTok.Tok == TOK_IDENT &&
236 (Entry = FindSym (NextTok.Ident)) != 0 &&
237 SymIsTypeDef (Entry)));
242 void PushAddr (const ExprDesc* Expr)
243 /* If the expression contains an address that was somehow evaluated,
244 * push this address on the stack. This is a helper function for all
245 * sorts of implicit or explicit assignment functions where the lvalue
246 * must be saved if it's not constant, before evaluating the rhs.
249 /* Get the address on stack if needed */
250 if (ED_IsLocExpr (Expr)) {
251 /* Push the address (always a pointer) */
258 /*****************************************************************************/
260 /*****************************************************************************/
264 static unsigned FunctionParamList (FuncDesc* Func, int IsFastcall)
265 /* Parse a function parameter list and pass the parameters to the called
266 * function. Depending on several criteria this may be done by just pushing
267 * each parameter separately, or creating the parameter frame once and then
268 * storing into this frame.
269 * The function returns the size of the parameters pushed.
274 /* Initialize variables */
275 SymEntry* Param = 0; /* Keep gcc silent */
276 unsigned ParamSize = 0; /* Size of parameters pushed */
277 unsigned ParamCount = 0; /* Number of parameters pushed */
278 unsigned FrameSize = 0; /* Size of parameter frame */
279 unsigned FrameParams = 0; /* Number of params in frame */
280 int FrameOffs = 0; /* Offset into parameter frame */
281 int Ellipsis = 0; /* Function is variadic */
283 /* As an optimization, we may allocate the complete parameter frame at
284 * once instead of pushing each parameter as it comes. We may do that,
287 * - optimizations that increase code size are enabled (allocating the
288 * stack frame at once gives usually larger code).
289 * - we have more than one parameter to push (don't count the last param
290 * for __fastcall__ functions).
292 * The FrameSize variable will contain a value > 0 if storing into a frame
293 * (instead of pushing) is enabled.
296 if (IS_Get (&CodeSizeFactor) >= 200) {
298 /* Calculate the number and size of the parameters */
299 FrameParams = Func->ParamCount;
300 FrameSize = Func->ParamSize;
301 if (FrameParams > 0 && IsFastcall) {
302 /* Last parameter is not pushed */
303 FrameSize -= CheckedSizeOf (Func->LastParam->Type);
307 /* Do we have more than one parameter in the frame? */
308 if (FrameParams > 1) {
309 /* Okeydokey, setup the frame */
310 FrameOffs = StackPtr;
312 StackPtr -= FrameSize;
314 /* Don't use a preallocated frame */
319 /* Parse the actual parameter list */
320 while (CurTok.Tok != TOK_RPAREN) {
324 /* Count arguments */
327 /* Fetch the pointer to the next argument, check for too many args */
328 if (ParamCount <= Func->ParamCount) {
329 /* Beware: If there are parameters with identical names, they
330 * cannot go into the same symbol table, which means that in this
331 * case of errorneous input, the number of nodes in the symbol
332 * table and ParamCount are NOT equal. We have to handle this case
333 * below to avoid segmentation violations. Since we know that this
334 * problem can only occur if there is more than one parameter,
335 * we will just use the last one.
337 if (ParamCount == 1) {
339 Param = Func->SymTab->SymHead;
340 } else if (Param->NextSym != 0) {
342 Param = Param->NextSym;
343 CHECK ((Param->Flags & SC_PARAM) != 0);
345 } else if (!Ellipsis) {
346 /* Too many arguments. Do we have an open param list? */
347 if ((Func->Flags & FD_VARIADIC) == 0) {
348 /* End of param list reached, no ellipsis */
349 Error ("Too many arguments in function call");
351 /* Assume an ellipsis even in case of errors to avoid an error
352 * message for each other argument.
357 /* Evaluate the parameter expression */
360 /* If we don't have an argument spec, accept anything, otherwise
361 * convert the actual argument to the type needed.
366 /* Convert the argument to the parameter type if needed */
367 TypeConversion (&Expr, Param->Type);
369 /* If we have a prototype, chars may be pushed as chars */
370 Flags |= CF_FORCECHAR;
374 /* No prototype available. Convert array to "pointer to first
375 * element", and function to "pointer to function".
377 Expr.Type = PtrConversion (Expr.Type);
381 /* Load the value into the primary if it is not already there */
382 LoadExpr (Flags, &Expr);
384 /* Use the type of the argument for the push */
385 Flags |= TypeOf (Expr.Type);
387 /* If this is a fastcall function, don't push the last argument */
388 if (ParamCount != Func->ParamCount || !IsFastcall) {
389 unsigned ArgSize = sizeofarg (Flags);
391 /* We have the space already allocated, store in the frame.
392 * Because of invalid type conversions (that have produced an
393 * error before), we can end up here with a non aligned stack
394 * frame. Since no output will be generated anyway, handle
395 * these cases gracefully instead of doing a CHECK.
397 if (FrameSize >= ArgSize) {
398 FrameSize -= ArgSize;
402 FrameOffs -= ArgSize;
404 g_putlocal (Flags | CF_NOKEEP, FrameOffs, Expr.IVal);
406 /* Push the argument */
407 g_push (Flags, Expr.IVal);
410 /* Calculate total parameter size */
411 ParamSize += ArgSize;
414 /* Check for end of argument list */
415 if (CurTok.Tok != TOK_COMMA) {
421 /* Check if we had enough parameters */
422 if (ParamCount < Func->ParamCount) {
423 Error ("Too few arguments in function call");
426 /* The function returns the size of all parameters pushed onto the stack.
427 * However, if there are parameters missing (which is an error and was
428 * flagged by the compiler) AND a stack frame was preallocated above,
429 * we would loose track of the stackpointer and generate an internal error
430 * later. So we correct the value by the parameters that should have been
431 * pushed to avoid an internal compiler error. Since an error was
432 * generated before, no code will be output anyway.
434 return ParamSize + FrameSize;
439 static void FunctionCall (ExprDesc* Expr)
440 /* Perform a function call. */
442 FuncDesc* Func; /* Function descriptor */
443 int IsFuncPtr; /* Flag */
444 unsigned ParamSize; /* Number of parameter bytes */
446 int PtrOffs = 0; /* Offset of function pointer on stack */
447 int IsFastcall = 0; /* True if it's a fast call function */
448 int PtrOnStack = 0; /* True if a pointer copy is on stack */
450 /* Skip the left paren */
453 /* Get a pointer to the function descriptor from the type string */
454 Func = GetFuncDesc (Expr->Type);
456 /* Handle function pointers transparently */
457 IsFuncPtr = IsTypeFuncPtr (Expr->Type);
460 /* Check wether it's a fastcall function that has parameters */
461 IsFastcall = IsQualFastcall (Expr->Type + 1) && (Func->ParamCount > 0);
463 /* Things may be difficult, depending on where the function pointer
464 * resides. If the function pointer is an expression of some sort
465 * (not a local or global variable), we have to evaluate this
466 * expression now and save the result for later. Since calls to
467 * function pointers may be nested, we must save it onto the stack.
468 * For fastcall functions we do also need to place a copy of the
469 * pointer on stack, since we cannot use a/x.
471 PtrOnStack = IsFastcall || !ED_IsConst (Expr);
474 /* Not a global or local variable, or a fastcall function. Load
475 * the pointer into the primary and mark it as an expression.
477 LoadExpr (CF_NONE, Expr);
478 ED_MakeRValExpr (Expr);
480 /* Remember the code position */
483 /* Push the pointer onto the stack and remember the offset */
489 /* Check function attributes */
490 if (Expr->Sym && SymHasAttr (Expr->Sym, atNoReturn)) {
491 /* For now, handle as if a return statement was encountered */
492 F_ReturnFound (CurrentFunc);
495 /* Check for known standard functions and inline them */
496 if (Expr->Name != 0) {
497 int StdFunc = FindStdFunc ((const char*) Expr->Name);
499 /* Inline this function */
500 HandleStdFunc (StdFunc, Func, Expr);
505 /* If we didn't inline the function, get fastcall info */
506 IsFastcall = IsQualFastcall (Expr->Type);
509 /* Parse the parameter list */
510 ParamSize = FunctionParamList (Func, IsFastcall);
512 /* We need the closing paren here */
515 /* Special handling for function pointers */
518 /* If the function is not a fastcall function, load the pointer to
519 * the function into the primary.
523 /* Not a fastcall function - we may use the primary */
525 /* If we have no parameters, the pointer is still in the
526 * primary. Remove the code to push it and correct the
529 if (ParamSize == 0) {
533 /* Load from the saved copy */
534 g_getlocal (CF_PTR, PtrOffs);
537 /* Load from original location */
538 LoadExpr (CF_NONE, Expr);
541 /* Call the function */
542 g_callind (TypeOf (Expr->Type+1), ParamSize, PtrOffs);
546 /* Fastcall function. We cannot use the primary for the function
547 * pointer and must therefore use an offset to the stack location.
548 * Since fastcall functions may never be variadic, we can use the
549 * index register for this purpose.
551 g_callind (CF_LOCAL, ParamSize, PtrOffs);
554 /* If we have a pointer on stack, remove it */
565 /* Normal function */
566 g_call (TypeOf (Expr->Type), (const char*) Expr->Name, ParamSize);
570 /* The function result is an rvalue in the primary register */
571 ED_MakeRValExpr (Expr);
572 Expr->Type = GetFuncReturn (Expr->Type);
577 static void Primary (ExprDesc* E)
578 /* This is the lowest level of the expression parser. */
583 /* Initialize fields in the expression stucture */
586 /* Character and integer constants. */
587 if (CurTok.Tok == TOK_ICONST || CurTok.Tok == TOK_CCONST) {
588 E->IVal = CurTok.IVal;
589 E->Flags = E_LOC_ABS | E_RTYPE_RVAL;
590 E->Type = CurTok.Type;
595 /* Floating point constant */
596 if (CurTok.Tok == TOK_FCONST) {
597 E->FVal = CurTok.FVal;
598 E->Flags = E_LOC_ABS | E_RTYPE_RVAL;
599 E->Type = CurTok.Type;
604 /* Process parenthesized subexpression by calling the whole parser
607 if (CurTok.Tok == TOK_LPAREN) {
614 /* If we run into an identifier in preprocessing mode, we assume that this
615 * is an undefined macro and replace it by a constant value of zero.
617 if (Preprocessing && CurTok.Tok == TOK_IDENT) {
619 ED_MakeConstAbsInt (E, 0);
623 /* All others may only be used if the expression evaluation is not called
624 * recursively by the preprocessor.
627 /* Illegal expression in PP mode */
628 Error ("Preprocessor expression expected");
629 ED_MakeConstAbsInt (E, 1);
633 switch (CurTok.Tok) {
636 /* Identifier. Get a pointer to the symbol table entry */
637 Sym = E->Sym = FindSym (CurTok.Ident);
639 /* Is the symbol known? */
642 /* We found the symbol - skip the name token */
645 /* Check for illegal symbol types */
646 CHECK ((Sym->Flags & SC_LABEL) != SC_LABEL);
647 if (Sym->Flags & SC_TYPE) {
648 /* Cannot use type symbols */
649 Error ("Variable identifier expected");
650 /* Assume an int type to make E valid */
651 E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
656 /* Mark the symbol as referenced */
657 Sym->Flags |= SC_REF;
659 /* The expression type is the symbol type */
662 /* Check for legal symbol types */
663 if ((Sym->Flags & SC_CONST) == SC_CONST) {
664 /* Enum or some other numeric constant */
665 E->Flags = E_LOC_ABS | E_RTYPE_RVAL;
666 E->IVal = Sym->V.ConstVal;
667 } else if ((Sym->Flags & SC_FUNC) == SC_FUNC) {
669 E->Flags = E_LOC_GLOBAL | E_RTYPE_LVAL;
670 E->Name = (unsigned long) Sym->Name;
671 } else if ((Sym->Flags & SC_AUTO) == SC_AUTO) {
672 /* Local variable. If this is a parameter for a variadic
673 * function, we have to add some address calculations, and the
674 * address is not const.
676 if ((Sym->Flags & SC_PARAM) == SC_PARAM && F_IsVariadic (CurrentFunc)) {
677 /* Variadic parameter */
678 g_leavariadic (Sym->V.Offs - F_GetParamSize (CurrentFunc));
679 E->Flags = E_LOC_EXPR | E_RTYPE_LVAL;
681 /* Normal parameter */
682 E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
683 E->IVal = Sym->V.Offs;
685 } else if ((Sym->Flags & SC_REGISTER) == SC_REGISTER) {
686 /* Register variable, zero page based */
687 E->Flags = E_LOC_REGISTER | E_RTYPE_LVAL;
688 E->Name = Sym->V.R.RegOffs;
689 } else if ((Sym->Flags & SC_STATIC) == SC_STATIC) {
690 /* Static variable */
691 if (Sym->Flags & (SC_EXTERN | SC_STORAGE)) {
692 E->Flags = E_LOC_GLOBAL | E_RTYPE_LVAL;
693 E->Name = (unsigned long) Sym->Name;
695 E->Flags = E_LOC_STATIC | E_RTYPE_LVAL;
696 E->Name = Sym->V.Label;
699 /* Local static variable */
700 E->Flags = E_LOC_STATIC | E_RTYPE_LVAL;
701 E->Name = Sym->V.Offs;
704 /* We've made all variables lvalues above. However, this is
705 * not always correct: An array is actually the address of its
706 * first element, which is a rvalue, and a function is a
707 * rvalue, too, because we cannot store anything in a function.
708 * So fix the flags depending on the type.
710 if (IsTypeArray (E->Type) || IsTypeFunc (E->Type)) {
716 /* We did not find the symbol. Remember the name, then skip it */
718 strcpy (Ident, CurTok.Ident);
721 /* IDENT is either an auto-declared function or an undefined variable. */
722 if (CurTok.Tok == TOK_LPAREN) {
723 /* C99 doesn't allow calls to undefined functions, so
724 * generate an error and otherwise a warning. Declare a
725 * function returning int. For that purpose, prepare a
726 * function signature for a function having an empty param
727 * list and returning int.
729 if (IS_Get (&Standard) >= STD_C99) {
730 Error ("Call to undefined function `%s'", Ident);
732 Warning ("Call to undefined function `%s'", Ident);
734 Sym = AddGlobalSym (Ident, GetImplicitFuncType(), SC_EXTERN | SC_REF | SC_FUNC);
736 E->Flags = E_LOC_GLOBAL | E_RTYPE_RVAL;
737 E->Name = (unsigned long) Sym->Name;
739 /* Undeclared Variable */
740 Sym = AddLocalSym (Ident, type_int, SC_AUTO | SC_REF, 0);
741 E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
743 Error ("Undefined symbol: `%s'", Ident);
752 L = UseLiteral (CurTok.SVal);
753 E->Type = GetCharArrayType (GetLiteralSize (CurTok.SVal));
754 E->Flags = E_LOC_LITERAL | E_RTYPE_RVAL;
756 E->Name = GetLiteralLabel (CurTok.SVal);
763 E->Flags = E_LOC_EXPR | E_RTYPE_RVAL;
768 /* Register pseudo variable */
769 E->Type = type_uchar;
770 E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
775 /* Register pseudo variable */
777 E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
782 /* Register pseudo variable */
783 E->Type = type_ulong;
784 E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
789 /* Illegal primary. Be sure to skip the token to avoid endless
792 Error ("Expression expected");
794 ED_MakeConstAbsInt (E, 1);
801 static void ArrayRef (ExprDesc* Expr)
802 /* Handle an array reference. This function needs a rewrite. */
813 /* Skip the bracket */
816 /* Get the type of left side */
819 /* We can apply a special treatment for arrays that have a const base
820 * address. This is true for most arrays and will produce a lot better
821 * code. Check if this is a const base address.
823 ConstBaseAddr = ED_IsRVal (Expr) &&
824 (ED_IsLocConst (Expr) || ED_IsLocStack (Expr));
826 /* If we have a constant base, we delay the address fetch */
828 if (!ConstBaseAddr) {
829 /* Get a pointer to the array into the primary */
830 LoadExpr (CF_NONE, Expr);
832 /* Get the array pointer on stack. Do not push more than 16
833 * bit, even if this value is greater, since we cannot handle
834 * other than 16bit stuff when doing indexing.
840 /* TOS now contains ptr to array elements. Get the subscript. */
841 MarkedExprWithCheck (hie0, &Subscript);
843 /* Check the types of array and subscript. We can either have a
844 * pointer/array to the left, in which case the subscript must be of an
845 * integer type, or we have an integer to the left, in which case the
846 * subscript must be a pointer/array.
847 * Since we do the necessary checking here, we can rely later on the
850 Qualifiers = T_QUAL_NONE;
851 if (IsClassPtr (Expr->Type)) {
852 if (!IsClassInt (Subscript.Type)) {
853 Error ("Array subscript is not an integer");
854 /* To avoid any compiler errors, make the expression a valid int */
855 ED_MakeConstAbsInt (&Subscript, 0);
857 if (IsTypeArray (Expr->Type)) {
858 Qualifiers = GetQualifier (Expr->Type);
860 ElementType = Indirect (Expr->Type);
861 } else if (IsClassInt (Expr->Type)) {
862 if (!IsClassPtr (Subscript.Type)) {
863 Error ("Subscripted value is neither array nor pointer");
864 /* To avoid compiler errors, make the subscript a char[] at
867 ED_MakeConstAbs (&Subscript, 0, GetCharArrayType (1));
868 } else if (IsTypeArray (Subscript.Type)) {
869 Qualifiers = GetQualifier (Subscript.Type);
871 ElementType = Indirect (Subscript.Type);
873 Error ("Cannot subscript");
874 /* To avoid compiler errors, fake both the array and the subscript, so
875 * we can just proceed.
877 ED_MakeConstAbs (Expr, 0, GetCharArrayType (1));
878 ED_MakeConstAbsInt (&Subscript, 0);
879 ElementType = Indirect (Expr->Type);
882 /* The element type has the combined qualifiers from itself and the array,
883 * it is a member of (if any).
885 if (GetQualifier (ElementType) != (GetQualifier (ElementType) | Qualifiers)) {
886 ElementType = TypeDup (ElementType);
887 ElementType->C |= Qualifiers;
890 /* If the subscript is a bit-field, load it and make it an rvalue */
891 if (ED_IsBitField (&Subscript)) {
892 LoadExpr (CF_NONE, &Subscript);
893 ED_MakeRValExpr (&Subscript);
896 /* Check if the subscript is constant absolute value */
897 if (ED_IsConstAbs (&Subscript) && ED_CodeRangeIsEmpty (&Subscript)) {
899 /* The array subscript is a numeric constant. If we had pushed the
900 * array base address onto the stack before, we can remove this value,
901 * since we can generate expression+offset.
903 if (!ConstBaseAddr) {
906 /* Get an array pointer into the primary */
907 LoadExpr (CF_NONE, Expr);
910 if (IsClassPtr (Expr->Type)) {
912 /* Lhs is pointer/array. Scale the subscript value according to
915 Subscript.IVal *= CheckedSizeOf (ElementType);
917 /* Remove the address load code */
920 /* In case of an array, we can adjust the offset of the expression
921 * already in Expr. If the base address was a constant, we can even
922 * remove the code that loaded the address into the primary.
924 if (IsTypeArray (Expr->Type)) {
926 /* Adjust the offset */
927 Expr->IVal += Subscript.IVal;
931 /* It's a pointer, so we do have to load it into the primary
932 * first (if it's not already there).
934 if (ConstBaseAddr || ED_IsLVal (Expr)) {
935 LoadExpr (CF_NONE, Expr);
936 ED_MakeRValExpr (Expr);
940 Expr->IVal = Subscript.IVal;
945 /* Scale the rhs value according to the element type */
946 g_scale (TypeOf (tptr1), CheckedSizeOf (ElementType));
948 /* Add the subscript. Since arrays are indexed by integers,
949 * we will ignore the true type of the subscript here and
950 * use always an int. #### Use offset but beware of LoadExpr!
952 g_inc (CF_INT | CF_CONST, Subscript.IVal);
958 /* Array subscript is not constant. Load it into the primary */
960 LoadExpr (CF_NONE, &Subscript);
963 if (IsClassPtr (Expr->Type)) {
965 /* Indexing is based on unsigneds, so we will just use the integer
966 * portion of the index (which is in (e)ax, so there's no further
969 g_scale (CF_INT, CheckedSizeOf (ElementType));
973 /* Get the int value on top. If we come here, we're sure, both
974 * values are 16 bit (the first one was truncated if necessary
975 * and the second one is a pointer). Note: If ConstBaseAddr is
976 * true, we don't have a value on stack, so to "swap" both, just
977 * push the subscript.
981 LoadExpr (CF_NONE, Expr);
988 g_scale (TypeOf (tptr1), CheckedSizeOf (ElementType));
992 /* The offset is now in the primary register. It we didn't have a
993 * constant base address for the lhs, the lhs address is already
994 * on stack, and we must add the offset. If the base address was
995 * constant, we call special functions to add the address to the
998 if (!ConstBaseAddr) {
1000 /* The array base address is on stack and the subscript is in the
1001 * primary. Add both.
1007 /* The subscript is in the primary, and the array base address is
1008 * in Expr. If the subscript has itself a constant address, it is
1009 * often a better idea to reverse again the order of the
1010 * evaluation. This will generate better code if the subscript is
1011 * a byte sized variable. But beware: This is only possible if the
1012 * subscript was not scaled, that is, if this was a byte array
1015 if ((ED_IsLocConst (&Subscript) || ED_IsLocStack (&Subscript)) &&
1016 CheckedSizeOf (ElementType) == SIZEOF_CHAR) {
1020 /* Reverse the order of evaluation */
1021 if (CheckedSizeOf (Subscript.Type) == SIZEOF_CHAR) {
1026 RemoveCode (&Mark2);
1028 /* Get a pointer to the array into the primary. */
1029 LoadExpr (CF_NONE, Expr);
1031 /* Add the variable */
1032 if (ED_IsLocStack (&Subscript)) {
1033 g_addlocal (Flags, Subscript.IVal);
1035 Flags |= GlobalModeFlags (&Subscript);
1036 g_addstatic (Flags, Subscript.Name, Subscript.IVal);
1040 if (ED_IsLocAbs (Expr)) {
1041 /* Constant numeric address. Just add it */
1042 g_inc (CF_INT, Expr->IVal);
1043 } else if (ED_IsLocStack (Expr)) {
1044 /* Base address is a local variable address */
1045 if (IsTypeArray (Expr->Type)) {
1046 g_addaddr_local (CF_INT, Expr->IVal);
1048 g_addlocal (CF_PTR, Expr->IVal);
1051 /* Base address is a static variable address */
1052 unsigned Flags = CF_INT | GlobalModeFlags (Expr);
1053 if (ED_IsRVal (Expr)) {
1054 /* Add the address of the location */
1055 g_addaddr_static (Flags, Expr->Name, Expr->IVal);
1057 /* Add the contents of the location */
1058 g_addstatic (Flags, Expr->Name, Expr->IVal);
1066 /* The result is an expression in the primary */
1067 ED_MakeRValExpr (Expr);
1071 /* Result is of element type */
1072 Expr->Type = ElementType;
1074 /* An array element is actually a variable. So the rules for variables
1075 * with respect to the reference type apply: If it's an array, it is
1076 * a rvalue, otherwise it's an lvalue. (A function would also be a rvalue,
1077 * but an array cannot contain functions).
1079 if (IsTypeArray (Expr->Type)) {
1085 /* Consume the closing bracket */
1091 static void StructRef (ExprDesc* Expr)
1092 /* Process struct field after . or ->. */
1098 /* Skip the token and check for an identifier */
1100 if (CurTok.Tok != TOK_IDENT) {
1101 Error ("Identifier expected");
1102 /* Make the expression an integer at address zero */
1103 ED_MakeConstAbs (Expr, 0, type_int);
1107 /* Get the symbol table entry and check for a struct field */
1108 strcpy (Ident, CurTok.Ident);
1110 Field = FindStructField (Expr->Type, Ident);
1112 Error ("Struct/union has no field named `%s'", Ident);
1113 /* Make the expression an integer at address zero */
1114 ED_MakeConstAbs (Expr, 0, type_int);
1118 /* If we have a struct pointer that is an lvalue and not already in the
1119 * primary, load it now.
1121 if (ED_IsLVal (Expr) && IsTypePtr (Expr->Type)) {
1123 /* Load into the primary */
1124 LoadExpr (CF_NONE, Expr);
1126 /* Make it an lvalue expression */
1127 ED_MakeLValExpr (Expr);
1130 /* Set the struct field offset */
1131 Expr->IVal += Field->V.Offs;
1133 /* The type is the type of the field plus any qualifiers from the struct */
1134 if (IsClassStruct (Expr->Type)) {
1135 Q = GetQualifier (Expr->Type);
1137 Q = GetQualifier (Indirect (Expr->Type));
1139 if (GetQualifier (Field->Type) == (GetQualifier (Field->Type) | Q)) {
1140 Expr->Type = Field->Type;
1142 Expr->Type = TypeDup (Field->Type);
1146 /* An struct member is actually a variable. So the rules for variables
1147 * with respect to the reference type apply: If it's an array, it is
1148 * a rvalue, otherwise it's an lvalue. (A function would also be a rvalue,
1149 * but a struct field cannot be a function).
1151 if (IsTypeArray (Expr->Type)) {
1157 /* Make the expression a bit field if necessary */
1158 if (SymIsBitField (Field)) {
1159 ED_MakeBitField (Expr, Field->V.B.BitOffs, Field->V.B.BitWidth);
1165 static void hie11 (ExprDesc *Expr)
1166 /* Handle compound types (structs and arrays) */
1168 /* Name value used in invalid function calls */
1169 static const char IllegalFunc[] = "illegal_function_call";
1171 /* Evaluate the lhs */
1174 /* Check for a rhs */
1175 while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN ||
1176 CurTok.Tok == TOK_DOT || CurTok.Tok == TOK_PTR_REF) {
1178 switch (CurTok.Tok) {
1181 /* Array reference */
1186 /* Function call. */
1187 if (!IsTypeFunc (Expr->Type) && !IsTypeFuncPtr (Expr->Type)) {
1188 /* Not a function */
1189 Error ("Illegal function call");
1190 /* Force the type to be a implicitly defined function, one
1191 * returning an int and taking any number of arguments.
1192 * Since we don't have a name, invent one.
1194 ED_MakeConstAbs (Expr, 0, GetImplicitFuncType ());
1195 Expr->Name = (long) IllegalFunc;
1197 /* Call the function */
1198 FunctionCall (Expr);
1202 if (!IsClassStruct (Expr->Type)) {
1203 Error ("Struct expected");
1209 /* If we have an array, convert it to pointer to first element */
1210 if (IsTypeArray (Expr->Type)) {
1211 Expr->Type = ArrayToPtr (Expr->Type);
1213 if (!IsClassPtr (Expr->Type) || !IsClassStruct (Indirect (Expr->Type))) {
1214 Error ("Struct pointer expected");
1220 Internal ("Invalid token in hie11: %d", CurTok.Tok);
1228 void Store (ExprDesc* Expr, const Type* StoreType)
1229 /* Store the primary register into the location denoted by Expr. If StoreType
1230 * is given, use this type when storing instead of Expr->Type. If StoreType
1231 * is NULL, use Expr->Type instead.
1236 /* If StoreType was not given, use Expr->Type instead */
1237 if (StoreType == 0) {
1238 StoreType = Expr->Type;
1241 /* Prepare the code generator flags */
1242 Flags = TypeOf (StoreType) | GlobalModeFlags (Expr);
1244 /* Do the store depending on the location */
1245 switch (ED_GetLoc (Expr)) {
1248 /* Absolute: numeric address or const */
1249 g_putstatic (Flags, Expr->IVal, 0);
1253 /* Global variable */
1254 g_putstatic (Flags, Expr->Name, Expr->IVal);
1259 /* Static variable or literal in the literal pool */
1260 g_putstatic (Flags, Expr->Name, Expr->IVal);
1263 case E_LOC_REGISTER:
1264 /* Register variable */
1265 g_putstatic (Flags, Expr->Name, Expr->IVal);
1269 /* Value on the stack */
1270 g_putlocal (Flags, Expr->IVal, 0);
1274 /* The primary register (value is already there) */
1278 /* An expression in the primary register */
1279 g_putind (Flags, Expr->IVal);
1283 Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
1286 /* Assume that each one of the stores will invalidate CC */
1287 ED_MarkAsUntested (Expr);
1292 static void PreInc (ExprDesc* Expr)
1293 /* Handle the preincrement operators */
1298 /* Skip the operator token */
1301 /* Evaluate the expression and check that it is an lvalue */
1303 if (!ED_IsLVal (Expr)) {
1304 Error ("Invalid lvalue");
1308 /* We cannot modify const values */
1309 if (IsQualConst (Expr->Type)) {
1310 Error ("Increment of read-only variable");
1313 /* Get the data type */
1314 Flags = TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR | CF_CONST;
1316 /* Get the increment value in bytes */
1317 Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1319 /* Check the location of the data */
1320 switch (ED_GetLoc (Expr)) {
1323 /* Absolute: numeric address or const */
1324 g_addeqstatic (Flags, Expr->IVal, 0, Val);
1328 /* Global variable */
1329 g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1334 /* Static variable or literal in the literal pool */
1335 g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1338 case E_LOC_REGISTER:
1339 /* Register variable */
1340 g_addeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1344 /* Value on the stack */
1345 g_addeqlocal (Flags, Expr->IVal, Val);
1349 /* The primary register */
1354 /* An expression in the primary register */
1355 g_addeqind (Flags, Expr->IVal, Val);
1359 Internal ("Invalid location in PreInc(): 0x%04X", ED_GetLoc (Expr));
1362 /* Result is an expression, no reference */
1363 ED_MakeRValExpr (Expr);
1368 static void PreDec (ExprDesc* Expr)
1369 /* Handle the predecrement operators */
1374 /* Skip the operator token */
1377 /* Evaluate the expression and check that it is an lvalue */
1379 if (!ED_IsLVal (Expr)) {
1380 Error ("Invalid lvalue");
1384 /* We cannot modify const values */
1385 if (IsQualConst (Expr->Type)) {
1386 Error ("Decrement of read-only variable");
1389 /* Get the data type */
1390 Flags = TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR | CF_CONST;
1392 /* Get the increment value in bytes */
1393 Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1395 /* Check the location of the data */
1396 switch (ED_GetLoc (Expr)) {
1399 /* Absolute: numeric address or const */
1400 g_subeqstatic (Flags, Expr->IVal, 0, Val);
1404 /* Global variable */
1405 g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1410 /* Static variable or literal in the literal pool */
1411 g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1414 case E_LOC_REGISTER:
1415 /* Register variable */
1416 g_subeqstatic (Flags, Expr->Name, Expr->IVal, Val);
1420 /* Value on the stack */
1421 g_subeqlocal (Flags, Expr->IVal, Val);
1425 /* The primary register */
1430 /* An expression in the primary register */
1431 g_subeqind (Flags, Expr->IVal, Val);
1435 Internal ("Invalid location in PreDec(): 0x%04X", ED_GetLoc (Expr));
1438 /* Result is an expression, no reference */
1439 ED_MakeRValExpr (Expr);
1444 static void PostInc (ExprDesc* Expr)
1445 /* Handle the postincrement operator */
1451 /* The expression to increment must be an lvalue */
1452 if (!ED_IsLVal (Expr)) {
1453 Error ("Invalid lvalue");
1457 /* We cannot modify const values */
1458 if (IsQualConst (Expr->Type)) {
1459 Error ("Increment of read-only variable");
1462 /* Get the data type */
1463 Flags = TypeOf (Expr->Type);
1465 /* Push the address if needed */
1468 /* Fetch the value and save it (since it's the result of the expression) */
1469 LoadExpr (CF_NONE, Expr);
1470 g_save (Flags | CF_FORCECHAR);
1472 /* If we have a pointer expression, increment by the size of the type */
1473 if (IsTypePtr (Expr->Type)) {
1474 g_inc (Flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (Expr->Type + 1));
1476 g_inc (Flags | CF_CONST | CF_FORCECHAR, 1);
1479 /* Store the result back */
1482 /* Restore the original value in the primary register */
1483 g_restore (Flags | CF_FORCECHAR);
1485 /* The result is always an expression, no reference */
1486 ED_MakeRValExpr (Expr);
1491 static void PostDec (ExprDesc* Expr)
1492 /* Handle the postdecrement operator */
1498 /* The expression to increment must be an lvalue */
1499 if (!ED_IsLVal (Expr)) {
1500 Error ("Invalid lvalue");
1504 /* We cannot modify const values */
1505 if (IsQualConst (Expr->Type)) {
1506 Error ("Decrement of read-only variable");
1509 /* Get the data type */
1510 Flags = TypeOf (Expr->Type);
1512 /* Push the address if needed */
1515 /* Fetch the value and save it (since it's the result of the expression) */
1516 LoadExpr (CF_NONE, Expr);
1517 g_save (Flags | CF_FORCECHAR);
1519 /* If we have a pointer expression, increment by the size of the type */
1520 if (IsTypePtr (Expr->Type)) {
1521 g_dec (Flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (Expr->Type + 1));
1523 g_dec (Flags | CF_CONST | CF_FORCECHAR, 1);
1526 /* Store the result back */
1529 /* Restore the original value in the primary register */
1530 g_restore (Flags | CF_FORCECHAR);
1532 /* The result is always an expression, no reference */
1533 ED_MakeRValExpr (Expr);
1538 static void UnaryOp (ExprDesc* Expr)
1539 /* Handle unary -/+ and ~ */
1543 /* Remember the operator token and skip it */
1544 token_t Tok = CurTok.Tok;
1547 /* Get the expression */
1550 /* We can only handle integer types */
1551 if (!IsClassInt (Expr->Type)) {
1552 Error ("Argument must have integer type");
1553 ED_MakeConstAbsInt (Expr, 1);
1556 /* Check for a constant expression */
1557 if (ED_IsConstAbs (Expr)) {
1558 /* Value is constant */
1560 case TOK_MINUS: Expr->IVal = -Expr->IVal; break;
1561 case TOK_PLUS: break;
1562 case TOK_COMP: Expr->IVal = ~Expr->IVal; break;
1563 default: Internal ("Unexpected token: %d", Tok);
1566 /* Value is not constant */
1567 LoadExpr (CF_NONE, Expr);
1569 /* Get the type of the expression */
1570 Flags = TypeOf (Expr->Type);
1572 /* Handle the operation */
1574 case TOK_MINUS: g_neg (Flags); break;
1575 case TOK_PLUS: break;
1576 case TOK_COMP: g_com (Flags); break;
1577 default: Internal ("Unexpected token: %d", Tok);
1580 /* The result is a rvalue in the primary */
1581 ED_MakeRValExpr (Expr);
1587 void hie10 (ExprDesc* Expr)
1588 /* Handle ++, --, !, unary - etc. */
1592 switch (CurTok.Tok) {
1610 if (evalexpr (CF_NONE, hie10, Expr) == 0) {
1611 /* Constant expression */
1612 Expr->IVal = !Expr->IVal;
1614 g_bneg (TypeOf (Expr->Type));
1615 ED_MakeRValExpr (Expr);
1616 ED_TestDone (Expr); /* bneg will set cc */
1622 ExprWithCheck (hie10, Expr);
1623 if (ED_IsLVal (Expr) || !(ED_IsLocConst (Expr) || ED_IsLocStack (Expr))) {
1624 /* Not a const, load it into the primary and make it a
1627 LoadExpr (CF_NONE, Expr);
1628 ED_MakeRValExpr (Expr);
1630 /* If the expression is already a pointer to function, the
1631 * additional dereferencing operator must be ignored. A function
1632 * itself is represented as "pointer to function", so any number
1633 * of dereference operators is legal, since the result will
1634 * always be converted to "pointer to function".
1636 if (IsTypeFuncPtr (Expr->Type) || IsTypeFunc (Expr->Type)) {
1637 /* Expression not storable */
1640 if (IsClassPtr (Expr->Type)) {
1641 Expr->Type = Indirect (Expr->Type);
1643 Error ("Illegal indirection");
1645 /* The * operator yields an lvalue */
1652 ExprWithCheck (hie10, Expr);
1653 /* The & operator may be applied to any lvalue, and it may be
1654 * applied to functions, even if they're no lvalues.
1656 if (ED_IsRVal (Expr) && !IsTypeFunc (Expr->Type) && !IsTypeArray (Expr->Type)) {
1657 Error ("Illegal address");
1659 if (ED_IsBitField (Expr)) {
1660 Error ("Cannot take address of bit-field");
1661 /* Do it anyway, just to avoid further warnings */
1662 Expr->Flags &= ~E_BITFIELD;
1664 Expr->Type = PointerTo (Expr->Type);
1665 /* The & operator yields an rvalue */
1672 if (TypeSpecAhead ()) {
1675 Size = CheckedSizeOf (ParseType (T));
1678 /* Remember the output queue pointer */
1682 Size = CheckedSizeOf (Expr->Type);
1683 /* Remove any generated code */
1686 ED_MakeConstAbs (Expr, Size, type_size_t);
1687 ED_MarkAsUntested (Expr);
1691 if (TypeSpecAhead ()) {
1701 /* Handle post increment */
1702 switch (CurTok.Tok) {
1703 case TOK_INC: PostInc (Expr); break;
1704 case TOK_DEC: PostDec (Expr); break;
1715 static void hie_internal (const GenDesc* Ops, /* List of generators */
1717 void (*hienext) (ExprDesc*),
1719 /* Helper function */
1725 token_t Tok; /* The operator token */
1726 unsigned ltype, type;
1727 int rconst; /* Operand is a constant */
1733 while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
1735 /* Tell the caller that we handled it's ops */
1738 /* All operators that call this function expect an int on the lhs */
1739 if (!IsClassInt (Expr->Type)) {
1740 Error ("Integer expression expected");
1741 /* To avoid further errors, make Expr a valid int expression */
1742 ED_MakeConstAbsInt (Expr, 1);
1745 /* Remember the operator token, then skip it */
1749 /* Get the lhs on stack */
1750 GetCodePos (&Mark1);
1751 ltype = TypeOf (Expr->Type);
1752 if (ED_IsConstAbs (Expr)) {
1753 /* Constant value */
1754 GetCodePos (&Mark2);
1755 g_push (ltype | CF_CONST, Expr->IVal);
1757 /* Value not constant */
1758 LoadExpr (CF_NONE, Expr);
1759 GetCodePos (&Mark2);
1763 /* Get the right hand side */
1764 MarkedExprWithCheck (hienext, &Expr2);
1766 /* Check for a constant expression */
1767 rconst = (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2));
1769 /* Not constant, load into the primary */
1770 LoadExpr (CF_NONE, &Expr2);
1773 /* Check the type of the rhs */
1774 if (!IsClassInt (Expr2.Type)) {
1775 Error ("Integer expression expected");
1778 /* Check for const operands */
1779 if (ED_IsConstAbs (Expr) && rconst) {
1781 /* Both operands are constant, remove the generated code */
1782 RemoveCode (&Mark1);
1784 /* Get the type of the result */
1785 Expr->Type = promoteint (Expr->Type, Expr2.Type);
1787 /* Handle the op differently for signed and unsigned types */
1788 if (IsSignSigned (Expr->Type)) {
1790 /* Evaluate the result for signed operands */
1791 signed long Val1 = Expr->IVal;
1792 signed long Val2 = Expr2.IVal;
1795 Expr->IVal = (Val1 | Val2);
1798 Expr->IVal = (Val1 ^ Val2);
1801 Expr->IVal = (Val1 & Val2);
1804 Expr->IVal = (Val1 * Val2);
1808 Error ("Division by zero");
1809 Expr->IVal = 0x7FFFFFFF;
1811 Expr->IVal = (Val1 / Val2);
1816 Error ("Modulo operation with zero");
1819 Expr->IVal = (Val1 % Val2);
1823 Internal ("hie_internal: got token 0x%X\n", Tok);
1827 /* Evaluate the result for unsigned operands */
1828 unsigned long Val1 = Expr->IVal;
1829 unsigned long Val2 = Expr2.IVal;
1832 Expr->IVal = (Val1 | Val2);
1835 Expr->IVal = (Val1 ^ Val2);
1838 Expr->IVal = (Val1 & Val2);
1841 Expr->IVal = (Val1 * Val2);
1845 Error ("Division by zero");
1846 Expr->IVal = 0xFFFFFFFF;
1848 Expr->IVal = (Val1 / Val2);
1853 Error ("Modulo operation with zero");
1856 Expr->IVal = (Val1 % Val2);
1860 Internal ("hie_internal: got token 0x%X\n", Tok);
1866 /* If the right hand side is constant, and the generator function
1867 * expects the lhs in the primary, remove the push of the primary
1870 unsigned rtype = TypeOf (Expr2.Type);
1873 /* Second value is constant - check for div */
1876 if (Tok == TOK_DIV && Expr2.IVal == 0) {
1877 Error ("Division by zero");
1878 } else if (Tok == TOK_MOD && Expr2.IVal == 0) {
1879 Error ("Modulo operation with zero");
1881 if ((Gen->Flags & GEN_NOPUSH) != 0) {
1882 RemoveCode (&Mark2);
1883 ltype |= CF_REG; /* Value is in register */
1887 /* Determine the type of the operation result. */
1888 type |= g_typeadjust (ltype, rtype);
1889 Expr->Type = promoteint (Expr->Type, Expr2.Type);
1892 Gen->Func (type, Expr2.IVal);
1894 /* We have a rvalue in the primary now */
1895 ED_MakeRValExpr (Expr);
1902 static void hie_compare (const GenDesc* Ops, /* List of generators */
1904 void (*hienext) (ExprDesc*))
1905 /* Helper function for the compare operators */
1911 token_t Tok; /* The operator token */
1913 int rconst; /* Operand is a constant */
1918 while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
1920 /* Remember the operator token, then skip it */
1924 /* Get the lhs on stack */
1925 GetCodePos (&Mark1);
1926 ltype = TypeOf (Expr->Type);
1927 if (ED_IsConstAbs (Expr)) {
1928 /* Constant value */
1929 GetCodePos (&Mark2);
1930 g_push (ltype | CF_CONST, Expr->IVal);
1932 /* Value not constant */
1933 LoadExpr (CF_NONE, Expr);
1934 GetCodePos (&Mark2);
1938 /* Get the right hand side */
1939 MarkedExprWithCheck (hienext, &Expr2);
1941 /* Check for a constant expression */
1942 rconst = (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2));
1944 /* Not constant, load into the primary */
1945 LoadExpr (CF_NONE, &Expr2);
1948 /* Make sure, the types are compatible */
1949 if (IsClassInt (Expr->Type)) {
1950 if (!IsClassInt (Expr2.Type) && !(IsClassPtr(Expr2.Type) && ED_IsNullPtr(Expr))) {
1951 Error ("Incompatible types");
1953 } else if (IsClassPtr (Expr->Type)) {
1954 if (IsClassPtr (Expr2.Type)) {
1955 /* Both pointers are allowed in comparison if they point to
1956 * the same type, or if one of them is a void pointer.
1958 Type* left = Indirect (Expr->Type);
1959 Type* right = Indirect (Expr2.Type);
1960 if (TypeCmp (left, right) < TC_EQUAL && left->C != T_VOID && right->C != T_VOID) {
1961 /* Incomatible pointers */
1962 Error ("Incompatible types");
1964 } else if (!ED_IsNullPtr (&Expr2)) {
1965 Error ("Incompatible types");
1969 /* Check for const operands */
1970 if (ED_IsConstAbs (Expr) && rconst) {
1972 /* If the result is constant, this is suspicious when not in
1973 * preprocessor mode.
1975 if (!Preprocessing) {
1976 Warning ("Result of comparison is constant");
1979 /* Both operands are constant, remove the generated code */
1980 RemoveCode (&Mark1);
1982 /* Determine if this is a signed or unsigned compare */
1983 if (IsClassInt (Expr->Type) && IsSignSigned (Expr->Type) &&
1984 IsClassInt (Expr2.Type) && IsSignSigned (Expr2.Type)) {
1986 /* Evaluate the result for signed operands */
1987 signed long Val1 = Expr->IVal;
1988 signed long Val2 = Expr2.IVal;
1990 case TOK_EQ: Expr->IVal = (Val1 == Val2); break;
1991 case TOK_NE: Expr->IVal = (Val1 != Val2); break;
1992 case TOK_LT: Expr->IVal = (Val1 < Val2); break;
1993 case TOK_LE: Expr->IVal = (Val1 <= Val2); break;
1994 case TOK_GE: Expr->IVal = (Val1 >= Val2); break;
1995 case TOK_GT: Expr->IVal = (Val1 > Val2); break;
1996 default: Internal ("hie_compare: got token 0x%X\n", Tok);
2001 /* Evaluate the result for unsigned operands */
2002 unsigned long Val1 = Expr->IVal;
2003 unsigned long Val2 = Expr2.IVal;
2005 case TOK_EQ: Expr->IVal = (Val1 == Val2); break;
2006 case TOK_NE: Expr->IVal = (Val1 != Val2); break;
2007 case TOK_LT: Expr->IVal = (Val1 < Val2); break;
2008 case TOK_LE: Expr->IVal = (Val1 <= Val2); break;
2009 case TOK_GE: Expr->IVal = (Val1 >= Val2); break;
2010 case TOK_GT: Expr->IVal = (Val1 > Val2); break;
2011 default: Internal ("hie_compare: got token 0x%X\n", Tok);
2017 /* If the right hand side is constant, and the generator function
2018 * expects the lhs in the primary, remove the push of the primary
2024 if ((Gen->Flags & GEN_NOPUSH) != 0) {
2025 RemoveCode (&Mark2);
2026 ltype |= CF_REG; /* Value is in register */
2030 /* Determine the type of the operation result. If the left
2031 * operand is of type char and the right is a constant, or
2032 * if both operands are of type char, we will encode the
2033 * operation as char operation. Otherwise the default
2034 * promotions are used.
2036 if (IsTypeChar (Expr->Type) && (IsTypeChar (Expr2.Type) || rconst)) {
2038 if (IsSignUnsigned (Expr->Type) || IsSignUnsigned (Expr2.Type)) {
2039 flags |= CF_UNSIGNED;
2042 flags |= CF_FORCECHAR;
2045 unsigned rtype = TypeOf (Expr2.Type) | (flags & CF_CONST);
2046 flags |= g_typeadjust (ltype, rtype);
2050 Gen->Func (flags, Expr2.IVal);
2052 /* The result is an rvalue in the primary */
2053 ED_MakeRValExpr (Expr);
2056 /* Result type is always int */
2057 Expr->Type = type_int;
2059 /* Condition codes are set */
2066 static void hie9 (ExprDesc *Expr)
2067 /* Process * and / operators. */
2069 static const GenDesc hie9_ops[] = {
2070 { TOK_STAR, GEN_NOPUSH, g_mul },
2071 { TOK_DIV, GEN_NOPUSH, g_div },
2072 { TOK_MOD, GEN_NOPUSH, g_mod },
2073 { TOK_INVALID, 0, 0 }
2077 hie_internal (hie9_ops, Expr, hie10, &UsedGen);
2082 static void parseadd (ExprDesc* Expr)
2083 /* Parse an expression with the binary plus operator. Expr contains the
2084 * unprocessed left hand side of the expression and will contain the
2085 * result of the expression on return.
2089 unsigned flags; /* Operation flags */
2090 CodeMark Mark; /* Remember code position */
2091 Type* lhst; /* Type of left hand side */
2092 Type* rhst; /* Type of right hand side */
2095 /* Skip the PLUS token */
2098 /* Get the left hand side type, initialize operation flags */
2102 /* Check for constness on both sides */
2103 if (ED_IsConst (Expr)) {
2105 /* The left hand side is a constant of some sort. Good. Get rhs */
2107 if (ED_IsConstAbs (&Expr2)) {
2109 /* Right hand side is a constant numeric value. Get the rhs type */
2112 /* Both expressions are constants. Check for pointer arithmetic */
2113 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2114 /* Left is pointer, right is int, must scale rhs */
2115 Expr->IVal += Expr2.IVal * CheckedPSizeOf (lhst);
2116 /* Result type is a pointer */
2117 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2118 /* Left is int, right is pointer, must scale lhs */
2119 Expr->IVal = Expr->IVal * CheckedPSizeOf (rhst) + Expr2.IVal;
2120 /* Result type is a pointer */
2121 Expr->Type = Expr2.Type;
2122 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2123 /* Integer addition */
2124 Expr->IVal += Expr2.IVal;
2125 typeadjust (Expr, &Expr2, 1);
2128 Error ("Invalid operands for binary operator `+'");
2133 /* lhs is a constant and rhs is not constant. Load rhs into
2136 LoadExpr (CF_NONE, &Expr2);
2138 /* Beware: The check above (for lhs) lets not only pass numeric
2139 * constants, but also constant addresses (labels), maybe even
2140 * with an offset. We have to check for that here.
2143 /* First, get the rhs type. */
2147 if (ED_IsLocAbs (Expr)) {
2148 /* A numerical constant */
2151 /* Constant address label */
2152 flags |= GlobalModeFlags (Expr) | CF_CONSTADDR;
2155 /* Check for pointer arithmetic */
2156 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2157 /* Left is pointer, right is int, must scale rhs */
2158 g_scale (CF_INT, CheckedPSizeOf (lhst));
2159 /* Operate on pointers, result type is a pointer */
2161 /* Generate the code for the add */
2162 if (ED_GetLoc (Expr) == E_LOC_ABS) {
2163 /* Numeric constant */
2164 g_inc (flags, Expr->IVal);
2166 /* Constant address */
2167 g_addaddr_static (flags, Expr->Name, Expr->IVal);
2169 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2171 /* Left is int, right is pointer, must scale lhs. */
2172 unsigned ScaleFactor = CheckedPSizeOf (rhst);
2174 /* Operate on pointers, result type is a pointer */
2176 Expr->Type = Expr2.Type;
2178 /* Since we do already have rhs in the primary, if lhs is
2179 * not a numeric constant, and the scale factor is not one
2180 * (no scaling), we must take the long way over the stack.
2182 if (ED_IsLocAbs (Expr)) {
2183 /* Numeric constant, scale lhs */
2184 Expr->IVal *= ScaleFactor;
2185 /* Generate the code for the add */
2186 g_inc (flags, Expr->IVal);
2187 } else if (ScaleFactor == 1) {
2188 /* Constant address but no need to scale */
2189 g_addaddr_static (flags, Expr->Name, Expr->IVal);
2191 /* Constant address that must be scaled */
2192 g_push (TypeOf (Expr2.Type), 0); /* rhs --> stack */
2193 g_getimmed (flags, Expr->Name, Expr->IVal);
2194 g_scale (CF_PTR, ScaleFactor);
2197 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2198 /* Integer addition */
2199 flags |= typeadjust (Expr, &Expr2, 1);
2200 /* Generate the code for the add */
2201 if (ED_IsLocAbs (Expr)) {
2202 /* Numeric constant */
2203 g_inc (flags, Expr->IVal);
2205 /* Constant address */
2206 g_addaddr_static (flags, Expr->Name, Expr->IVal);
2210 Error ("Invalid operands for binary operator `+'");
2214 /* Result is a rvalue in primary register */
2215 ED_MakeRValExpr (Expr);
2220 /* Left hand side is not constant. Get the value onto the stack. */
2221 LoadExpr (CF_NONE, Expr); /* --> primary register */
2223 g_push (TypeOf (Expr->Type), 0); /* --> stack */
2225 /* Evaluate the rhs */
2226 MarkedExprWithCheck (hie9, &Expr2);
2228 /* Check for a constant rhs expression */
2229 if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) {
2231 /* Right hand side is a constant. Get the rhs type */
2234 /* Remove pushed value from stack */
2237 /* Check for pointer arithmetic */
2238 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2239 /* Left is pointer, right is int, must scale rhs */
2240 Expr2.IVal *= CheckedPSizeOf (lhst);
2241 /* Operate on pointers, result type is a pointer */
2243 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2244 /* Left is int, right is pointer, must scale lhs (ptr only) */
2245 g_scale (CF_INT | CF_CONST, CheckedPSizeOf (rhst));
2246 /* Operate on pointers, result type is a pointer */
2248 Expr->Type = Expr2.Type;
2249 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2250 /* Integer addition */
2251 flags = typeadjust (Expr, &Expr2, 1);
2254 Error ("Invalid operands for binary operator `+'");
2258 /* Generate code for the add */
2259 g_inc (flags | CF_CONST, Expr2.IVal);
2263 /* Not constant, load into the primary */
2264 LoadExpr (CF_NONE, &Expr2);
2266 /* lhs and rhs are not constant. Get the rhs type. */
2269 /* Check for pointer arithmetic */
2270 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2271 /* Left is pointer, right is int, must scale rhs */
2272 g_scale (CF_INT, CheckedPSizeOf (lhst));
2273 /* Operate on pointers, result type is a pointer */
2275 } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2276 /* Left is int, right is pointer, must scale lhs */
2277 g_tosint (TypeOf (rhst)); /* Make sure, TOS is int */
2278 g_swap (CF_INT); /* Swap TOS and primary */
2279 g_scale (CF_INT, CheckedPSizeOf (rhst));
2280 /* Operate on pointers, result type is a pointer */
2282 Expr->Type = Expr2.Type;
2283 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2284 /* Integer addition. Note: Result is never constant.
2285 * Problem here is that typeadjust does not know if the
2286 * variable is an rvalue or lvalue, so if both operands
2287 * are dereferenced constant numeric addresses, typeadjust
2288 * thinks the operation works on constants. Removing
2289 * CF_CONST here means handling the symptoms, however, the
2290 * whole parser is such a mess that I fear to break anything
2291 * when trying to apply another solution.
2293 flags = typeadjust (Expr, &Expr2, 0) & ~CF_CONST;
2296 Error ("Invalid operands for binary operator `+'");
2300 /* Generate code for the add */
2305 /* Result is a rvalue in primary register */
2306 ED_MakeRValExpr (Expr);
2309 /* Condition codes not set */
2310 ED_MarkAsUntested (Expr);
2316 static void parsesub (ExprDesc* Expr)
2317 /* Parse an expression with the binary minus operator. Expr contains the
2318 * unprocessed left hand side of the expression and will contain the
2319 * result of the expression on return.
2323 unsigned flags; /* Operation flags */
2324 Type* lhst; /* Type of left hand side */
2325 Type* rhst; /* Type of right hand side */
2326 CodeMark Mark1; /* Save position of output queue */
2327 CodeMark Mark2; /* Another position in the queue */
2328 int rscale; /* Scale factor for the result */
2331 /* Skip the MINUS token */
2334 /* Get the left hand side type, initialize operation flags */
2336 rscale = 1; /* Scale by 1, that is, don't scale */
2338 /* Remember the output queue position, then bring the value onto the stack */
2339 GetCodePos (&Mark1);
2340 LoadExpr (CF_NONE, Expr); /* --> primary register */
2341 GetCodePos (&Mark2);
2342 g_push (TypeOf (lhst), 0); /* --> stack */
2344 /* Parse the right hand side */
2345 MarkedExprWithCheck (hie9, &Expr2);
2347 /* Check for a constant rhs expression */
2348 if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) {
2350 /* The right hand side is constant. Get the rhs type. */
2353 /* Check left hand side */
2354 if (ED_IsConstAbs (Expr)) {
2356 /* Both sides are constant, remove generated code */
2357 RemoveCode (&Mark1);
2359 /* Check for pointer arithmetic */
2360 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2361 /* Left is pointer, right is int, must scale rhs */
2362 Expr->IVal -= Expr2.IVal * CheckedPSizeOf (lhst);
2363 /* Operate on pointers, result type is a pointer */
2364 } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2365 /* Left is pointer, right is pointer, must scale result */
2366 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2367 Error ("Incompatible pointer types");
2369 Expr->IVal = (Expr->IVal - Expr2.IVal) /
2370 CheckedPSizeOf (lhst);
2372 /* Operate on pointers, result type is an integer */
2373 Expr->Type = type_int;
2374 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2375 /* Integer subtraction */
2376 typeadjust (Expr, &Expr2, 1);
2377 Expr->IVal -= Expr2.IVal;
2380 Error ("Invalid operands for binary operator `-'");
2383 /* Result is constant, condition codes not set */
2384 ED_MarkAsUntested (Expr);
2388 /* Left hand side is not constant, right hand side is.
2389 * Remove pushed value from stack.
2391 RemoveCode (&Mark2);
2393 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2394 /* Left is pointer, right is int, must scale rhs */
2395 Expr2.IVal *= CheckedPSizeOf (lhst);
2396 /* Operate on pointers, result type is a pointer */
2398 } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2399 /* Left is pointer, right is pointer, must scale result */
2400 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2401 Error ("Incompatible pointer types");
2403 rscale = CheckedPSizeOf (lhst);
2405 /* Operate on pointers, result type is an integer */
2407 Expr->Type = type_int;
2408 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2409 /* Integer subtraction */
2410 flags = typeadjust (Expr, &Expr2, 1);
2413 Error ("Invalid operands for binary operator `-'");
2417 /* Do the subtraction */
2418 g_dec (flags | CF_CONST, Expr2.IVal);
2420 /* If this was a pointer subtraction, we must scale the result */
2422 g_scale (flags, -rscale);
2425 /* Result is a rvalue in the primary register */
2426 ED_MakeRValExpr (Expr);
2427 ED_MarkAsUntested (Expr);
2433 /* Not constant, load into the primary */
2434 LoadExpr (CF_NONE, &Expr2);
2436 /* Right hand side is not constant. Get the rhs type. */
2439 /* Check for pointer arithmetic */
2440 if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2441 /* Left is pointer, right is int, must scale rhs */
2442 g_scale (CF_INT, CheckedPSizeOf (lhst));
2443 /* Operate on pointers, result type is a pointer */
2445 } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2446 /* Left is pointer, right is pointer, must scale result */
2447 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2448 Error ("Incompatible pointer types");
2450 rscale = CheckedPSizeOf (lhst);
2452 /* Operate on pointers, result type is an integer */
2454 Expr->Type = type_int;
2455 } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2456 /* Integer subtraction. If the left hand side descriptor says that
2457 * the lhs is const, we have to remove this mark, since this is no
2458 * longer true, lhs is on stack instead.
2460 if (ED_IsLocAbs (Expr)) {
2461 ED_MakeRValExpr (Expr);
2463 /* Adjust operand types */
2464 flags = typeadjust (Expr, &Expr2, 0);
2467 Error ("Invalid operands for binary operator `-'");
2471 /* Generate code for the sub (the & is a hack here) */
2472 g_sub (flags & ~CF_CONST, 0);
2474 /* If this was a pointer subtraction, we must scale the result */
2476 g_scale (flags, -rscale);
2479 /* Result is a rvalue in the primary register */
2480 ED_MakeRValExpr (Expr);
2481 ED_MarkAsUntested (Expr);
2487 void hie8 (ExprDesc* Expr)
2488 /* Process + and - binary operators. */
2491 while (CurTok.Tok == TOK_PLUS || CurTok.Tok == TOK_MINUS) {
2492 if (CurTok.Tok == TOK_PLUS) {
2502 static void hie6 (ExprDesc* Expr)
2503 /* Handle greater-than type comparators */
2505 static const GenDesc hie6_ops [] = {
2506 { TOK_LT, GEN_NOPUSH, g_lt },
2507 { TOK_LE, GEN_NOPUSH, g_le },
2508 { TOK_GE, GEN_NOPUSH, g_ge },
2509 { TOK_GT, GEN_NOPUSH, g_gt },
2510 { TOK_INVALID, 0, 0 }
2512 hie_compare (hie6_ops, Expr, ShiftExpr);
2517 static void hie5 (ExprDesc* Expr)
2518 /* Handle == and != */
2520 static const GenDesc hie5_ops[] = {
2521 { TOK_EQ, GEN_NOPUSH, g_eq },
2522 { TOK_NE, GEN_NOPUSH, g_ne },
2523 { TOK_INVALID, 0, 0 }
2525 hie_compare (hie5_ops, Expr, hie6);
2530 static void hie4 (ExprDesc* Expr)
2531 /* Handle & (bitwise and) */
2533 static const GenDesc hie4_ops[] = {
2534 { TOK_AND, GEN_NOPUSH, g_and },
2535 { TOK_INVALID, 0, 0 }
2539 hie_internal (hie4_ops, Expr, hie5, &UsedGen);
2544 static void hie3 (ExprDesc* Expr)
2545 /* Handle ^ (bitwise exclusive or) */
2547 static const GenDesc hie3_ops[] = {
2548 { TOK_XOR, GEN_NOPUSH, g_xor },
2549 { TOK_INVALID, 0, 0 }
2553 hie_internal (hie3_ops, Expr, hie4, &UsedGen);
2558 static void hie2 (ExprDesc* Expr)
2559 /* Handle | (bitwise or) */
2561 static const GenDesc hie2_ops[] = {
2562 { TOK_OR, GEN_NOPUSH, g_or },
2563 { TOK_INVALID, 0, 0 }
2567 hie_internal (hie2_ops, Expr, hie3, &UsedGen);
2572 static void hieAndPP (ExprDesc* Expr)
2573 /* Process "exp && exp" in preprocessor mode (that is, when the parser is
2574 * called recursively from the preprocessor.
2579 ConstAbsIntExpr (hie2, Expr);
2580 while (CurTok.Tok == TOK_BOOL_AND) {
2586 ConstAbsIntExpr (hie2, &Expr2);
2588 /* Combine the two */
2589 Expr->IVal = (Expr->IVal && Expr2.IVal);
2595 static void hieOrPP (ExprDesc *Expr)
2596 /* Process "exp || exp" in preprocessor mode (that is, when the parser is
2597 * called recursively from the preprocessor.
2602 ConstAbsIntExpr (hieAndPP, Expr);
2603 while (CurTok.Tok == TOK_BOOL_OR) {
2609 ConstAbsIntExpr (hieAndPP, &Expr2);
2611 /* Combine the two */
2612 Expr->IVal = (Expr->IVal || Expr2.IVal);
2618 static void hieAnd (ExprDesc* Expr, unsigned TrueLab, int* BoolOp)
2619 /* Process "exp && exp" */
2625 if (CurTok.Tok == TOK_BOOL_AND) {
2627 /* Tell our caller that we're evaluating a boolean */
2630 /* Get a label that we will use for false expressions */
2631 FalseLab = GetLocalLabel ();
2633 /* If the expr hasn't set condition codes, set the force-test flag */
2634 if (!ED_IsTested (Expr)) {
2635 ED_MarkForTest (Expr);
2638 /* Load the value */
2639 LoadExpr (CF_FORCECHAR, Expr);
2641 /* Generate the jump */
2642 g_falsejump (CF_NONE, FalseLab);
2644 /* Parse more boolean and's */
2645 while (CurTok.Tok == TOK_BOOL_AND) {
2652 if (!ED_IsTested (&Expr2)) {
2653 ED_MarkForTest (&Expr2);
2655 LoadExpr (CF_FORCECHAR, &Expr2);
2657 /* Do short circuit evaluation */
2658 if (CurTok.Tok == TOK_BOOL_AND) {
2659 g_falsejump (CF_NONE, FalseLab);
2661 /* Last expression - will evaluate to true */
2662 g_truejump (CF_NONE, TrueLab);
2666 /* Define the false jump label here */
2667 g_defcodelabel (FalseLab);
2669 /* The result is an rvalue in primary */
2670 ED_MakeRValExpr (Expr);
2671 ED_TestDone (Expr); /* Condition codes are set */
2677 static void hieOr (ExprDesc *Expr)
2678 /* Process "exp || exp". */
2681 int BoolOp = 0; /* Did we have a boolean op? */
2682 int AndOp; /* Did we have a && operation? */
2683 unsigned TrueLab; /* Jump to this label if true */
2687 TrueLab = GetLocalLabel ();
2689 /* Call the next level parser */
2690 hieAnd (Expr, TrueLab, &BoolOp);
2692 /* Any boolean or's? */
2693 if (CurTok.Tok == TOK_BOOL_OR) {
2695 /* If the expr hasn't set condition codes, set the force-test flag */
2696 if (!ED_IsTested (Expr)) {
2697 ED_MarkForTest (Expr);
2700 /* Get first expr */
2701 LoadExpr (CF_FORCECHAR, Expr);
2703 /* For each expression jump to TrueLab if true. Beware: If we
2704 * had && operators, the jump is already in place!
2707 g_truejump (CF_NONE, TrueLab);
2710 /* Remember that we had a boolean op */
2713 /* while there's more expr */
2714 while (CurTok.Tok == TOK_BOOL_OR) {
2721 hieAnd (&Expr2, TrueLab, &AndOp);
2722 if (!ED_IsTested (&Expr2)) {
2723 ED_MarkForTest (&Expr2);
2725 LoadExpr (CF_FORCECHAR, &Expr2);
2727 /* If there is more to come, add shortcut boolean eval. */
2728 g_truejump (CF_NONE, TrueLab);
2732 /* The result is an rvalue in primary */
2733 ED_MakeRValExpr (Expr);
2734 ED_TestDone (Expr); /* Condition codes are set */
2737 /* If we really had boolean ops, generate the end sequence */
2739 DoneLab = GetLocalLabel ();
2740 g_getimmed (CF_INT | CF_CONST, 0, 0); /* Load FALSE */
2741 g_falsejump (CF_NONE, DoneLab);
2742 g_defcodelabel (TrueLab);
2743 g_getimmed (CF_INT | CF_CONST, 1, 0); /* Load TRUE */
2744 g_defcodelabel (DoneLab);
2750 static void hieQuest (ExprDesc* Expr)
2751 /* Parse the ternary operator */
2755 CodeMark TrueCodeEnd;
2756 ExprDesc Expr2; /* Expression 2 */
2757 ExprDesc Expr3; /* Expression 3 */
2758 int Expr2IsNULL; /* Expression 2 is a NULL pointer */
2759 int Expr3IsNULL; /* Expression 3 is a NULL pointer */
2760 Type* ResultType; /* Type of result */
2763 /* Call the lower level eval routine */
2764 if (Preprocessing) {
2770 /* Check if it's a ternary expression */
2771 if (CurTok.Tok == TOK_QUEST) {
2773 if (!ED_IsTested (Expr)) {
2774 /* Condition codes not set, request a test */
2775 ED_MarkForTest (Expr);
2777 LoadExpr (CF_NONE, Expr);
2778 FalseLab = GetLocalLabel ();
2779 g_falsejump (CF_NONE, FalseLab);
2781 /* Parse second expression. Remember for later if it is a NULL pointer
2782 * expression, then load it into the primary.
2784 ExprWithCheck (hie1, &Expr2);
2785 Expr2IsNULL = ED_IsNullPtr (&Expr2);
2786 if (!IsTypeVoid (Expr2.Type)) {
2787 /* Load it into the primary */
2788 LoadExpr (CF_NONE, &Expr2);
2789 ED_MakeRValExpr (&Expr2);
2790 Expr2.Type = PtrConversion (Expr2.Type);
2793 /* Remember the current code position */
2794 GetCodePos (&TrueCodeEnd);
2796 /* Jump around the evaluation of the third expression */
2797 TrueLab = GetLocalLabel ();
2801 /* Jump here if the first expression was false */
2802 g_defcodelabel (FalseLab);
2804 /* Parse third expression. Remember for later if it is a NULL pointer
2805 * expression, then load it into the primary.
2807 ExprWithCheck (hie1, &Expr3);
2808 Expr3IsNULL = ED_IsNullPtr (&Expr3);
2809 if (!IsTypeVoid (Expr3.Type)) {
2810 /* Load it into the primary */
2811 LoadExpr (CF_NONE, &Expr3);
2812 ED_MakeRValExpr (&Expr3);
2813 Expr3.Type = PtrConversion (Expr3.Type);
2816 /* Check if any conversions are needed, if so, do them.
2817 * Conversion rules for ?: expression are:
2818 * - if both expressions are int expressions, default promotion
2819 * rules for ints apply.
2820 * - if both expressions are pointers of the same type, the
2821 * result of the expression is of this type.
2822 * - if one of the expressions is a pointer and the other is
2823 * a zero constant, the resulting type is that of the pointer
2825 * - if both expressions are void expressions, the result is of
2827 * - all other cases are flagged by an error.
2829 if (IsClassInt (Expr2.Type) && IsClassInt (Expr3.Type)) {
2831 CodeMark CvtCodeStart;
2832 CodeMark CvtCodeEnd;
2835 /* Get common type */
2836 ResultType = promoteint (Expr2.Type, Expr3.Type);
2838 /* Convert the third expression to this type if needed */
2839 TypeConversion (&Expr3, ResultType);
2841 /* Emit conversion code for the second expression, but remember
2842 * where it starts end ends.
2844 GetCodePos (&CvtCodeStart);
2845 TypeConversion (&Expr2, ResultType);
2846 GetCodePos (&CvtCodeEnd);
2848 /* If we had conversion code, move it to the right place */
2849 if (!CodeRangeIsEmpty (&CvtCodeStart, &CvtCodeEnd)) {
2850 MoveCode (&CvtCodeStart, &CvtCodeEnd, &TrueCodeEnd);
2853 } else if (IsClassPtr (Expr2.Type) && IsClassPtr (Expr3.Type)) {
2854 /* Must point to same type */
2855 if (TypeCmp (Indirect (Expr2.Type), Indirect (Expr3.Type)) < TC_EQUAL) {
2856 Error ("Incompatible pointer types");
2858 /* Result has the common type */
2859 ResultType = Expr2.Type;
2860 } else if (IsClassPtr (Expr2.Type) && Expr3IsNULL) {
2861 /* Result type is pointer, no cast needed */
2862 ResultType = Expr2.Type;
2863 } else if (Expr2IsNULL && IsClassPtr (Expr3.Type)) {
2864 /* Result type is pointer, no cast needed */
2865 ResultType = Expr3.Type;
2866 } else if (IsTypeVoid (Expr2.Type) && IsTypeVoid (Expr3.Type)) {
2867 /* Result type is void */
2868 ResultType = Expr3.Type;
2870 Error ("Incompatible types");
2871 ResultType = Expr2.Type; /* Doesn't matter here */
2874 /* Define the final label */
2875 g_defcodelabel (TrueLab);
2877 /* Setup the target expression */
2878 ED_MakeRValExpr (Expr);
2879 Expr->Type = ResultType;
2885 static void opeq (const GenDesc* Gen, ExprDesc* Expr, const char* Op)
2886 /* Process "op=" operators. */
2893 /* op= can only be used with lvalues */
2894 if (!ED_IsLVal (Expr)) {
2895 Error ("Invalid lvalue in assignment");
2899 /* The left side must not be const qualified */
2900 if (IsQualConst (Expr->Type)) {
2901 Error ("Assignment to const");
2904 /* There must be an integer or pointer on the left side */
2905 if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
2906 Error ("Invalid left operand type");
2907 /* Continue. Wrong code will be generated, but the compiler won't
2908 * break, so this is the best error recovery.
2912 /* Skip the operator token */
2915 /* Determine the type of the lhs */
2916 flags = TypeOf (Expr->Type);
2917 MustScale = (Gen->Func == g_add || Gen->Func == g_sub) && IsTypePtr (Expr->Type);
2919 /* Get the lhs address on stack (if needed) */
2922 /* Fetch the lhs into the primary register if needed */
2923 LoadExpr (CF_NONE, Expr);
2925 /* Bring the lhs on stack */
2929 /* Evaluate the rhs */
2930 MarkedExprWithCheck (hie1, &Expr2);
2932 /* The rhs must be an integer (or a float, but we don't support that yet */
2933 if (!IsClassInt (Expr2.Type)) {
2934 Error ("Invalid right operand for binary operator `%s'", Op);
2935 /* Continue. Wrong code will be generated, but the compiler won't
2936 * break, so this is the best error recovery.
2940 /* Check for a constant expression */
2941 if (ED_IsConstAbs (&Expr2) && ED_CodeRangeIsEmpty (&Expr2)) {
2942 /* The resulting value is a constant. If the generator has the NOPUSH
2943 * flag set, don't push the lhs.
2945 if (Gen->Flags & GEN_NOPUSH) {
2949 /* lhs is a pointer, scale rhs */
2950 Expr2.IVal *= CheckedSizeOf (Expr->Type+1);
2953 /* If the lhs is character sized, the operation may be later done
2956 if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
2957 flags |= CF_FORCECHAR;
2960 /* Special handling for add and sub - some sort of a hack, but short code */
2961 if (Gen->Func == g_add) {
2962 g_inc (flags | CF_CONST, Expr2.IVal);
2963 } else if (Gen->Func == g_sub) {
2964 g_dec (flags | CF_CONST, Expr2.IVal);
2966 if (Expr2.IVal == 0) {
2967 /* Check for div by zero/mod by zero */
2968 if (Gen->Func == g_div) {
2969 Error ("Division by zero");
2970 } else if (Gen->Func == g_mod) {
2971 Error ("Modulo operation with zero");
2974 Gen->Func (flags | CF_CONST, Expr2.IVal);
2978 /* rhs is not constant. Load into the primary */
2979 LoadExpr (CF_NONE, &Expr2);
2981 /* lhs is a pointer, scale rhs */
2982 g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Expr->Type+1));
2985 /* If the lhs is character sized, the operation may be later done
2988 if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
2989 flags |= CF_FORCECHAR;
2992 /* Adjust the types of the operands if needed */
2993 Gen->Func (g_typeadjust (flags, TypeOf (Expr2.Type)), 0);
2996 ED_MakeRValExpr (Expr);
3001 static void addsubeq (const GenDesc* Gen, ExprDesc *Expr, const char* Op)
3002 /* Process the += and -= operators */
3010 /* We're currently only able to handle some adressing modes */
3011 if (ED_GetLoc (Expr) == E_LOC_EXPR || ED_GetLoc (Expr) == E_LOC_PRIMARY) {
3012 /* Use generic routine */
3013 opeq (Gen, Expr, Op);
3017 /* We must have an lvalue */
3018 if (ED_IsRVal (Expr)) {
3019 Error ("Invalid lvalue in assignment");
3023 /* The left side must not be const qualified */
3024 if (IsQualConst (Expr->Type)) {
3025 Error ("Assignment to const");
3028 /* There must be an integer or pointer on the left side */
3029 if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
3030 Error ("Invalid left operand type");
3031 /* Continue. Wrong code will be generated, but the compiler won't
3032 * break, so this is the best error recovery.
3036 /* Skip the operator */
3039 /* Check if we have a pointer expression and must scale rhs */
3040 MustScale = IsTypePtr (Expr->Type);
3042 /* Initialize the code generator flags */
3046 /* Evaluate the rhs. We expect an integer here, since float is not
3050 if (!IsClassInt (Expr2.Type)) {
3051 Error ("Invalid right operand for binary operator `%s'", Op);
3052 /* Continue. Wrong code will be generated, but the compiler won't
3053 * break, so this is the best error recovery.
3056 if (ED_IsConstAbs (&Expr2)) {
3057 /* The resulting value is a constant. Scale it. */
3059 Expr2.IVal *= CheckedSizeOf (Indirect (Expr->Type));
3064 /* Not constant, load into the primary */
3065 LoadExpr (CF_NONE, &Expr2);
3067 /* lhs is a pointer, scale rhs */
3068 g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Indirect (Expr->Type)));
3072 /* Setup the code generator flags */
3073 lflags |= TypeOf (Expr->Type) | GlobalModeFlags (Expr) | CF_FORCECHAR;
3074 rflags |= TypeOf (Expr2.Type) | CF_FORCECHAR;
3076 /* Convert the type of the lhs to that of the rhs */
3077 g_typecast (lflags, rflags);
3079 /* Output apropriate code depending on the location */
3080 switch (ED_GetLoc (Expr)) {
3083 /* Absolute: numeric address or const */
3084 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3085 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3087 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3092 /* Global variable */
3093 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3094 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3096 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3102 /* Static variable or literal in the literal pool */
3103 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3104 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3106 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3110 case E_LOC_REGISTER:
3111 /* Register variable */
3112 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3113 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3115 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
3120 /* Value on the stack */
3121 if (Gen->Tok == TOK_PLUS_ASSIGN) {
3122 g_addeqlocal (lflags, Expr->IVal, Expr2.IVal);
3124 g_subeqlocal (lflags, Expr->IVal, Expr2.IVal);
3129 Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
3132 /* Expression is a rvalue in the primary now */
3133 ED_MakeRValExpr (Expr);
3138 void hie1 (ExprDesc* Expr)
3139 /* Parse first level of expression hierarchy. */
3142 switch (CurTok.Tok) {
3148 case TOK_PLUS_ASSIGN:
3149 addsubeq (&GenPASGN, Expr, "+=");
3152 case TOK_MINUS_ASSIGN:
3153 addsubeq (&GenSASGN, Expr, "-=");
3156 case TOK_MUL_ASSIGN:
3157 opeq (&GenMASGN, Expr, "*=");
3160 case TOK_DIV_ASSIGN:
3161 opeq (&GenDASGN, Expr, "/=");
3164 case TOK_MOD_ASSIGN:
3165 opeq (&GenMOASGN, Expr, "%=");
3168 case TOK_SHL_ASSIGN:
3169 opeq (&GenSLASGN, Expr, "<<=");
3172 case TOK_SHR_ASSIGN:
3173 opeq (&GenSRASGN, Expr, ">>=");
3176 case TOK_AND_ASSIGN:
3177 opeq (&GenAASGN, Expr, "&=");
3180 case TOK_XOR_ASSIGN:
3181 opeq (&GenXOASGN, Expr, "^=");
3185 opeq (&GenOASGN, Expr, "|=");
3195 void hie0 (ExprDesc *Expr)
3196 /* Parse comma operator. */
3199 while (CurTok.Tok == TOK_COMMA) {
3207 int evalexpr (unsigned Flags, void (*Func) (ExprDesc*), ExprDesc* Expr)
3208 /* Will evaluate an expression via the given function. If the result is a
3209 * constant, 0 is returned and the value is put in the Expr struct. If the
3210 * result is not constant, LoadExpr is called to bring the value into the
3211 * primary register and 1 is returned.
3215 ExprWithCheck (Func, Expr);
3217 /* Check for a constant expression */
3218 if (ED_IsConstAbs (Expr)) {
3219 /* Constant expression */
3222 /* Not constant, load into the primary */
3223 LoadExpr (Flags, Expr);
3230 void Expression0 (ExprDesc* Expr)
3231 /* Evaluate an expression via hie0 and put the result into the primary register */
3233 ExprWithCheck (hie0, Expr);
3234 LoadExpr (CF_NONE, Expr);
3239 void ConstExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3240 /* Will evaluate an expression via the given function. If the result is not
3241 * a constant of some sort, a diagnostic will be printed, and the value is
3242 * replaced by a constant one to make sure there are no internal errors that
3243 * result from this input error.
3246 ExprWithCheck (Func, Expr);
3247 if (!ED_IsConst (Expr)) {
3248 Error ("Constant expression expected");
3249 /* To avoid any compiler errors, make the expression a valid const */
3250 ED_MakeConstAbsInt (Expr, 1);
3256 void BoolExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3257 /* Will evaluate an expression via the given function. If the result is not
3258 * something that may be evaluated in a boolean context, a diagnostic will be
3259 * printed, and the value is replaced by a constant one to make sure there
3260 * are no internal errors that result from this input error.
3263 ExprWithCheck (Func, Expr);
3264 if (!ED_IsBool (Expr)) {
3265 Error ("Boolean expression expected");
3266 /* To avoid any compiler errors, make the expression a valid int */
3267 ED_MakeConstAbsInt (Expr, 1);
3273 void ConstAbsIntExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3274 /* Will evaluate an expression via the given function. If the result is not
3275 * a constant numeric integer value, a diagnostic will be printed, and the
3276 * value is replaced by a constant one to make sure there are no internal
3277 * errors that result from this input error.
3280 ExprWithCheck (Func, Expr);
3281 if (!ED_IsConstAbsInt (Expr)) {
3282 Error ("Constant integer expression expected");
3283 /* To avoid any compiler errors, make the expression a valid const */
3284 ED_MakeConstAbsInt (Expr, 1);