Compiler - code generation based on AST expressions

pseudo code:

struct node
{
    type(Op,var,name);
    op(Add,Sub,Div,Mult);
    val;
    base;
    offset;
    left;
    right;
}

Emit(Op,src1,src2,des);

GetNextReg();

Expr(node)
{
    int t1,t2,res;
    switch(node.type){
        case num:
            rest = GetNextReg();
            Emit(loadI,node.val,NULL,res);
            break;
       
        case var:
            res = GetNextReg();
            Emit(loadAI,node.base,node.offset,res)
            break;
        
        case Op:
            t1 = Expr(node.left);
            t2 = Expr(node.right);
            rest = GetNextReg();
            Emit(Op.op,t1,t2,res);
            break;
    }
    return res;
}

A * 3 + b 

The first step is to call root plus sign + call the Expr function to push into the stack + it is Op, so it will call t1 = Expr(node.left); the
left node of the root node is the multiplication sign*

Then enter t1 = Expr(node.left) in Op again;

Next, it will enter case var and generate instruction 

After the return, it returns to the t1 = Expr(node.left) of the multiplication sign Op; then executes the next line t2 = Expr(node.right);
and generates the instruction

Next, after executing r1 and r2, execute getNextReg to get r3 and then the next line generates instrctuon

At this time, the multiplication sign * has been executed and returned

At this time, return to the plus sign + t1 = Expr(node.left); the execution has been completed return r3 starts to execute t2 = Expr(node.right);

After executing t2 = Expr(node.right); return r4, the next line getNextReg will return r5 and execute Emit to generate instruction

Guess you like

Origin blog.csdn.net/weixin_43754049/article/details/126337126