In: Computer Science
Assemby language - MIPS
Your assembly should implement the C code directly – i.e.,do not ’optimize’ the C code to change the order of operations or reduce computations. Write MIPS assembly code implementing the following C/C++ statement:
y = 13 - 11*x;
One way of doing the multiply without a multiply instruction is by using many add instructions (x+x+...+x). For this problem you should do it with fewer additions.
Hint: We know how to express any integer as a sum of powers of 2 (e.g.,7 = 1+2+4), and we also know how to multiply by powers of 2 using repeated addition. This gives us a method to multiply by 11 (applying distributivity), and this technique is in fact an underlying principle of many hardware multipliers
Thank you!
CODE :
la $t0,x($gp) // Load the value of x into register using global
pointer
sll $t1,$t0,3 // Logical left shift of x and stored in t1
sll $t2,$t0,1 // Logical left shift of x and stored in t2
add $t0,$t1,$t0 // Adding t0 and t1
add $t0,$t2,$t0 // Adding t2 to t0
mul $t0,$t0,-1 // Multiplying t0 by -1
addi $t0,$t0,13 // Adding 13 to the multiplied value
la $t1,y // Loading the address of y
sw $t0, 0($t1) // Storing the value back into y
Explanation :
Doing this, we will have performed the given C code of y = 13 - 11*x; in MIPS using the least number of instructions. The key point to notice in this is the use of left shift operator to simplify the operations. This is a very useful technique used and makes the code very fast. It also reduces the number of instructions without using the "mul" operation.