Ejemplo n.º 1
0
static void DoStatement (void)
/* Handle the 'do' statement */
{
    /* Get the loop control labels */
    unsigned LoopLabel      = GetLocalLabel ();
    unsigned BreakLabel     = GetLocalLabel ();
    unsigned ContinueLabel  = GetLocalLabel ();

    /* Skip the while token */
    NextToken ();

    /* Add the loop to the loop stack */
    AddLoop (BreakLabel, ContinueLabel);

    /* Define the loop label */
    g_defcodelabel (LoopLabel);

    /* Parse the loop body */
    Statement (0);

    /* Output the label for a continue */
    g_defcodelabel (ContinueLabel);

    /* Parse the end condition */
    Consume (TOK_WHILE, "`while' expected");
    TestInParens (LoopLabel, 1);
    ConsumeSemi ();

    /* Define the break label */
    g_defcodelabel (BreakLabel);

    /* Remove the loop from the loop stack */
    DelLoop ();
}
Ejemplo n.º 2
0
static void WhileStatement (void)
/* Handle the 'while' statement */
{
    int         PendingToken;
    CodeMark    CondCodeStart;  /* Start of condition evaluation code */
    CodeMark    CondCodeEnd;    /* End of condition evaluation code */
    CodeMark    Here;           /* "Here" location of code */

    /* Get the loop control labels */
    unsigned LoopLabel  = GetLocalLabel ();
    unsigned BreakLabel = GetLocalLabel ();
    unsigned CondLabel  = GetLocalLabel ();

    /* Skip the while token */
    NextToken ();

    /* Add the loop to the loop stack. In case of a while loop, the condition
    ** label is used for continue statements.
    */
    AddLoop (BreakLabel, CondLabel);

    /* We will move the code that evaluates the while condition to the end of
    ** the loop, so generate a jump here.
    */
    g_jump (CondLabel);

    /* Remember the current position */
    GetCodePos (&CondCodeStart);

    /* Emit the code position label */
    g_defcodelabel (CondLabel);

    /* Test the loop condition */
    TestInParens (LoopLabel, 1);

    /* Remember the end of the condition evaluation code */
    GetCodePos (&CondCodeEnd);

    /* Define the head label */
    g_defcodelabel (LoopLabel);

    /* Loop body */
    Statement (&PendingToken);

    /* Move the test code here */
    GetCodePos (&Here);
    MoveCode (&CondCodeStart, &CondCodeEnd, &Here);

    /* Exit label */
    g_defcodelabel (BreakLabel);

    /* Eat remaining tokens that were delayed because of line info
    ** correctness
    */
    SkipPending (PendingToken);

    /* Remove the loop from the loop stack */
    DelLoop ();
}
Ejemplo n.º 3
0
static int IfStatement (void)
/* Handle an 'if' statement */
{
    unsigned Label1;
    unsigned TestResult;
    int GotBreak;

    /* Skip the if */
    NextToken ();

    /* Generate a jump label and parse the condition */
    Label1 = GetLocalLabel ();
    TestResult = TestInParens (Label1, 0);

    /* Parse the if body */
    GotBreak = Statement (0);

    /* Else clause present? */
    if (CurTok.Tok != TOK_ELSE) {

        g_defcodelabel (Label1);

        /* Since there's no else clause, we're not sure, if the a break
        ** statement is really executed.
        */
        return 0;

    } else {

        /* Generate a jump around the else branch */
        unsigned Label2 = GetLocalLabel ();
        g_jump (Label2);

        /* Skip the else */
        NextToken ();

        /* If the if expression was always true, the code in the else branch
        ** is never executed. Output a warning if this is the case.
        */
        if (TestResult == TESTEXPR_TRUE) {
            Warning ("Unreachable code");
        }

        /* Define the target for the first test */
        g_defcodelabel (Label1);

        /* Total break only if both branches had a break. */
        GotBreak &= Statement (0);

        /* Generate the label for the else clause */
        g_defcodelabel (Label2);

        /* Done */
        return GotBreak;
    }
}
Ejemplo n.º 4
0
void DefaultLabel (void)
/* Handle a default label */
{
    /* Default case */
    NextToken ();

    /* Now check if we're inside a switch statement */
    if (Switch != 0) {

        /* Check if we do already have a default branch */
        if (Switch->DefaultLabel == 0) {

            /* Generate and emit the default label */
            Switch->DefaultLabel = GetLocalLabel ();
            g_defcodelabel (Switch->DefaultLabel);

        } else {
            /* We had the default label already */
            Error ("Multiple default labels in one switch");
        }

    } else {

        /* case keyword outside a switch statement */
        Error ("`default' label not within a switch statement");

    }

    /* Skip the colon */
    ConsumeColon ();
}
Ejemplo n.º 5
0
static void WhileStatement (void)
/* Handle the 'while' statement */
{
    int PendingToken;

    /* Get the loop control labels */
    unsigned LoopLabel  = GetLocalLabel ();
    unsigned BreakLabel = GetLocalLabel ();

    /* Skip the while token */
    NextToken ();

    /* Add the loop to the loop stack. In case of a while loop, the loop head
     * label is used for continue statements.
     */
    AddLoop (BreakLabel, LoopLabel);

    /* Define the head label */
    g_defcodelabel (LoopLabel);

    /* Test the loop condition */
    TestInParens (BreakLabel, 0);

    /* Loop body */
    Statement (&PendingToken);

    /* Jump back to loop top */
    g_jump (LoopLabel);

    /* Exit label */
    g_defcodelabel (BreakLabel);

    /* Eat remaining tokens that were delayed because of line info
     * correctness
     */
    SkipPending (PendingToken);

    /* Remove the loop from the loop stack */
    DelLoop ();
}
Ejemplo n.º 6
0
void NewFunc (SymEntry* Func)
/* Parse argument declarations and function body. */
{
    int         C99MainFunc = 0;/* Flag for C99 main function returning int */
    SymEntry*   Param;

    /* Get the function descriptor from the function entry */
    FuncDesc* D = Func->V.F.Func;

    /* Allocate the function activation record for the function */
    CurrentFunc = NewFunction (Func);

    /* Reenter the lexical level */
    ReenterFunctionLevel (D);

    /* Check if the function header contains unnamed parameters. These are
     * only allowed in cc65 mode.
     */
    if ((D->Flags & FD_UNNAMED_PARAMS) != 0 && (IS_Get (&Standard) != STD_CC65)) {
        Error ("Parameter name omitted");
    }

    /* Declare two special functions symbols: __fixargs__ and __argsize__.
     * The latter is different depending on the type of the function (variadic
     * or not).
     */
    AddConstSym ("__fixargs__", type_uint, SC_DEF | SC_CONST, D->ParamSize);
    if (D->Flags & FD_VARIADIC) {
        /* Variadic function. The variable must be const. */
        static const Type T[] = { TYPE(T_UCHAR | T_QUAL_CONST), TYPE(T_END) };
        AddLocalSym ("__argsize__", T, SC_DEF | SC_REF | SC_AUTO, 0);
    } else {
        /* Non variadic */
        AddConstSym ("__argsize__", type_uchar, SC_DEF | SC_CONST, D->ParamSize);
    }

    /* Function body now defined */
    Func->Flags |= SC_DEF;

    /* Special handling for main() */
    if (strcmp (Func->Name, "main") == 0) {

        /* Mark this as the main function */
        CurrentFunc->Flags |= FF_IS_MAIN;

        /* Main cannot be a fastcall function */
        if (IsQualFastcall (Func->Type)) {
            Error ("`main' cannot be declared as __fastcall__");
        }

        /* If cc65 extensions aren't enabled, don't allow a main function that
         * doesn't return an int.
         */
        if (IS_Get (&Standard) != STD_CC65 && CurrentFunc->ReturnType[0].C != T_INT) {
            Error ("`main' must always return an int");
        }

        /* Add a forced import of a symbol that is contained in the startup
         * code. This will force the startup code to be linked in.
         */
        g_importstartup ();

        /* If main() takes parameters, generate a forced import to a function
         * that will setup these parameters. This way, programs that do not
         * need the additional code will not get it.
         */
        if (D->ParamCount > 0 || (D->Flags & FD_VARIADIC) != 0) {
            g_importmainargs ();
        }

        /* Determine if this is a main function in a C99 environment that
         * returns an int.
         */
        if (IsTypeInt (F_GetReturnType (CurrentFunc)) &&
            IS_Get (&Standard) == STD_C99) {
            C99MainFunc = 1;
        }
    }

    /* Allocate code and data segments for this function */
    Func->V.F.Seg = PushSegments (Func);

    /* Allocate a new literal pool */
    PushLiteralPool (Func);

    /* If this is a fastcall function, push the last parameter onto the stack */
    if (IsQualFastcall (Func->Type) && D->ParamCount > 0) {

        unsigned Flags;

        /* Fastcall functions may never have an ellipsis or the compiler is buggy */
        CHECK ((D->Flags & FD_VARIADIC) == 0);

        /* Generate the push */
        if (IsTypeFunc (D->LastParam->Type)) {
            /* Pointer to function */
            Flags = CF_PTR;
        } else {
            Flags = TypeOf (D->LastParam->Type) | CF_FORCECHAR;
        }
        g_push (Flags, 0);
    }

    /* Generate function entry code if needed */
    g_enter (TypeOf (Func->Type), F_GetParamSize (CurrentFunc));

    /* If stack checking code is requested, emit a call to the helper routine */
    if (IS_Get (&CheckStack)) {
        g_stackcheck ();
    }

    /* Setup the stack */
    StackPtr = 0;

    /* Walk through the parameter list and allocate register variable space
     * for parameters declared as register. Generate code to swap the contents
     * of the register bank with the save area on the stack.
     */
    Param = D->SymTab->SymHead;
    while (Param && (Param->Flags & SC_PARAM) != 0) {

        /* Check for a register variable */
        if (SymIsRegVar (Param)) {

            /* Allocate space */
            int Reg = F_AllocRegVar (CurrentFunc, Param->Type);

            /* Could we allocate a register? */
            if (Reg < 0) {
                /* No register available: Convert parameter to auto */
                CvtRegVarToAuto (Param);
            } else {
                /* Remember the register offset */
                Param->V.R.RegOffs = Reg;

                /* Generate swap code */
                g_swap_regvars (Param->V.R.SaveOffs, Reg, CheckedSizeOf (Param->Type));
            }
        }

        /* Next parameter */
        Param = Param->NextSym;
    }

    /* Need a starting curly brace */
    ConsumeLCurly ();

    /* Parse local variable declarations if any */
    DeclareLocals ();

    /* Remember the current stack pointer. All variables allocated elsewhere
     * must be dropped when doing a return from an inner block.
     */
    CurrentFunc->TopLevelSP = StackPtr;

    /* Now process statements in this block */
    while (CurTok.Tok != TOK_RCURLY && CurTok.Tok != TOK_CEOF) {
        Statement (0);
    }

    /* If this is not a void function, and not the main function in a C99
     * environment returning int, output a warning if we didn't see a return
     * statement.
     */
    if (!F_HasVoidReturn (CurrentFunc) && !F_HasReturn (CurrentFunc) && !C99MainFunc) {
        Warning ("Control reaches end of non-void function");
    }

    /* If this is the main function in a C99 environment returning an int, let
     * it always return zero. Note: Actual return statements jump to the return
     * label defined below.
     * The code is removed by the optimizer if unused.
     */
    if (C99MainFunc) {
        g_getimmed (CF_INT | CF_CONST, 0, 0);
    }

    /* Output the function exit code label */
    g_defcodelabel (F_GetRetLab (CurrentFunc));

    /* Restore the register variables */
    F_RestoreRegVars (CurrentFunc);

    /* Generate the exit code */
    g_leave ();

    /* Emit references to imports/exports */
    EmitExternals ();

    /* Emit function debug info */
    F_EmitDebugInfo ();
    EmitDebugInfo ();

    /* Leave the lexical level */
    LeaveFunctionLevel ();

    /* Eat the closing brace */
    ConsumeRCurly ();

    /* Restore the old literal pool, remembering the one for the function */
    Func->V.F.LitPool = PopLiteralPool ();

    /* Switch back to the old segments */
    PopSegments ();

    /* Reset the current function pointer */
    FreeFunction (CurrentFunc);
    CurrentFunc = 0;
}
Ejemplo n.º 7
0
void SwitchStatement (void)
/* Handle a switch statement for chars with a cmp cascade for the selector */
{
    ExprDesc    SwitchExpr;     /* Switch statement expression */
    CodeMark    CaseCodeStart;  /* Start of code marker */
    CodeMark    SwitchCodeStart;/* Start of switch code */
    CodeMark    SwitchCodeEnd;  /* End of switch code */
    unsigned    ExitLabel;      /* Exit label */
    unsigned    SwitchCodeLabel;/* Label for the switch code */
    int         HaveBreak = 0;  /* True if the last statement had a break */
    int         RCurlyBrace;    /* True if last token is right curly brace */
    SwitchCtrl* OldSwitch;      /* Pointer to old switch control data */
    SwitchCtrl  SwitchData;     /* New switch data */


    /* Eat the "switch" token */
    NextToken ();

    /* Read the switch expression and load it into the primary. It must have
     * integer type.
     */
    ConsumeLParen ();
    Expression0 (&SwitchExpr);
    if (!IsClassInt (SwitchExpr.Type))  {
        Error ("Switch quantity is not an integer");
        /* To avoid any compiler errors, make the expression a valid int */
        ED_MakeConstAbsInt (&SwitchExpr, 1);
    }
    ConsumeRParen ();

    /* Add a jump to the switch code. This jump is usually unnecessary,
     * because the switch code will moved up just behind the switch
     * expression. However, in rare cases, there's a label at the end of
     * the switch expression. This label will not get moved, so the code
     * jumps around the switch code, and after moving the switch code,
     * things look really weird. If we add a jump here, we will never have
     * a label attached to the current code position, and the jump itself
     * will get removed by the optimizer if it is unnecessary.
     */
    SwitchCodeLabel = GetLocalLabel ();
    g_jump (SwitchCodeLabel);

    /* Remember the current code position. We will move the switch code
     * to this position later.
     */
    GetCodePos (&CaseCodeStart);

    /* Setup the control structure, save the old and activate the new one */
    SwitchData.Nodes        = NewCollection ();
    SwitchData.ExprType     = UnqualifiedType (SwitchExpr.Type[0].C);
    SwitchData.Depth        = SizeOf (SwitchExpr.Type);
    SwitchData.DefaultLabel = 0;
    OldSwitch = Switch;
    Switch = &SwitchData;

    /* Get the exit label for the switch statement */
    ExitLabel = GetLocalLabel ();

    /* Create a loop so we may use break. */
    AddLoop (ExitLabel, 0);

    /* Make sure a curly brace follows */
    if (CurTok.Tok != TOK_LCURLY) {
        Error ("`{' expected");
    }

    /* Parse the following statement, which will actually be a compound
     * statement because of the curly brace at the current input position
     */
    HaveBreak = Statement (&RCurlyBrace);

    /* Check if we had any labels */
    if (CollCount (SwitchData.Nodes) == 0 && SwitchData.DefaultLabel == 0) {
        Warning ("No case labels");
    }

    /* If the last statement did not have a break, we may have an open
     * label (maybe from an if or similar). Emitting code and then moving
     * this code to the top will also move the label to the top which is
     * wrong. So if the last statement did not have a break (which would
     * carry the label), add a jump to the exit. If it is useless, the
     * optimizer will remove it later.
     */
    if (!HaveBreak) {
        g_jump (ExitLabel);
    }

    /* Remember the current position */
    GetCodePos (&SwitchCodeStart);

    /* Output the switch code label */
    g_defcodelabel (SwitchCodeLabel);

    /* Generate code */
    if (SwitchData.DefaultLabel == 0) {
        /* No default label, use switch exit */
        SwitchData.DefaultLabel = ExitLabel;
    }
    g_switch (SwitchData.Nodes, SwitchData.DefaultLabel, SwitchData.Depth);

    /* Move the code to the front */
    GetCodePos (&SwitchCodeEnd);
    MoveCode (&SwitchCodeStart, &SwitchCodeEnd, &CaseCodeStart);

    /* Define the exit label */
    g_defcodelabel (ExitLabel);

    /* Exit the loop */
    DelLoop ();

    /* Switch back to the enclosing switch statement if any */
    Switch = OldSwitch;

    /* Free the case value tree */
    FreeCaseNodeColl (SwitchData.Nodes);

    /* If the case statement was (correctly) terminated by a closing curly
     * brace, skip it now.
     */
    if (RCurlyBrace) {
        NextToken ();
    }
}
Ejemplo n.º 8
0
void CaseLabel (void)
/* Handle a case sabel */
{
    ExprDesc CaseExpr;          /* Case label expression */
    long     Val;               /* Case label value */
    unsigned CodeLabel;         /* Code label for this case */


    /* Skip the "case" token */
    NextToken ();

    /* Read the selector expression */
    ConstAbsIntExpr (hie1, &CaseExpr);
    Val = CaseExpr.IVal;

    /* Now check if we're inside a switch statement */
    if (Switch != 0) {

        /* Check the range of the expression */
        switch (Switch->ExprType) {

            case T_SCHAR:
                /* Signed char */
                if (Val < -128 || Val > 127) {
                    Error ("Range error");
                }
                break;

            case T_UCHAR:
                if (Val < 0 || Val > 255) {
                    Error ("Range error");
                }
                break;

            case T_SHORT:
            case T_INT:
                if (Val < -32768 || Val > 32767) {
                    Error ("Range error");
                }
                break;

            case T_USHORT:
            case T_UINT:
                if (Val < 0 || Val > 65535) {
                    Error ("Range error");
                }
                break;

            case T_LONG:
            case T_ULONG:
                break;

            default:
                Internal ("Invalid type: %06lX", Switch->ExprType);
        }

        /* Insert the case selector into the selector table */
        CodeLabel = InsertCaseValue (Switch->Nodes, Val, Switch->Depth);

        /* Define this label */
        g_defcodelabel (CodeLabel);

    } else {

        /* case keyword outside a switch statement */
        Error ("Case label not within a switch statement");

    }

    /* Skip the colon */
    ConsumeColon ();
}
Ejemplo n.º 9
0
static void ForStatement (void)
/* Handle a 'for' statement */
{
    ExprDesc lval1;
    ExprDesc lval3;
    int HaveIncExpr;
    CodeMark IncExprStart;
    CodeMark IncExprEnd;
    int PendingToken;

    /* Get several local labels needed later */
    unsigned TestLabel    = GetLocalLabel ();
    unsigned BreakLabel   = GetLocalLabel ();
    unsigned IncLabel     = GetLocalLabel ();
    unsigned BodyLabel    = GetLocalLabel ();

    /* Skip the FOR token */
    NextToken ();

    /* Add the loop to the loop stack. A continue jumps to the start of the
    ** the increment condition.
    */
    AddLoop (BreakLabel, IncLabel);

    /* Skip the opening paren */
    ConsumeLParen ();

    /* Parse the initializer expression */
    if (CurTok.Tok != TOK_SEMI) {
        Expression0 (&lval1);
    }
    ConsumeSemi ();

    /* Label for the test expressions */
    g_defcodelabel (TestLabel);

    /* Parse the test expression */
    if (CurTok.Tok != TOK_SEMI) {
        Test (BodyLabel, 1);
        g_jump (BreakLabel);
    } else {
        g_jump (BodyLabel);
    }
    ConsumeSemi ();

    /* Remember the start of the increment expression */
    GetCodePos (&IncExprStart);

    /* Label for the increment expression */
    g_defcodelabel (IncLabel);

    /* Parse the increment expression */
    HaveIncExpr = (CurTok.Tok != TOK_RPAREN);
    if (HaveIncExpr) {
        Expression0 (&lval3);
    }

    /* Jump to the test */
    g_jump (TestLabel);

    /* Remember the end of the increment expression */
    GetCodePos (&IncExprEnd);

    /* Skip the closing paren */
    ConsumeRParen ();

    /* Loop body */
    g_defcodelabel (BodyLabel);
    Statement (&PendingToken);

    /* If we had an increment expression, move the code to the bottom of
    ** the loop. In this case we don't need to jump there at the end of
    ** the loop body.
    */
    if (HaveIncExpr) {
        CodeMark Here;
        GetCodePos (&Here);
        MoveCode (&IncExprStart, &IncExprEnd, &Here);
    } else {
        /* Jump back to the increment expression */
        g_jump (IncLabel);
    }

    /* Skip a pending token if we have one */
    SkipPending (PendingToken);

    /* Declare the break label */
    g_defcodelabel (BreakLabel);

    /* Remove the loop from the loop stack */
    DelLoop ();
}