Lab6 PDF
Lab6 PDF
Lab6 PDF
Arithmetic in MIPS
Objectives
After completing this lab you will:
Introduction
The definition of the R2000 architecture includes all integer arithmetic within the actual CPU. Floating point
arithmetic is done by one of the four possible coprocessors, namely coprocessor number 1.
Integer arithmetic
Addition and subtraction are performed on 32 bit numbers held in the general purpose registers (32 bit each).
The result is a 32 bit number itself. Two kinds of instructions are included in the instruction set to do integer
addition and subtraction:
• instructions for signed arithmetic: the 32 bit numbers are considered to be represented in 2’s comple-
ment. The execution of the instruction (addition or subtraction) may generate an overflow.
• instructions for unsigned arithmetic: the 32 bit numbers are considered to be in standard binary repre-
sentation. Executing the instruction will never generate an overflow error even if there is an actual
overflow (the result cannot be represented with 32 bits).
Multiplication and division may generate results that are larger than 32 bits. The architecture provides two
special 32 bit registers that are the destination for multiplication and division instructions. These registers are
called hi and lo as to indicate that they hold the higher 32 bits of the result and the lower 32 bits respectively.
Special instructions are also provided to move data from these registers into the general purpose ones ($0 to
$31).
Instruction Effect
Two kinds of instructions are included in the instruction set to do integer multiplication and division:
• instructions for signed arithmetic: the 32 bit numbers are considered to be represented in 2’s comple-
ment. An integer multiplication will never generate an overflow. Division may overflow. Note
however that the instruction will not signal the overflow: this must be done in software.
• instructions for unsigned arithmetic: the 32 bit numbers are considered to be in standard binary repre-
sentation. Executing the instruction will never generate an overflow error even if there is an actual
overflow (this is the case for division).
Floating point arithmetic resembles the IEEE-754 floating-point standard. A very brief description of number
formats in this standard is given in Appendix A.
Floating-point addition, subtraction, multiplication and division may overflow. An overflow means that the
exponent is too large to be represented in the exponent field.
The MIPS instruction set provides instructions that, beside floating-point operations, do floating-point com-
parisons, branching, load and store from/to memory and conversions between floating point formats and
between integer and floating-point numbers. Unlike the integer unit where comparisons explicitly set some
destination register, in the floating point unit, a comparison will implicitly set a condition flag. The condition
flag can then be tested by branch instructions.
A summary of native instructions is presented in the table below. The x suffix for some instructions should
be replaced by a s (e.g. add.s) to indicate the instruction should operate on single precision floating-point
numbers, or by a (e.g. add.d) to indicate double precision operation.
Instruction Comment
mfc1 Rdest, FPsrc Move the content of floating-point register FPsrc to Rdest
mtc1 Rsrc, FPdest Integer register Rsrc is moved to floating-point register FPdest
mov.x FPdest, FPsrc Move floating-point register FPsrc to FPdest
lwc1 FPdest, address Load word from address in register FPdesta
swc1 FPsrc, address Store the content of register FPsrc at addressb
add.x FPdest, FPsrc1, FPsrc2 Add single precision
Date Section
Name
Signed integers can be both positive and negative. With n bits, in 2’s complement representation, the smallest
n–1 n–1
integer is – 2 and the largest is 2 –1
At the C/C++ programming level the difference between unsigned and signed integers is sometimes ignored.
Note, however that declaring an integer variable that is always positive as int (when it should in fact be
declared as unsigned int), reduces the range of that variable in half.
Ex 1:
// Assume that integers are 32 bit wide
{
unsigned int ex1; // values for ex1 between 0 and 4,294,967,295
int ex2; // values for ex2 between -2,147,483,648 and 2,147,483,647
}
If the variable ex2 is always positive, then its possible values will be in the range 0 to 2,147,483,647, half of
the range an unsigned integer has. ■
Q 1:
A negative number is represented as a bit pattern whose most significant bit is 1 (in 2’s complement repre-
sentation). The same bit pattern, when looked at as an unsigned integer, will be a large number. Fill out the
00000000
01111111
10000000
11111111
At the assembly language level the difference between signed and unsigned is more subtle. Most instructions
that do arithmetic on signed numbers may overflow and the overflow will be signaled. Thus the trap handler1
can take appropriate action to deal with the situation: ignoring an overflow may result in the computation of
results that are completely wrong.
Instructions that do arithmetic on unsigned integers on the other hand, will not signal an overflow even if the
operation itself yields a result which is not representable with the given number of bits for the result.
Q 2:
In what cases can the operation overflow? In the ‘Addition’ and ‘Subtraction’ columns of the following table
use a ‘Y’ to indicate that the operation can overflow, and ‘N’ to indicate that the operation can not overflow.
positiveb positive
positive negativec
negative positive
negative negative
0 positive
0 negative
positive 0
negative 0
a. Operand_2 is subtracted from Operand_1
b. Strictly greater than 0
c. Strictly smaller than 0
Step 1
Write a program, called lab6.1.c which:
• declares two integer variables, a and b. The initial value for a and b is the maximum possible value
for an integer (INT_MAX if you include the limits.h file)
• adds a and b and prints the result
Q 3:
Do you think the addition in lab6.1.c overflows? Explain.
Step 2
Compile and run the executable created from lab6.1.c.
a b Printed result
Q 4:
Is the result your program prints correct? Explain.
Most compilers generate code that does not signal integer overflows. An unsuspecting programmer may eas-
ily generate incorrect output without any error message to indicate it.
Step 3
Create the program lab6.1.asm based on the following description:
• in ‘main’ prompts the user to enter two integers; store them in $t0 and $t1
• adds the two numbers using the native signed instruction; store the result in $t2
• prints the result
Run the program and fill out the following test plan. Wherever possible use numbers that would make the
addition overflow. In the ‘Overflows’ column use a ‘Y’ to indicate the operation overflows and a ‘N’ to indi-
cate it does not. In the ‘Comment’ column mark with a star those cases when an overflow error is actually
reported.
Note: carefully choose the numbers you enter for test. The system function that reads an integer from the user
(read_int) will truncate a very big number as to fit an integer register (32 bits). What you have in the register
may be something you did not expect (try for example to enter a number like 8,589,934,593 and then look in
the register where you store the number to see what has actually been stored there).
+2000000000 +2000000000 Y
+ -
- +
- -
Step 4
Create the program lab6.2.asm based on the following description:
• in ‘main’ prompts the user to enter two integers; store them in $t0 and $t1
• subtracts the second number from the first using the native signed instruction; store the result in $t2
• prints the result
Run the program and fill out the following test plan. Wherever possible use numbers that would make the
subtraction overflow. In the ‘Overflows’ column use a ‘Y’ to indicate the operation overflows and a ‘N’ to
indicate it does not. In the ‘Comment’ column mark with a star those cases when an overflow error is actually
reported.
+ +
+ -
- +
- -
Step 5
Testing unsigned addition and subtraction requires some attention. The SPIM simulator always prints the
content of a general purpose register as a signed integer. The fact that a large valid unsigned integer is printed
n–1 n
as a negative number may confuse you. Unsigned numbers larger or equal to 2 (but smaller than 2 ) have
the most significant bit 1. Therefore they will be interpreted as negative numbers by the printing function.
• in ‘main’ prompts the user to enter two integers; store them in $t0 and $t1
• adds the two numbers using the native unsigned instruction; store the result in $t2
• prints the result
Run the program and fill out the following test plan. Wherever possible use numbers that would make the
addition overflow. In the ‘Overflows’ column use a ‘Y’ to indicate the operation overflows and a ‘N’ to indi-
cate it does not. In the ‘Comment’ column mark with a star those cases when an overflow error is actually
reported.
+ +
Step 6
Create the program lab6.4.asm based on the following description:
• in ‘main’ prompts the user to enter two integers; store them in $t0 and $t1
• subtracts the second number from the first using the native unsigned instruction; store the result in $t2
• prints the result
Run the program and fill out the following test plan. Wherever possible use numbers that would make the
subtraction overflow. In the ‘Overflows’ column use a ‘Y’ to indicate the operation overflows and a ‘N’ to
indicate it does not. In the ‘Comment’ column mark with a star those cases when an overflow error is actually
reported.
+ +
0 +
Date Section
Name
Integer multiplication
Integer multiplication can be done using both signed and unsigned numbers. The architecture specifies two
special registers, hi and lo (32 bit each), which are the destination for integer multiplication and division.
Multiplying two n-bit unsigned integers may yield a result that requires 2 ⋅ n bits to be represented.
Ex 1:
Assume 2 bit unsigned integers. Then the largest integer that can be represented using 2 bits is 3 (its binary
representation is 11).
Multiplication Comment
Decimal 3⋅3 = 9
Binary 11 ⋅ 11 = 1101 Result requires 4 bits for representation
For signed multiplication the two numbers to be multiplied are in 2’s complement representation. The result
is also in 2’s complement representation. The result of a signed multiplication may require 2 ⋅ n – 1 bits for
representation: there are 2 ⋅ ( n – 1 ) bits for the magnitude and one bit for the sign.
Instruction Comment
mult Rsrc1, Rsrc2 Multiply the signed numbers in Rsrc1 and Rsrc2. The higher 32 bits of the
result go in register hi. The lower 32 bits of the result go in register lo
multu Rsrc1, Rsrc2 Multiply the unsigned numbers in Rsrc1 and Rsrc2. The higher 32 bits of the
result go in register hi. The lower 32 bits of the result go in register lo
Since both signed and unsigned integer multiplication never require more than 64 bits for the result, an over-
flow will never occur during integer multiplication using the native multiply instructions.
The virtual machine provides multiply instructions whose result is the size of a word (the destination register
is some general purpose integer register). Since the destination register is only 32 bit wide, these synthetic
instructions may overflow.
Instruction Comment
mul Rdest, Rsrc1, Rsrc2 Multiply the signed numbers in Rsrc1 and Rsrc2. The lower 32 bits
of the result go in register Rdest.
mulo Rdest, Rsrc1, Rsrc2 Multiply the signed numbers in Rsrc1 and Rsrc2. The lower 32 bits
of the result go in register Rdest. Signal overflow
mulou Rdest, Rsrc1, Rsrc2 Multiply the unsigned numbers in Rsrc1 and Rsrc2. The lower 32
bits of the result go in register Rdest. Signal overflow
Integer division
The result of an integer division is a quotient (stored in register lo) and a remainder (stored in register hi),
both integer numbers.
• There is one complication related to integer division: the sign of the remainder. There are two
approaches to this problem:
• follow the division theorem from mathematics
• use the computer science view
By dividing an integer DD called dividend, by a positive integer DR called divisor, the following conditions
are true (the division theorem):
DD = DR ⋅ Q + RM (1)
0 ≤ RM < DR (2)
where Q (the quotient) and RM (the remainder) are unique integers. Note that the remainder is always
positive.
Ex 2:
What is the result of dividing -22 by 3?
DD = -22, DR = 3, Q = -8, RM = +2
Note that relation (1) could be satisfied by Q’ = -7, RM’ = -1. However this solution is not valid since it does
not satisfy the condition that the remainder must be positive (2).
DD = +22, DR = 3, Q = +7, RM = +1
22 – 22
- ≠ ---------
In this approach – -----
7 7 . If this was implemented on computers, then programming would definitely
be more fun than it is now. ■
The way division is usually implemented (the ‘computer science way’), the following relations are true:
DD = DR ⋅ Q + RM (3)
RM < DR (4)
sign ( RM ) = sign ( DD ) (5)
If the dividend and the divisor have the same sign then the quotient is positive; otherwise it is negative. A
nonzero remainder has always the same sign as the dividend.
Q 1:
What are the results of the following integer divisions?
22 7
-22 7
22 -7
-22 -7
In MIPS, if one of the operands in a division is negative, then the remainder is unspecified. The SPIM sim-
ulator will return a result based on the conventions on the machine it is run on.
To obtain the correct result for division, extra steps need to be performed:
A signed division may overflow since the 2’s complement representation of integers is asymmetric: there is
one negative number more than positive numbers. Note however that the overflowing division does not signal
the overflow. It is the compiler’s or programmer’s task to generate proper code that detects the overflow.
Dividing an integer by zero is an illegal operation. However, even if the divisor is zero, the division will report
no error. It is again the compiler’s or programmer’s task to generate proper code that detects the illegal
operation.
Instruction Comment
div Rsrc1, Rsrc2 Divide the signed integer in Rsrc1 by the signed integer in Rsrc2. The quo-
tient (32 bits) goes in register lo. The remainder goes in register hi. Can
overflow.
Instruction Comment
divu Rsrc1, Rsrc2 Divide the unsigned integer in Rsrc1 by the unsigned integer in Rsrc2. The
quotient (32 bits) goes in register lo. The remainder goes in register hi. Does
not overflow.
The virtual machine provides divide instructions whose result is stored in a general purpose register.
Instruction Comment
div Rdest, Rsrc1, Rsrc2 Divide the signed integer in Rsrc1 by the signed integer in Rsrc2.
Store the quotient (32 bits) in register Rdest. Can overflow.
divu Rdest, Rsrc1, Rsrc2 Divide the unsigned integer in Rsrc1 by the unsigned integer in
Rsrc2. Store the quotient in Rdest. Does not overflow.
rem Rdest, Rsrc1, Rsrc2 Divide the signed integer in Rsrc1 by the signed integer in Rsrc2.
Store the remaindera (32 bits) in register Rdest. Can overflow.
remu Rdest, Rsrc1, Rsrc2 Divide the signed integer in Rsrc1 by the signed integer in Rsrc2.
Store the remaindera (32 bits) in register Rdest. Does not overflow.
a. If one of the operands is negative then the remainder is undefined.
Step 1
Write a program, called lab6.2.c which:
• declares two integer variables, a and b. The initial value for a and b is the maximum possible value
for an integer (INT_MAX if you include the limits.h file)
• multiplies a and b and prints the result
Q 2:
Do you think the multiplication in lab6.2.c overflows? Explain.
Step 2
Compile and run the executable created from lab6.2.c.
a b Printed result
Q 3:
Is the result your program prints correct? Explain.
Most compilers generate code that does not signal integer overflows. An unsuspecting programmer may eas-
ily generate incorrect output without any error message to indicate it.
Step 3
Create the program lab6.5.asm based on the following description:
• in ‘main’ prompts the user to enter two integers; store them in $t0 and $t1
• multiplies the two numbers using the native signed instruction
• prints the result
Run the program and fill out the following test plan. Use the print command in the simulator to see the
content of registers hi and lo. In the last two rows of the table enter the numbers that represent the largest
possible signed integer and the smallest possible one respectively.
2 1
2 -1
Q 4:
In the second row of this test plan the register hi is all 1s. Why is that?
Step 4
Run the program again and fill out the next test plan. Use the same numbers you have used in the previous
step.
Q 5:
Some of the results your program prints are not correct. Why?
Step 5
Create the program lab6.6.asm based on the following description:
• in ‘main’ prompts the user to enter two integers; store them in $t0 and $t1
• multiplies the two numbers using the native unsigned instruction
Run the program and fill out the following test plan.
2 1
2 -1
Q 6:
What numbers are in reality multiplied when the input numbers are 2 and -1? Remember that a negative inte-
ger will mean a large positive unsigned integer.
-1
Step 6
Create the program lab6.7.asm based on the following description:
• in ‘main’ prompts the user to enter two integers; store them in $t0 and $t1
• divides the first number by the second one, using the native signed instruction
• prints the quotient and the remainder
Run the program and fill out the following test plan. Use small numbers that would generate a nonzero
remainder. For the last row use a pair of numbers that would make the division overflow. Note that division
by zero (which is an illegal operation) and overflow are different things. In the ‘Comment’ column mark with
a star those cases where an error is reported.
+ +
+ -
- +
- -
Step 7
Create the program lab6.8.asm based on the following description:
• in ‘main’ prompts the user to enter two integers; store them in $t0 and $t1
• divides the first number by the second one, using the native unsigned instruction
• prints the quotient and the remainder
Run the program and fill out the following test plan. Use small numbers that would generate a nonzero
remainder. For the last row use a pair of numbers that would make the division overflow. In the ‘Comment’
+ +
+ -
- +
-1 +2
- -
Q 7:
What numbers are in reality divided when the input numbers are -1 and +2?
-1
+2
Date Section
Name
Infinity does not mean mathematically infinite, rather something too big to be represented. An overflow can
return an +inf or a -inf (though the standard also provides a mechanism to determine the correct result in case
of overflows). Some operations on infinity return yet another infinity as a result.
There can be a positive zero if the sign bit is 0 and a negative zero (the sign bit is 1). Denormalized numbers
are included in IEEE-754 to handle cases of exponent underflow (very small numbers).
A NaN (sometimes denoted by nan) is used to represent an indeterminate result. There are two kinds of NaNs,
signaling and quiet: the actual bit pattern in the significand field is used to differentiate between them, and it
is implementation-dependent. A signaling NaN can be used for instance for uninitialized variables: attempt-
ing to operate on a signaling NaN can cause a trap. Note that any operation on a signaling NaN will have as
a result a quiet NaN. Operating on a quiet NaN simply returns another NaN without generating any exception.
Operation Comment
0 * ( inf)
0/0
inf/inf
Step 1
Create a program named lab6.9.asm which:
• declares the variables Zero.s, PlusInf.s, MinusInf.s, PlusNaN.s, MinusNaN, of size word, initialized
with the bit patterns corresponding to zero, plus infinity, minus infinity, positive Not a Number, and
negative Not a Number respectively, in single precision representation
• declares the variables Zero.d, PlusInf.d, MinusInf.d, NaN.d, initialized with the bit patterns corre-
sponding to zero, plus infinity, minus infinity, and Not a Number respectively, in double precision
• loads these variables in floating-point registers, starting with $f0
• prints, starting with $f0, the contents of those registers where variables have been loaded; print a new-
line (\n) character after each value.
Step 2
Create the program lab6.10.asm which:
Q 1:
What is the bit pattern for the largest possible single precision floating point number? Write it down in hexa-
decimal.
Laboratory 6: Inlab
Date Section
Name
Step 1
During Lab #4 you created a program named lab4.5.asm which computes the factorial of an integer number.
All operations were performed on integer numbers. You are to create a new program named lab6.11.asm
which computes the factorial of an integer using floating point numbers:
Run lab4.5.asm and the new program to complete the following test plan. Use scientific notation for the out-
put printed by lab6.11.asm (i.e. 3.141592e0).
10
15
20
40
Q 1:
Why some of the results printed by lab4.5.asm are negative?’
Q 2:
What are the maximum values of the input for which correct output is still printed?’
Integer n=
Step 2
Using some other method, calculate the exact value of 20! On a UNIX platform you can use bc (the “arbitrary-
precision arithmetic language”). If no software is available to you to do the job, then you will have to use the
old-good pencil and paper method.
Run again lab6.11.asm and write down the value printed for 20!
Q 3:
Why do the two values differ? ’
Q 4:
How many digits are exact in the result printed by lab6.11.asm?
exact_digits =
Q 5:
Based on the answer to the previous question, can you make a rough estimation of the number of digits that
should be printed for a floating-point single precision number?
digits_to_print =
Step 3
In step 1 you have used the integer to floating point conversion (cvt.s.w). Let’s now try a conversion from
float to integer. Modify lab6.11.asm (save the new program as lab6.12.asm):
• after printing the value returned by ‘FactorialSingle’, convert that value to an integer and print it too.
Run the program and complete the next test plan. Write down the value printed for the factorial as is, don’t
use scientific notation this time.
10
11
12
13
14
15
Highlight those cases where the integer output is a number different than the floating-point output.
Q 6:
Do you think the conversion operation yields a signed integer or an unsigned one? Explain.
Q 7:
As you can see the conversion instruction does not signal any error even if the conversion itself results in a
wrong value for the result. What is, in your opinion, the reason the architecture does not specify the conver-
sion instructions should report errors? ’
Q 8:
What would be the sequence of instructions that would emulate a signaling conversion? Do this only for the
float to integer conversion.
Laboratory 6: Postlab
Date Section
Name
Step 1
During the prelab exercises you have been, at the very least, annoyed by the fact that you could not correctly
31
print unsigned integers. By using print_int, a large unsigned integer (larger or equal to 2 ) would print
as a negative number. You now want to correct this by providing future users with a procedure that prints
unsigned integers. You will write a procedure, named ‘PrintUnsigned’ which:
Here is the C code for the integer to ASCII conversion function, itoa(). You will have to slightly modify
it and use it in your implementation of ‘PrintUnsigned’.
P.1:
/* code for itoa() from “The C Programming Language” by Kernigan and Richie
*/
if ((sign=n) < 0)
n = -n;
i=0;
do {
s[i++] = n%10 + '0';
} while((n/=10) > 0);
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
Hints:
• you will need to reserve space in ‘PrintUnsigned’ for the string you generate;
• make sure you use the appropriate (signed/unsigned) arithmetic functions
Step 2
Create a program called lab6.13.asm which you use to test ‘PrintUnsigned’, as follows:
31
• the program prints six times (in a loop) the value of a counter initialized to 2 – 3 ;
• at each iteration the program prints the counter using print_int and then the same counter using
‘PrintUnsigned’
• at each iteration the counter is incremented by one using an unsigned operation
Step 3
Return to your lab instructor a copy of lab6.13.asm together with this postlab description. Ask your lab
instructor whether copies of programs must be on paper (hardcopy), e-mail or both.