Compiler Designing W07L1202

Code Generation I

  • A function cgen(e) is introduced that produces the code for expression for e.
  • Red: Compile time operation; Blue: Run-time operation
cgen(constant) = li $a0 constant

/*Add Operation*/
cgen(a+b) = 
      cgen(a)
      sw $a0 0($sp)
      addiu $sp $sp -4
      cgen(b)
      lw $t1 4($sp)
      add $a0 $a0 $t1
      addiu $sp $sp 4 
/*Subtract Operation*/
cgen(a-b) = 
      cgen(a)
      sw $a0 0($sp)
      addiu $sp $sp -4
      cgen(b)
      lw $t1 4($sp)
      sub $a0 $a0 $t1                      //just changes here
      addiu $sp $sp 4 
  • One optimization can be proposed using $t1 to load e1, but it won’t work correctly. Take the case of 1+(2+3).
  • From the above, see that the cgen is actually a template, it is to be plugged with different values and get the result.
  • Stack machine code generation is recursive, hence a recursive-descent of AST can be used to implement it.

[II]

  • Two other operations are:
beq $a $b branch_label          //beq: branch if equal
b branch_label                  //b: unconditional branch
  • Example execution of if (a== b) then c else d;
      cgen(a)
      sw $a0 0($sp)
            addiu $sp $sp -4
      cgen(b)
       lw $t1 4($sp)
              addiu $sp $sp 4 
              beq $a0 $t1 true_branch
              b false_brach
   
   true_branch cgen(c)
   end_if
     false_branch cgen(d)
   end_if
Advertisements

Help to improve or comment as you wish

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s