# Part 3 .data # put a postfix expression into memory to evaluate, just for # testing / debugging purposes. (5 9 - 4 *) expression: .word 0x00000005, 0x00000009, 0xaa00002d, 0x00000004, 0xaa00002a, 0xaa000000 # Space for 128 elements in the stack stackbottom: .space 128 stacktop: .globl main .text main: # $s0 is the pointer to the user expression la $s0, expression # $s1 is the stack pointer for rpn la $s1, stacktop # end of expression marker li $t1, 0xAA000000 # MSB code of operator li $t2, 0xAA loop: lw $t0, 0($s0) # load a value from memory addi $s0, $s0, 4 # set expression address to the # next word in memory # Check end of expression beq $t0, $t1, endLoop # Check for operator # - Get MSB of value srl $t3, $t0, 24 # - Compare with 0xAA beq $t3, $t2, operator # An operand. Push to stack addi $s1, $s1, -4 sw $t0, 0($s1) j loop operator: # Clear bits 31-8, leave operator ascii code only # Move operator in $a1, ready for 'calculator' # No check for wrong operator andi $a1, $t0, 0x00FF # Pop operand from stack # Note that this becomes $a2, the 2nd operand lw $a2, 0($s1) addi $s1, $s1, 4 # Pop other operand from stack # Always 2 operands expected lw $a0, 0($s1) addi $s1, $s1, 4 # Do calculation jal calculator # push result onto stack addi $s1, $s1, -4 sw $v0, 0($s1) j loop endLoop: # Get the value at top of stack lw $a0,0($s1) addi $s1, $s1, 4 # print the result li $v0, 1 syscall # exit the program li $v0, 10 syscall calculator: # $a0 and $a2 are operands and $a1 is the operator # the return value is in $v0 # calculator uses $t1, preserved in stack addi $sp, $sp, -4 sw $t1, 0($sp) # branch to the proper piece of code depending on the operand li $t1, '+' beq $a1, $t1, OperationAdd li $t1, '-' beq $a1, $t1, OperationSub li $t1, '*' beq $a1, $t1, OperationMul li $t1, '/' beq $a1, $t1, OperationDiv # Should never end up here! # Ignore for coursework OperationAdd: add $v0, $a0, $a2 j return OperationSub: sub $v0, $a0, $a2 j return OperationMul: mul $v0, $a0, $a2 j return OperationDiv: div $v0, $a0, $a2 return: # restore $t1 from stack lw $t1, 0($sp) addi $sp, $sp, 4 jr $ra