Pages

Saturday, November 6, 2010

LabD1 : Translate Java class into MIPS (1)

#===================== JAVA =====================
public class Fraction
{
private int numerator;
private int denominator;

public Fraction(int numerator, int denominator)
{
this.numerator = numerator;
this.denominator = denominator;
}

public int getNumerator() { return this.numerator }
public int getDenomimator() { return this.denominator }

public void add(Fraction other)
{
this.numerator = this.numerator * other.denominator + this.denominator * other.numerator;
this.denominator = this.denominator * other.denominstor;
}
}

#==================== MIPS ==========================

LabD1.s

# keyword public in Java will be translated as .globl in MIPS
.globl Fraction
.globl getNumerator #  public 
.globl adding
.globl setNumerator
.globl setDenominator
.text
#----------------------------------------------
# -------- the property of the class and the constructor is translated here -------------
Fraction:
# Initialize the property of each class
addi $t0, $0, 0 # private int numerator
addi $t1, $0, 1 # private int numerator
# constructor with 2 params
# allocate 8 bytes in the heap memory and save the address of the first byte in $v0
addi $v0, $0, 9 # $v0 = 9 means allocate memory address and save it in $v0
addi $a0, $0, 8 # $a0 = 8 means # of bytes needed.
syscall
# why? a continious 8 bytes heap memory were allocated, first 4 bytes for int variable numerator,
# second 4 bytes for int variable denomerator
sw $t0, 0($v0)
sw $t1, 4($v0)
# store the attributes somewhere in memory and return a reference to where they are
jr $ra


#--------------getNumerator accessor -----------------------------
# what does this method do??
# it retrive the value saved in the first 4 bytes and return it in $v0
# why $a0???
# a.getNumerator() 
# get the instance addrss and retrive the first 4 bytes.
getNumerator:
lw $v0, 0($a0)  
jr $ra


# -------------- getDenominator access ------------------------------
getDenominator:
lw $v0, 4($a0)
jr $ra


# ---------------   add(Fraction other) -----------------------------
# 2 addresses is needed in this method
# the address of the source instance address, and the address of the param instance
# e.g. a.add(b)
adding:
lw $t0, 0($a0) # the numerator of the source instance
lw $t1, 4($a0) # the denominator of the source instance
lw $t2, 0($a1) # the numerator of the param instance
lw $t3, 4($a1) # the denominator of the param instance
# calculate the numerator
mult $t0, $t3
mflo $t4
mulf $t1, $t2
mflo $t5
add $t6, $t4, $t5
# calculate denominator
multi $t1, $t3
mflo $t7

# update the numerator with the new value
sw $t6, 0($a0)
sw $t7, 4($a0)
jr $ra
# ------------ setNumerator( int numerator )  ---------------
setNumerator:
lw $t0, 0($a0)
add $t0, $t0, $a1
sw $t0, 0($a0)
jr $ra
# ------------- setDenominator (int denominator ) ------------
setDenominator:
lw $t0, 4($a0)
add $t0, $t0, $a1
sw $t0, 4($a0)
jr $ra

No comments:

Post a Comment