1

For example, I have a piece of C code that I am trying to convert to MIPS for practice, but for the variable count, I don't know whether to use addi $t0,0 or li $t0, 0. Could I use either either or? And what is the difference?

   Void haarPredict (int vector[], int N) 
    { 
        int half = N >> 1; 
        int count = 0; 

        for(int i = 0; i < half; i++) 
        { 
            int predictVal = vector[i]; 
            int j = i + half; 
            vector[j] = vector[j] - predictVal 
        } 
    } 

This is what I have so far after converting the above code to MIPS. Assuming $a0 is vector[] and $a1 is N. Again, I am not sure if li or addi is the correct thing to use.

      srl $t0, $a1, 1     #t0 holds half. half = N >> 1
      addi $t1, $t1, 0    #t1 holds count. count = 0
      addi $t2, $t2, 0    #t2 holds i. i = 0
loop: slt $t3, $t2, $t0     #t3 holds 1 if i < half
      beg $t3, $zero, exit  #exit if t3 == 0
      lw  $t4, 0($a0)       #t4 holds predictValue
      addi $a0, $a0, 4    #4 bytes for next word address
      addi $t5, $t2, $t0  #t5 holds j. j = i + half
      lw $t6, $t6, $t4    #vector[j]=vector[j]-predivtVal
      addi $t2, $t2, 1    #i++
      j loop
exit: jr $ra
LiveToLearn
  • 163
  • 1
  • 2
  • 12

1 Answers1

3

The li (Load immediate) instruction loads a specific numeric value into a register.

The addi (Add inmediate) adds a register and a sign-extended immediate value and stores the result in a register.

So, unless you are 100% sure a register has a zero value, then you shouldn't use an addi instruction to set a register.

For example:

addi $t1, $t1, 0    #t1 holds count. count = 0

You don't know if $t1 is zero at that particular moment. If thats a subroutine, you might be using a garbage value of $t1 (a value from before the invocation of the subroutine, before the jump to the address of the subroutine).

So the safe way is to set the register with li (thus, count=0), not taking into consideration the previous value of the register.

MAP
  • 397
  • 2
  • 8
  • 4
    _"So, unless you are 100% sure a register has a zero value"_ Side note: MIPS processors have a register (`$zero`) that _always_ contains the value 0. So that's what you'd use as the source register when loading an immediate. In fact, `li $t1, 123` will assemble into something like `ori $t1, $zero, 123` or `addiu $t1, $zero, 123`. However, `li` should be preferred if the assembler supports it, since it makes the code easier to read and write. – Michael Oct 15 '18 at 08:04