Name: Date:

HW8 solution

  1. In the following assembly code fragment, registers x5 and x6 are initialized to N and zero respectively.

    LOOP: slt     x7, x0, x5
          beq     x7, x0, DONE
          addi    x5, x5, -1
          addi    x6, x6, 3
          jal x0,       LOOP
    DONE:    

    a. (2 points) What is the value in register x6 for when the code reaches the label DONE:?

    3N

    b. (2 points) How many RISC-V instructions are executed?

    5N + 2

    c. (6 points) If the registers x5, x6, and x7 correspond to variables i, a, and t respectively, write the equivalent C code for the loop. Note: you probably won't end up with a t variable in your answer.

    a = 0;
    i = N;
    while(0 < i) { //same as i >= 0
        i--;
        a = a + 3;
    }

    or

    a = 0;
    for( i=N; 0<i; i-- )
        a += 3;
  1. (20 points) Below is a snippet from a Checkers game program in C.

    void setKing(int row, int col, int isKing)
    {
      int* rowAddr = getRowAddr(row); //returns the memory address of row
      rowAddr[col] = isKing;
    }

    Fill in the missing portions of the setKing function below, adhering to the RISC-V procedure call conventions. You should assume setKing is called according to RISC-V convention. Do not implement getRowAddr, assume it is already implemented following the conventions. You are encouraged to use register names (e.g. t0) instead of register ids (e.g. x5) in this code.

    setKing:   #entry point to setKing procedure
    
    addi sp, sp, -12   #allocate space on stack
    sw a1, 0(sp)       #backup needed arg values, since they
    sw a2, 4(sp)       # would be lost after jal
    sw ra, 8(sp)       #backup return address, since we do jal
    #note that row is already in a0 so we don't need to move it
    
    jal ra, getRowAddr  #call to getRowAddr
    
    #note that a0 is now the return value from getRowAddr
    lw ra, 8(sp)       #restore values from stack
    lw a2, 4(sp)
    lw a1, 0(sp)
    addi sp, sp, 12    #deallocate space on stack
    
    slli a1, a1, 2      #multiply col by 4 to get ready for address
    add a0, a1, a0    #build address from base and col offset
    sw a2, 0(a0)       #store king value at row+col location
    #this procedure returns nothing so we don't need to put anything special in a0
    
    jalr    x0, 0(ra)   #return form setKing