G
G
Grigory Dikiy2016-04-15 20:34:35
C++ / C#
Grigory Dikiy, 2016-04-15 20:34:35

Arithmetic problems in assembler?

Good day, I'm making a truncated compiler for Pascal, but I ran into a problem, the fact is that with seemingly obvious things, the assembler does not behave clearly. I'm broadcasting a:=2-3+4; this entry into the assembler having previously received the reverse Polish entry of the form: 2 3 - 4 + . Himself in assembler newbie and his habits are not familiar to me. As a result of the execution of the expression, I get 2. I am attaching the generated code:

.data
a:
  .long 0
printf_format:
  .string "%d\n"

.text
.global main
main:
  movl $0, %eax
  movl $0, %edx
  movl $2, %edx
  sub $3, %edx
  addl %edx, %eax // Здесь должно быть -1 в eax

  movl $0, %edx
  movl %eax, %edx
  addl $4, %edx
  addl %edx, %eax // Здесь 3 в eax

  movl %eax, a


  pushl a
  pushl $printf_format
  call  printf
  addl  $8, %esp

  ret

The generator itself is written like this:
string outStr = "";
    vector<Token *> poliz;
    stack<string> arStack;
    root->next[1]->Log();
    root->next[1]->ReverseNodes(poliz);

    arStack.push(poliz[0]->value);
    arStack.push(poliz[1]->value);

    AddLine("\tmovl $0, %eax");

    for(int it = 2; it < poliz.size(); it++)
    {
        if(poliz[it]->value == "+" || poliz[it]->value == "-" ||
           poliz[it]->value == "*" || poliz[it]->value == "/")
        {
            string op1 = arStack.top();
            arStack.pop();
            string op2 = arStack.top();
            arStack.pop();
            string op = "";

            if(op1 != "%eax")
                op1 = "$" + op1;

            if(op2 != "%eax")
                op2 = "$" + op2;

            AddLine("\tmovl $0, %edx");

            if(poliz[it]->value == "+")
                op = "\taddl ";
            if(poliz[it]->value == "-")
                op = "\tsub ";

            AddLine("\tmovl " + op2 + ", %edx");
            AddLine(op + op1 + ", %edx");
            AddLine("\taddl %edx, %eax");
            AddLine("");
            arStack.push("%eax");
        }
        else
            arStack.push(poliz[it]->value);
    }

    AddLine("\tmovl %eax, " + root->next[0]->data.token->value);
    AddLine("\n");

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Daniil Kolesnichenko, 2016-04-15
@frilix

You don't set it to zero %eax(the value -1 remains in it, to which you add 3, so you get 2)
PS printf_format should be "%ld\n"because the type of the variable is long, not int.

G
Grigory Dikiy, 2016-04-15
@frilix

Thanks

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question