
上完編譯器,最後還要用 bison/flex 產生一個compiler,生成 mips 組合語言真的有趣
SPIM: A MIPS32 Simulator
http://spimsimulator.sourceforge.net/
https://github.com/x213212/mipsgenerator
test case
WHILE() {
int n;
n = 1;
while(n > 0)
{
write 1;
}
}
.data
n: .word 0
.text
main:
la $t0, n
li $t1, 1
sw $t1, 0($t0)
#while
L1: # endif2
la $t0, n
lw $t0, 0($t0)
li $t1, 0
bgt $t0, $t1, L2
b L3
L2: # then
li $t0, 1
move $a0, $t0
li $v0, 1
syscall
b L1
L3:
Arith4()
{
write (5 + 2) * -14 / -2 % 2
;
}
.data
.text
main:
li $t0, 5
li $t1, 2
add $t0, $t0, $t1
li $t1, 14
neg $t1, $t1
mul $t0, $t0, $t1
li $t1, 2
neg $t1, $t1
div $t0, $t0, $t1
li $t1, 2
rem $t0, $t0, $t1
move $a0, $t0
li $v0, 1
syscall
sum()
{
int n;
int s;
read n;
if(n < 0) {
write -1;
exit;
} else {
s = 0;
while(n > 0){
s = s + n;
n = n - 1;
}
}
write s;
}
.data
n: .word 0
s: .word 0
.text
main:
li $v0, 5
syscall
la $t0, n;
sw $v0, 0($t0)
la $t0, n
lw $t0, 0($t0)
li $t1, 0
blt $t0, $t1, L1
b L2
L1: # then
li $t0, 1
neg $t0, $t0
move $a0, $t0
li $v0, 1
syscall
li $v0, 10
syscall
b L3
L2: # else
la $t0, s
li $t1, 0
sw $t1, 0($t0)
#while
L4: # endif2
la $t0, n
lw $t0, 0($t0)
li $t1, 0
bgt $t0, $t1, L5
b L3
L5: # then
la $t0, s
la $t1, s
lw $t1, 0($t1)
la $t2, n
lw $t2, 0($t2)
add $t1, $t1, $t2
sw $t1, 0($t0)
la $t0, n
la $t1, n
lw $t1, 0($t1)
li $t2, 1
sub $t1, $t1, $t2
sw $t1, 0($t0)
b L4
L6:
L3:
la $t0, s
lw $t0, 0($t0)
move $a0, $t0
li $v0, 1
syscall
Comments