#-------------------------------------------
# Subroutines - Arguments and Return Values
# Ported by: Noah Gergel
# Last updated: May 6 2020
#-------------------------------------------

.text

#-------------------------------------------------------------------------------
# foo
# A function that does something, and as a sub-task foils two numbers.
#
# Arguments:
#       None
# Return Values:
#       None
# Side Effects:
#       None
# Register Usage:
#       t0, t1: Intermediaries to be foiled out.
#
#-------------------------------------------------------------------------------
foo:
    # Imagine we are doing some task which results in t0, t1 having
    # the values we want to foil out.

    # Move t0, t1 to a0, a1.
    mv      a0, t0
    mv      a1, t1

    jal     ra, foil

    # Lastly, return from foo.
    jalr    zero, ra, 0


#-------------------------------------------------------------------------------
# foil
# Given two numbers a and b, this function foils them out. That is, expands (a + b)^2
# into a^2 + 2ab + b^2.
#
# Arguments:
#       a0: The value of a.
#       a1: The value of b.
# Return Values:
#       None
# Side Effects:
#       Prints the sum of a^2 + 2ab + b^2 to terminal.
# Register Usage:
#       t0, t1: Intermediaries in calculations.
#
#-------------------------------------------------------------------------------
foil:
    # Calculate the squares.
    mul     t0, a0, a0      # t0 <- a^2
    mul     t1, a1, a1      # t1 <- b^2
    add     t0, t0, t1      # t0 <- a^2 + b^2

    # Now the 2*a*b term.
    mul     t1, a0, a1      # t1 <- a * b
    add     t0, t0, t1      # t0 <- a^2 + b^2 + a*b
    add     t0, t0, t1      # t0 <- a^2 + b^2 + 2*a*b

    # To print it out, we need to move the value into a0 and the number 1 into a7.
    mv      a0, t0
    addi    a7, zero, 1
    ecall

    # Since we are returning the value in a0, we don't need to move it anywhere.
    # Now we return to foo.
    jalr    zero, ra, 0