text
stringlengths
1
7.76k
source
stringlengths
17
81
246 Chapter 3 Arithmetic for Computers exponent range, its primary advantage is its greater precision because of the much larger significand. These formats go beyond MIPS. They are part of the IEEE 754 floating-point standard, found in virtually every computer invented since 1980. This standard has greatly improved both the ease of porting floating-point programs and the quality of computer arithmetic. To pack even more bits into the significand, IEEE 754 makes the leading 1-bit of normalized binary numbers implicit. Hence, the number is actually 24 bits long in single precision (implied 1 and a 23-bit fraction), and 53 bits long in double precision (1 + 52). To be precise, we use the term significand to represent the 24- or 53-bit number that is 1 plus the fraction, and fraction when we mean the 23- or 52-bit number. Since 0 has no leading 1, it is given the reserved exponent value 0 so that the hardware won’t attach a leading 1 to it. Thus 00 . . . 00two represents 0; the representation of the rest of the numbers uses the form from before with the hidden 1 added: (-1)S × (1 + Fraction) × 2E where the bits of the fraction represent a number between 0 and 1 and E specifies the value in the exponent field, to be given in detail shortly. If we number the bits of the fraction from left to right s1, s2, s3, . . . , then the value is (-1)S × (1 + (s1 × 2-1) + (s2 × 2-2) + (s3 × 2-3) + (s4 × 2-4) + …) × 2E Figure 3.14 shows the encodings of IEEE 754 floating-point numbers. Other features of IEEE 754 are special symbols to represent unusual events. For example, instead of interrupting on a divide by 0, software can set the result to a bit pattern representing +∞ or -∞; the largest exponent is reserved for these special symbols. When the programmer prints the results, the program will print an infinity symbol. (For the mathematically trained, the purpose of infinity is to form topological closure of the reals.) Single precision Double precision Object represented Exponent Fraction Exponent Fraction 0 0 0 0 0 0 Nonzero 0 Nonzero ± denormalized number 1–254 Anything 1–2046 Anything ± floating-point number 255 0 2047 0 ± infinity 255 Nonzero 2047 Nonzero NaN (Not a Number) FIGURE 3.14 IEEE 754 encoding of floating-point numbers. A separate sign bit determines the sign. Denormalized numbers are described in the Elaboration on page 270. This information is also found in Column 4 of the MIPS Reference Data Card at the front of this book.
clipped_hennesy_Page_244_Chunk5601
IEEE 754 even has a symbol for the result of invalid operations, such as 0/0 or subtracting infinity from infinity. This symbol is NaN, for Not a Number. The purpose of NaNs is to allow programmers to postpone some tests and decisions to a later time in the program when they are convenient. The designers of IEEE 754 also wanted a floating-point representation that could be easily processed by integer comparisons, especially for sorting. This desire is why the sign is in the most significant bit, allowing a quick test of less than, greater than, or equal to 0. (It’s a little more complicated than a simple integer sort, since this notation is essentially sign and magnitude rather than two’s complement.) Placing the exponent before the significand also simplifies the sorting of ­ floating-point numbers using integer comparison instructions, since numbers with bigger exponents look larger than numbers with smaller exponents, as long as both exponents have the same sign. Negative exponents pose a challenge to simplified sorting. If we use two’s complement or any other notation in which negative exponents have a 1 in the most significant bit of the exponent field, a negative exponent will look like a big number. For example, 1.0two × 2-1 would be represented as 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 . . . (Remember that the leading 1 is implicit in the significand.) The value 1.0two × 2+1 would look like the smaller binary number 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 . . . The desirable notation must therefore represent the most negative exponent as 00 . . . 00two and the most positive as 11 . . . 11two. This convention is called biased notation, with the bias being the number subtracted from the normal, unsigned representation to determine the real value. IEEE 754 uses a bias of 127 for single precision, so an exponent of -1 is represented by the bit pattern of the value -1 + 127ten, or 126ten = 0111 1110two, and +1 is represented by 1 + 127, or 128ten = 1000 0000two. The exponent bias for double precision is 1023. Biased exponent means that the value represented by a floating-point number is really (-1)S × (1 + Fraction) × 2(Exponent - Bias) The range of single precision numbers is then from as small as ±1.0000 0000 0000 0000 0000 000two × 2-126 to as large as ±1.1111 1111 1111 1111 1111 111two × 2+127. 3.5 Floating Point 247
clipped_hennesy_Page_245_Chunk5602
248 Chapter 3 Arithmetic for Computers Let’s show the representation. Floating-Point Representation Show the IEEE 754 binary representation of the number -0.75ten in single and double precision. The number -0.75ten is also -3/4ten or -3/22 ten It is also represented by the binary fraction -11two/22 ten or -0.11two In scientific notation, the value is -0.11two × 20 and in normalized scientific notation, it is -1.1two × 2-1 The general representation for a single precision number is (-1)S × (1 + Fraction) × 2(Exponent - 127) Subtracting the bias 127 from the exponent of -1.1two × 2-1 yields (-1)1 × (1 + .1000 0000 0000 0000 0000 000two) × 2(126-127) The single precision binary representation of -0.75ten is then 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 1 0 1 1 1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 bit 8 bits 23 bits EXAMPLE ANSWER
clipped_hennesy_Page_246_Chunk5603
The double precision representation is (-1)1 × (1 + .1000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000two) × 2(1022-1023) 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 1 0 1 1 1 1 1 1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 bit 11 bits 20 bits 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 32 bits Now let’s try going the other direction. Converting Binary to Decimal Floating Point What decimal number is represented by this single precision float? 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 1 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 . . . The sign bit is 1, the exponent field contains 129, and the fraction field contains 1 × 2-2 = 1/4, or 0.25. Using the basic equation, (-1)S × (1 + Fraction) × 2(Exponent - Bias) = (-1)1 × (1 + 0.25) × 2(129-127) = -1 × 1.25 × 22 = -1.25 × 4 = -5.0 In the next subsections, we will give the algorithms for floating-point addition and multiplication. At their core, they use the corresponding integer operations EXAMPLE ANSWER 3.5 Floating Point 249
clipped_hennesy_Page_247_Chunk5604
250 Chapter 3 Arithmetic for Computers on the significands, but extra bookkeeping is necessary to handle the exponents and normalize the result. We first give an intuitive derivation of the algorithms in decimal and then give a more detailed, binary version in the figures. Elaboration: In an attempt to increase range without removing bits from the signifi- cand, some computers before the IEEE 754 standard used a base other than 2. For example, the IBM 360 and 370 mainframe computers use base 16. Since changing the IBM exponent by one means shifting the significand by 4 bits, “normalized” base 16 numbers can have up to 3 leading bits of 0s! Hence, hexadecimal digits mean that up to 3 bits must be dropped from the significand, which leads to surprising problems in the accuracy of floating-point arithmetic. Recent IBM mainframes support IEEE 754 as well as the hex format. Floating-Point Addition Let’s add numbers in scientific notation by hand to illustrate the problems in floating-point addition: 9.999ten × 101 + 1.610ten × 10-1. Assume that we can store only four decimal digits of the significand and two decimal digits of the exponent. Step 1. To be able to add these numbers properly, we must align the decimal point of the number that has the smaller exponent. Hence, we need a form of the smaller number, 1.610ten × 10-1, that matches the larger exponent. We obtain this by observing that there are multiple representations of an unnormalized floating-point number in scientific notation: 1.610ten × 10-1 = 0.1610ten × 100 = 0.01610ten × 101 The number on the right is the version we desire, since its exponent matches the exponent of the larger number, 9.999ten × 101. Thus, the first step shifts the significand of the smaller number to the right until its corrected exponent matches that of the larger number. But we can represent only four decimal digits so, after shifting, the number is really 0.016ten × 101 Step 2. Next comes the addition of the significands: 9.999ten + 0.016ten 10.015ten The sum is 10.015ten × 101.
clipped_hennesy_Page_248_Chunk5605
Step 3. This sum is not in normalized scientific notation, so we need to adjust it: 10.015ten × 101 = 1.0015ten × 102 Thus, after the addition we may have to shift the sum to put it into normalized form, adjusting the exponent appropriately. This example shows shifting to the right, but if one number were positive and the other were negative, it would be possible for the sum to have many leading 0s, requiring left shifts. Whenever the exponent is increased or decreased, we must check for overflow or underflow—that is, we must make sure that the exponent still fits in its field. Step 4. Since we assumed that the significand can be only four digits long (excluding the sign), we must round the number. In our grammar school algorithm, the rules truncate the number if the digit to the right of the desired point is between 0 and 4 and add 1 to the digit if the number to the right is between 5 and 9. The number 1.0015ten × 102 is rounded to four digits in the significand to 1.002ten × 102 since the fourth digit to the right of the decimal point was between 5 and 9. Notice that if we have bad luck on rounding, such as adding 1 to a string of 9s, the sum may no longer be normalized and we would need to perform step 3 again. Figure 3.15 shows the algorithm for binary floating-point addition that follows this decimal example. Steps 1 and 2 are similar to the example just discussed: adjust the significand of the number with the smaller exponent and then add the two significands. Step 3 normalizes the results, forcing a check for overflow or underflow. The test for overflow and underflow in step 3 depends on the precision of the operands. Recall that the pattern of all 0 bits in the exponent is reserved and used for the floating-point representation of zero. Moreover, the pattern of all 1 bits in the exponent is reserved for indicating values and situations outside the scope of normal floating-point numbers (see the Elaboration on page 270). Thus, for single precision, the maximum exponent is 127, and the minimum exponent is -126. The limits for double precision are 1023 and -1022. 3.5 Floating Point 251
clipped_hennesy_Page_249_Chunk5606
252 Chapter 3 Arithmetic for Computers Still normalized? 4. Round the significand to the appropriate number of bits Yes Overflow or underflow? Start No Yes Done 1. Compare the exponents of the two numbers; shift the smaller number to the right until its exponent would match the larger exponent 2. Add the significands 3. Normalize the sum, either shifting right and incrementing the exponent or shifting left and decrementing the exponent No Exception FIGURE 3.15 Floating-point addition. The normal path is to execute steps 3 and 4 once, but if rounding causes the sum to be unnormalized, we must repeat step 3.
clipped_hennesy_Page_250_Chunk5607
Binary Floating-Point Addition Try adding the numbers 0.5ten and -0.4375ten in binary using the algorithm in Figure 3.15. Let’s first look at the binary version of the two numbers in normalized scien- tific notation, assuming that we keep 4 bits of precision: 0.5ten = 1/2ten = 1/21 ten = 0.1two = 0.1two × 20 = 1.000two × 2-1 -0.4375ten = -7/16ten = -7/24 ten = -0.0111two = -0.0111two × 20 = -1.110two × 2-2 Now we follow the algorithm: Step 1. The significand of the number with the lesser exponent (-1.11two × 2-2) is shifted right until its exponent matches the larger number: -1.110two × 2-2 = -0.111two × 2-1 Step 2. Add the significands: 1.000two × 2-1 + (-0.111two × 2-1) = 0.001two × 2-1 Step 3. Normalize the sum, checking for overflow or underflow: 0.001two × 2-1 = 0.010two × 2-2 = 0.100two × 2-3 = 1.000two × 2-4 Since 127 ≥ -4 ≥ -126, there is no overflow or underflow. (The biased exponent would be -4 + 127, or 123, which is between 1 and 254, the smallest and largest unreserved biased exponents.) Step 4. Round the sum: 1.000two × 2-4 The sum already fits exactly in 4 bits, so there is no change to the bits due to rounding. This sum is then 1.000two × 2-4 = 0.0001000two = 0.0001two = 1/24 ten = 1/16ten = 0.0625ten This sum is what we would expect from adding 0.5ten to -0.4375ten. EXAMPLE ANSWER 3.5 Floating Point 253
clipped_hennesy_Page_251_Chunk5608
254 Chapter 3 Arithmetic for Computers Compare exponents Small ALU Exponent difference Control Exponent Sign Fraction Big ALU Exponent Sign Fraction 0 1 0 1 0 1 Shift right 0 1 0 1 Increment or decrement Shift left or right Rounding hardware Exponent Sign Fraction Shift smaller number right Add Normalize Round FIGURE 3.16 Block diagram of an arithmetic unit dedicated to floating-point addition. The steps of Figure 3.15 correspond to each block, from top to bottom. First, the exponent of one operand is subtracted from the other using the small ALU to determine which is larger and by how much. This difference controls the three multiplexors; from left to right, they select the larger exponent, the significand of the smaller number, and the significand of the larger number. The smaller significand is shifted right, and then the significands are added together using the big ALU. The normalization step then shifts the sum left or right and increments or decrements the exponent. Rounding then creates the final result, which may require normalizing again to produce the final result. Many computers dedicate hardware to run floating-point operations as fast as possible. Figure 3.16 sketches the basic organization of hardware for floating-point addition.
clipped_hennesy_Page_252_Chunk5609
Floating-Point Multiplication Now that we have explained floating-point addition, let’s try floating-point multiplication. We start by multiplying decimal numbers in scientific notation by hand: 1.110ten × 1010 × 9.200ten × 10-5. Assume that we can store only four digits of the significand and two digits of the exponent. Step 1. Unlike addition, we calculate the exponent of the product by simply adding the exponents of the operands together: New exponent = 10 + (-5) = 5 Let’s do this with the biased exponents as well to make sure we obtain the same result: 10 + 127 = 137, and -5 + 127 = 122, so New exponent = 137 + 122 = 259 This result is too large for the 8-bit exponent field, so something is amiss! The problem is with the bias because we are adding the biases as well as the exponents: New exponent = (10 + 127) + (-5 + 127) = (5 + 2 × 127) = 259 Accordingly, to get the correct biased sum when we add biased numbers, we must subtract the bias from the sum: New exponent = 137 + 122 - 127 = 259 - 127 = 132 = (5 + 127) and 5 is indeed the exponent we calculated initially. Step 2. Next comes the multiplication of the significands: 1.110ten x 9.200ten 0000 0000 2220 9990 10212000ten There are three digits to the right of the decimal point for each operand, so the decimal point is placed six digits from the right in the product significand: 10.212000ten 3.5 Floating Point 255
clipped_hennesy_Page_253_Chunk5610
256 Chapter 3 Arithmetic for Computers Assuming that we can keep only three digits to the right of the decimal point, the product is 10.212 × 105. Step 3. This product is unnormalized, so we need to normalize it: 10.212ten × 105 = 1.0212ten × 106 Thus, after the multiplication, the product can be shifted right one digit to put it in normalized form, adding 1 to the exponent. At this point, we can check for overflow and underflow. Underflow may occur if both operands are small—that is, if both have large negative exponents. Step 4. We assumed that the significand is only four digits long (excluding the sign), so we must round the number. The number 1.0212ten × 106 is rounded to four digits in the significand to 1.021ten × 106 Step 5. The sign of the product depends on the signs of the original operands. If they are both the same, the sign is positive; otherwise, it’s negative. Hence, the product is +1.021ten × 106 The sign of the sum in the addition algorithm was determined by addition of the significands, but in multiplication, the sign of the product is determined by the signs of the operands. Once again, as Figure 3.17 shows, multiplication of binary floating-point numbers is quite similar to the steps we have just completed. We start with calculating the new exponent of the product by adding the biased exponents, being sure to subtract one bias to get the proper result. Next is multiplication of significands, followed by an optional normalization step. The size of the exponent is checked for overflow or underflow, and then the product is rounded. If rounding leads to further normalization, we once again check for exponent size. Finally, set the sign bit to 1 if the signs of the operands were different (negative product) or to 0 if they were the same (positive product). Binary Floating-Point Multiplication Let’s try multiplying the numbers 0.5ten and -0.4375ten, using the steps in Figure 3.17. EXAMPLE
clipped_hennesy_Page_254_Chunk5611
In binary, the task is multiplying 1.000two × 2-1 by - 1.110two × 2-2. Step 1. Adding the exponents without bias: -1 + (-2) = -3 or, using the biased representation: (-1 + 127) + (-2 + 127) - 127 = (-1 - 2) + (127 + 127 - 127) = -3 + 127 = 124 Step 2. Multiplying the significands: 1.000two x 1.110two 0000 1000 1000 1000 1110000two The product is 1.110000two × 2-3, but we need to keep it to 4 bits, so it is 1.110two × 2-3. Step 3. Now we check the product to make sure it is normalized, and then check the exponent for overflow or underflow. The product is already normalized and, since 127 ≥ -3 ≥ -126, there is no overflow or underflow. (Using the biased representation, 254 ≥ 124 ≥ 1, so the exponent fits.) Step 4. Rounding the product makes no change: 1.110two × 2-3 Step 5. Since the signs of the original operands differ, make the sign of the product negative. Hence, the product is -1.110two × 2-3 Converting to decimal to check our results: -1.110two × 2-3 = -0.001110two = -0.00111two = -7/25 ten = -7/32ten = -0.21875ten The product of 0.5ten and - 0.4375ten is indeed - 0.21875ten. ANSWER 3.5 Floating Point 257
clipped_hennesy_Page_255_Chunk5612
258 Chapter 3 Arithmetic for Computers 5. Set the sign of the product to positive if the signs of the original operands are the same; if they differ make the sign negative Still normalized? 4. Round the significand to the appropriate number of bits Yes Overflow or underflow? Start No Yes Done 1. Add the biased exponents of the two numbers, subtracting the bias from the sum to get the new biased exponent 2. Multiply the significands 3. Normalize the product if necessary, shifting it right and incrementing the exponent No Exception FIGURE 3.17 Floating-point multiplication. The normal path is to execute steps 3 and 4 once, but if rounding causes the sum to be unnormalized, we must repeat step 3.
clipped_hennesy_Page_256_Chunk5613
Floating-Point Instructions in MIPS MIPS supports the IEEE 754 single precision and double precision formats with these instructions: ■ ■Floating-point addition, single (add.s) and addition, double (add.d) ■ ■Floating-point subtraction, single (sub.s) and subtraction, double (sub.d) ■ ■Floating-point multiplication, single (mul.s) and multiplication, double (mul.d) ■ ■Floating-point division, single (div.s) and division, double (div.d) ■ ■Floating-point comparison, single (c.x.s) and comparison, double (c.x.d), where x may be equal (eq), not equal (neq), less than (lt), less than or equal (le), greater than (gt), or greater than or equal (ge) ■ ■Floating-point branch, true (bc1t) and branch, false (bc1f) Floating-point comparison sets a bit to true or false, depending on the comparison condition, and a floating-point branch then decides whether or not to branch, depending on the condition. The MIPS designers decided to add separate floating-point registers—called $f0, $f1, $f2, . . .—used either for single precision or double precision. Hence, they included separate loads and stores for floating-point registers: lwc1 and swc1. The base registers for floating-point data transfers remain integer registers. The MIPS code to load two single precision numbers from memory, add them, and then store the sum might look like this: lwc1 $f4,x($sp) # Load 32-bit F.P. number into F4 lwc1 $f6,y($sp) # Load 32-bit F.P. number into F6 add.s $f2,$f4,$f6 # F2 = F4 + F6 single precision swc1 $f2,z($sp) # Store 32-bit F.P. number from F2 A double precision register is really an even-odd pair of single precision registers, using the even register number as its name. Thus, the pair of single precision registers $f2 and $f3 also form the double precision register named $f2. Figure 3.18 summarizes the floating-point portion of the MIPS architecture revealed in this chapter, with the additions to support floating point shown in color. Similar to Figure 2.19 in Chapter 2, Figure 3.19 shows the encoding of these instructions. 3.5 Floating Point 259
clipped_hennesy_Page_257_Chunk5614
260 Chapter 3 Arithmetic for Computers MIPS floating-point operands Name Example Comments 32 floating- point registers $f0, $f1, $f2, . . . , $f31 MIPS floating-point registers are used in pairs for double precision numbers. 230 memory words Memory[0], Memory[4], . . . , Memory[4294967292] Accessed only by data transfer instructions. MIPS uses byte addresses, so sequential word addresses differ by 4. Memory holds data structures, such as arrays, and spilled registers, such as those saved on procedure calls. MIPS floating-point assembly language Category Instruction Example Meaning Comments Arithmetic FP add single add.s $f2,$f4,$f6 $f2 = $f4 + $f6 FP add (single precision) FP subtract single sub.s $f2,$f4,$f6 $f2 = $f4 – $f6 FP sub (single precision) FP multiply single mul.s $f2,$f4,$f6 $f2 = $f4 × $f6 FP multiply (single precision) FP divide single div.s $f2,$f4,$f6 $f2 = $f4 / $f6 FP divide (single precision) FP add double add.d $f2,$f4,$f6 $f2 = $f4 + $f6 FP add (double precision) FP subtract double sub.d $f2,$f4,$f6 $f2 = $f4 – $f6 FP sub (double precision) FP multiply double mul.d $f2,$f4,$f6 $f2 = $f4 × $f6 FP multiply (double precision) FP divide double div.d $f2,$f4,$f6 $f2 = $f4 / $f6 FP divide (double precision) Data transfer load word copr. 1 lwc1 $f1,100($s2) $f1 = Memory[$s2 + 100] 32-bit data to FP register store word copr. 1 swc1 $f1,100($s2) Memory[$s2 + 100] = $f1 32-bit data to memory Condi- tional branch branch on FP true bc1t 25 if (cond == 1) go to PC + 4 + 100 PC-relative branch if FP cond. branch on FP false bc1f 25 if (cond == 0) go to PC + 4 + 100 PC-relative branch if not cond. FP compare single (eq,ne,lt,le,gt,ge) c.lt.s $f2,$f4 if ($f2 < $f4) cond = 1; else cond = 0 FP compare less than single precision FP compare double (eq,ne,lt,le,gt,ge) c.lt.d $f2,$f4 if ($f2 < $f4) cond = 1; else cond = 0 FP compare less than double precision MIPS floating-point machine language Name Format Example Comments add.s R 17 16 6 4 2 0 add.s $f2,$f4,$f6 sub.s R 17 16 6 4 2 1 sub.s $f2,$f4,$f6 mul.s R 17 16 6 4 2 2 mul.s $f2,$f4,$f6 div.s R 17 16 6 4 2 3 div.s $f2,$f4,$f6 add.d R 17 17 6 4 2 0 add.d $f2,$f4,$f6 sub.d R 17 17 6 4 2 1 sub.d $f2,$f4,$f6 mul.d R 17 17 6 4 2 2 mul.d $f2,$f4,$f6 div.d R 17 17 6 4 2 3 div.d $f2,$f4,$f6 lwc1 I 49 20 2 100 lwc1 $f2,100($s4) swc1 I 57 20 2 100 swc1 $f2,100($s4) bc1t I 17 8 1 25 bc1t 25 bc1f I 17 8 0 25 bc1f 25 c.lt.s R 17 16 4 2 0 60 c.lt.s $f2,$f4 c.lt.d R 17 17 4 2 0 60 c.lt.d $f2,$f4 Field size 6 bits 5 bits 5 bits 5 bits 5 bits 6 bits All MIPS instructions 32 bits FIGURE 3.18 MIPS floating-point architecture revealed thus far. See Appendix B, Section B.10, for more detail. This information is also found in column 2 of the MIPS Reference Data Card at the front of this book.
clipped_hennesy_Page_258_Chunk5615
op(31:26): 28–26 31–29 0(000) 1(001) 2(010) 3(011) 4(100) 5(101) 6(110) 7(111) 0(000) Rfmt Bltz/gez j jal beq bne blez bgtz 1(001) addi addiu slti sltiu ANDi ORi xORi lui 2(010) TLB FlPt 3(011) 4(100) lb lh lwl lw lbu lhu lwr 5(101) sb sh swl sw swr 6(110) lwc0 lwc1 7(111) swc0 swc1 op(31:26) = 010001 (FlPt), (rt(16:16) = 0 => c = f, rt(16:16) = 1 => c = t), rs(25:21): 23–21 25–24 0(000) 1(001) 2(010) 3(011) 4(100) 5(101) 6(110) 7(111) 0(00) mfc1 cfc1 mtc1 ctc1 1(01) bc1.c 2(10) f = single f = double 3(11) op(31:26) = 010001 (FlPt), (f above: 10000 => f = s, 10001 => f = d), funct(5:0): 2–0 5–3 0(000) 1(001) 2(010) 3(011) 4(100) 5(101) 6(110) 7(111) 0(000) add.f sub.f mul.f div.f abs.f mov.f neg.f 1(001) 2(010) 3(011) 4(100) cvt.s.f cvt.d.f cvt.w.f 5(101) 6(110) c.f.f c.un.f c.eq.f c.ueq.f c.olt.f c.ult.f c.ole.f c.ule.f 7(111) c.sf.f c.ngle.f c.seq.f c.ngl.f c.lt.f c.nge.f c.le.f c.ngt.f FIGURE 3.19 MIPS floating-point instruction encoding. This notation gives the value of a field by row and by column. For example, in the top portion of the figure, lw is found in row number 4 (100two for bits 31–29 of the instruction) and column number 3 (011two for bits 28–26 of the instruction), so the corresponding value of the op field (bits 31–26) is 100011two. Underscore means the field is used elsewhere. For example, FlPt in row 2 and column 1 (op = 010001two) is defined in the bottom part of the figure. Hence sub.f in row 0 and column 1 of the bottom section means that the funct field (bits 5–0) of the instruction) is 000001two and the op field (bits 31–26) is 010001two. Note that the 5-bit rs field, specified in the middle portion of the figure, determines whether the operation is single precision (f = s, so rs = 10000) or double precision (f = d, so rs = 10001). Similarly, bit 16 of the instruction determines if the bc1.c instruction tests for true (bit 16 = 1 =>bc1.t) or false (bit 16 = 0 =>bc1.f). Instructions in color are described in Chapter 2 or this chapter, with Appendix B covering all instructions. This information is also found in column 2 of the MIPS Reference Data Card at the front of this book. 3.5 Floating Point 261
clipped_hennesy_Page_259_Chunk5616
262 Chapter 3 Arithmetic for Computers One issue that architects face in supporting floating-point arithmetic is whether to use the same registers used by the integer instructions or to add a special set for floating point. Because programs normally perform integer operations and floating-point operations on different data, separating the registers will only slightly increase the number of instructions needed to execute a program. The major impact is to create a separate set of data transfer instructions to move data between floating-point registers and memory. The benefits of separate floating-point registers are having twice as many registers without using up more bits in the instruction format, having twice the register bandwidth by having separate integer and floating-point register sets, and being able to customize registers to floating point; for example, some computers convert all sized operands in registers into a single internal format. Compiling a Floating-Point C Program into MIPS Assembly Code Let’s convert a temperature in Fahrenheit to Celsius: float f2c (float fahr) { return ((5.0/9.0) * (fahr – 32.0)); } Assume that the floating-point argument fahr is passed in $f12 and the result should go in $f0. (Unlike integer registers, floating-point register 0 can contain a number.) What is the MIPS assembly code? We assume that the compiler places the three floating-point constants in memory within easy reach of the global pointer $gp. The first two instruc­ tions load the constants 5.0 and 9.0 into floating-point registers: f2c: lwc1 $f16,const5($gp) # $f16 = 5.0 (5.0 in memory) lwc1 $f18,const9($gp) # $f18 = 9.0 (9.0 in memory) They are then divided to get the fraction 5.0/9.0: div.s $f16, $f16, $f18 # $f16 = 5.0 / 9.0 Hardware/ Software Interface EXAMPLE ANSWER
clipped_hennesy_Page_260_Chunk5617
(Many compilers would divide 5.0 by 9.0 at compile time and save the single constant 5.0/9.0 in memory, thereby avoiding the divide at runtime.) Next, we load the constant 32.0 and then subtract it from fahr ($f12): lwc1 $f18, const32($gp)# $f18 = 32.0 sub.s $f18, $f12, $f18 # $f18 = fahr – 32.0 Finally, we multiply the two intermediate results, placing the product in $f0 as the return result, and then return mul.s $f0, $f16, $f18 # $f0 = (5/9)*(fahr – 32.0) jr $ra # return Now let’s perform floating-point operations on matrices, code commonly found in scientific programs. Compiling Floating-Point C Procedure with Two-Dimensional Matrices into MIPS Most floating-point calculations are performed in double precision. Let’s per­ form matrix multiply of X = X + Y * Z. Let’s assume X, Y, and Z are all square matrices with 32 elements in each dimension. void mm (double x[][], double y[][], double z[][]) { int i, j, k; for (i = 0; i != 32; i = i + 1) for (j = 0; j != 32; j = j + 1) for (k = 0; k != 32; k = k + 1) x[i][j] = x[i][j] + y[i][k] * z[k][j]; } The array starting addresses are parameters, so they are in $a0, $a1, and $a2. Assume that the integer variables are in $s0, $s1, and $s2, respectively. What is the MIPS assembly code for the body of the procedure? Note that x[i][j] is used in the innermost loop above. Since the loop index is k, the index does not affect x[i][j], so we can avoid loading and storing x[i][j] each iteration. Instead, the compiler loads x[i][j] into a register outside the loop, accumulates the sum of the products of y[i][k] and z[k][j] in that same register, and then stores the sum into x[i][j] upon termination of the innermost loop. We keep the code simpler by using the assembly language pseudoinstructions li (which loads a constant into a register), and l.d and s.d (which the assembler turns into a pair of data transfer instructions, lwc1 or swc1, to a pair of floating-point registers). EXAMPLE ANSWER 3.5 Floating Point 263
clipped_hennesy_Page_261_Chunk5618
264 Chapter 3 Arithmetic for Computers The body of the procedure starts with saving the loop termination value of 32 in a temporary register and then initializing the three for loop variables: mm:... li $t1, 32 # $t1 = 32 (row size/loop end) li $s0, 0 # i = 0; initialize 1st for loop L1: li $s1, 0 # j = 0; restart 2nd for loop L2: li $s2, 0 # k = 0; restart 3rd for loop To calculate the address of x[i][j], we need to know how a 32 × 32, two- dimensional array is stored in memory. As you might expect, its layout is the same as if there were 32 single-dimension arrays, each with 32 elements. So the first step is to skip over the i “single-dimensional arrays,” or rows, to get the one we want. Thus, we multiply the index in the first dimension by the size of the row, 32. Since 32 is a power of 2, we can use a shift instead: sll $t2, $s0, 5 # $t2 = i * 25 (size of row of x) Now we add the second index to select the jth element of the desired row: addu $t2, $t2, $s1 # $t2 = i * size(row) + j To turn this sum into a byte index, we multiply it by the size of a matrix element in bytes. Since each element is 8 bytes for double precision, we can instead shift left by 3: sll $t2, $t2, 3 # $t2 = byte offset of [i][j] Next we add this sum to the base address of x, giving the address of x[i][j], and then load the double precision number x[i][j] into $f4: addu $t2, $a0, $t2 # $t2 = byte address of x[i][j] l.d $f4, 0($t2) # $f4 = 8 bytes of x[i][j] The following five instructions are virtually identical to the last five: calcu­ late the address and then load the double precision number z[k][j]. L3: sll $t0, $s2, 5 # $t0 = k * 25 (size of row of z) addu $t0, $t0, $s1 # $t0 = k * size(row) + j sll $t0, $t0, 3 # $t0 = byte offset of [k][j] addu $t0, $a2, $t0 # $t0 = byte address of z[k][j] l.d $f16, 0($t0) # $f16 = 8 bytes of z[k][j] Similarly, the next five instructions are like the last five: calculate the address and then load the double precision number y[i][k].
clipped_hennesy_Page_262_Chunk5619
sll $t0, $s0, 5 # $t0 = i * 25 (size of row of y) addu $t0, $t0, $s2 # $t0 = i * size(row) + k sll $t0, $t0, 3 # $t0 = byte offset of [i][k] addu $t0, $a1, $t0 # $t0 = byte address of y[i][k] l.d $f18, 0($t0) # $f18 = 8 bytes of y[i][k] Now that we have loaded all the data, we are finally ready to do some floating-point operations! We multiply elements of y and z located in registers $f18 and $f16, and then accumulate the sum in $f4. mul.d $f16, $f18, $f16 # $f16 = y[i][k] * z[k][j] add.d $f4, $f4, $f16 # f4 = x[i][j]+ y[i][k] * z[k][j] The final block increments the index k and loops back if the index is not 32. If it is 32, and thus the end of the innermost loop, we need to store the sum accumulated in $f4 into x[i][j]. addiu $s2, $s2, 1 # $k k + 1 bne $s2, $t1, L3 # if (k != 32) go to L3 s.d $f4, 0($t2) # x[i][j] = $f4 Similarly, these final four instructions increment the index variable of the middle and outermost loops, looping back if the index is not 32 and exiting if the index is 32. addiu $s1, $s1, 1 # $j = j + 1 bne $s1, $t1, L2 # if (j != 32) go to L2 addiu $s0, $s0, 1 # $i = i + 1 bne $s0, $t1, L1 # if (i != 32) go to L1 ... Elaboration: The array layout discussed in the example, called row-major order, is used by C and many other programming languages. Fortran instead uses column-major order, whereby the array is stored column by column. Elaboration: Only 16 of the 32 MIPS floating-point registers could originally be used for double precision operations: $f0, $f2, $f4, ..., $f30. Double precision is computed using pairs of these single precision registers. The odd-numbered floating- point registers were used only to load and store the right half of 64-bit floating-point numbers. MIPS-32 added l.d and s.d to the instruction set. MIPS-32 also added “paired single” versions of all floating-point instructions, where a single instruction results in two parallel floating-point operations on two 32-bit operands inside 64-bit registers. For example, add.ps $f0, $f2, $f4 is equivalent to add.s $f0, $f2, $f4 followed by add.s $f1, $f3, $f5. 3.5 Floating Point 265
clipped_hennesy_Page_263_Chunk5620
266 Chapter 3 Arithmetic for Computers Elaboration: Another reason for separate integers and floating-point registers is that microprocessors in the 1980s didn’t have enough transistors to put the floating-point unit on the same chip as the integer unit. Hence, the floating-point unit, including the floating- point registers, was optionally available as a second chip. Such optional accelerator chips are called coprocessors, and explain the acronym for floating-point loads in MIPS: lwc1 means load word to coprocessor 1, the floating-point unit. (Coprocessor 0 deals with virtual memory, described in Chapter 5.) Since the early 1990s, microprocessors have integrated floating point (and just about everything else) on chip, and hence the term coprocessor joins accumulator and core memory as quaint terms that date the speaker. Elaboration: As mentioned in Section 3.4, accelerating division is more challenging than multiplication. In addition to SRT, another technique to leverage a fast multiplier is Newton’s iteration, where division is recast as finding the zero of a function to find the reciprocal 1/x, which is then multiplied by the other operand. Iteration techniques cannot be rounded properly without calculating many extra bits. A TI chip solves this problem by calculating an extra-precise reciprocal. Elaboration: Java embraces IEEE 754 by name in its definition of Java floating-point data types and operations. Thus, the code in the first example could have well been generated for a class method that converted Fahrenheit to Celsius. The second example uses multiple dimensional arrays, which are not explicitly supported in Java. Java allows arrays of arrays, but each array may have its own length, unlike multiple dimensional arrays in C. Like the examples in Chapter 2, a Java version of this second example would require a good deal of checking code for array bounds, including a new length calculation at the end of row access. It would also need to check that the object reference is not null. Accurate Arithmetic Unlike integers, which can represent exactly every number between the smallest and largest number, floating-point numbers are normally approximations for a number they can’t really represent. The reason is that an infinite variety of real numbers exists between, say, 0 and 1, but no more than 253 can be represented exactly in double precision floating point. The best we can do is getting the floating-point representation close to the actual number. Thus, IEEE 754 offers several modes of rounding to let the programmer pick the desired approximation. Rounding sounds simple enough, but to round accurately requires the hardware to include extra bits in the calculation. In the preceding examples, we were vague on the number of bits that an intermediate representation can occupy, but clearly, if every intermediate result had to be truncated to the exact number of digits, there would be no opportunity to round. IEEE 754, therefore, always keeps two extra bits on the right during intermediate additions, called guard and round, respectively. Let’s do a decimal example to illustrate their value. guard The first of two extra bits kept on the right during intermediate calculations of floating- point numbers; used to improve rounding accuracy. round Method to make the intermediate floating‑point result fit the floating-point format; the goal is typically to find the nearest number that can be represented in the format.
clipped_hennesy_Page_264_Chunk5621
Rounding with Guard Digits Add 2.56ten × 100 to 2.34ten × 102, assuming that we have three significant decimal digits. Round to the nearest decimal number with three significant decimal digits, first with guard and round digits, and then without them. First we must shift the smaller number to the right to align the exponents, so 2.56ten × 100 becomes 0.0256ten × 102. Since we have guard and round digits, we are able to represent the two least significant digits when we align expo­ nents. The guard digit holds 5 and the round digit holds 6. The sum is 2.3400ten + 0.0256ten 2.3656ten Thus the sum is 2.3656ten × 102. Since we have two digits to round, we want values 0 to 49 to round down and 51 to 99 to round up, with 50 being the tiebreaker. Rounding the sum up with three significant digits yields 2.37ten × 102. Doing this without guard and round digits drops two digits from the calculation. The new sum is then 2.34ten + 0.02ten 2.36ten The answer is 2.36ten × 102, off by 1 in the last digit from the sum above. Since the worst case for rounding would be when the actual number is halfway between two floating-point representations, accuracy in floating point is normally measured in terms of the number of bits in error in the least significant bits of the significand; the measure is called the number of units in the last place, or ulp. If a number were off by 2 in the least significant bits, it would be called off by 2 ulps. Provided there is no overflow, underflow, or invalid operation exceptions, IEEE 754 guarantees that the computer uses the number that is within one-half ulp. Elaboration: Although the example above really needed just one extra digit, multiply can need two. A binary product may have one leading 0 bit; hence, the normalizing step must shift the product one bit left. This shifts the guard digit into the least significant bit of the product, leaving the round bit to help accurately round the product. EXAMPLE ANSWER units in the last place (ulp) The number of bits in error in the least significant bits of the significand between the actual number and the number that can be represented. 3.5 Floating Point 267
clipped_hennesy_Page_265_Chunk5622
268 Chapter 3 Arithmetic for Computers IEEE 754 has four rounding modes: always round up (toward +∞), always round down (toward – ∞), truncate, and round to nearest even. The final mode determines what to do if the number is exactly halfway in between. The U.S. Internal Revenue Service (IRS) always rounds 0.50 dollars up, possibly to the benefit of the IRS. A more equitable way would be to round up this case half the time and round down the other half. IEEE 754 says that if the least significant bit retained in a halfway case would be odd, add one; if it’s even, truncate. This method always creates a 0 in the least significant bit in the tie-breaking case, giving the rounding mode its name. This mode is the most commonly used, and the only one that Java supports. The goal of the extra rounding bits is to allow the computer to get the same results as if the intermediate results were calculated to infinite precision and then rounded. To support this goal and round to the nearest even, the standard has a third bit in addition to guard and round; it is set whenever there are nonzero bits to the right of the round bit. This sticky bit allows the computer to see the difference between 0.50 . . . 00 ten and 0.50 . . . 01ten when rounding. The sticky bit may be set, for example, during addition, when the smaller number is shifted to the right. Suppose we added 5.01ten × 10–1 to 2.34ten × 102 in the example above. Even with guard and round, we would be adding 0.0050 to 2.34, with a sum of 2.3450. The sticky bit would be set, since there are nonzero bits to the right. Without the sticky bit to remember whether any 1s were shifted off, we would assume the number is equal to 2.345000 . . . 00 and round to the nearest even of 2.34. With the sticky bit to remember that the number is larger than 2.345000 . . . 00, we round instead to 2.35. Elaboration: PowerPC, SPARC64, and AMD SSE5 architectures provide a single instruction that does a multiply and add on three registers: a = a + (b × c). Obviously, this instruction allows potentially higher floating-point performance for this common operation. Equally important is that instead of performing two roundings—-after the multiply and then after the add—which would happen with separate instructions, the multiply add instruction can perform a single rounding after the add. A single rounding step increases the precision of multiply add. Such operations with a single rounding are called fused multiply add. It was added to the revised IEEE 754 standard (see Section 3.10 on the CD). Summary The Big Picture that follows reinforces the stored-program concept from Chapter 2; the meaning of the information cannot be determined just by looking at the bits, for the same bits can represent a variety of objects. This section shows that computer arithmetic is finite and thus can disagree with natural arithmetic. For example, the IEEE 754 standard floating-point representation (-1)S × (1 + Fraction) × 2(Exponent - Bias) is almost always an approximation of the real number. Computer systems must take care to minimize this gap between computer arithmetic and arithmetic in the real world, and programmers at times need to be aware of the implications of this approximation. sticky bit A bit used in rounding in addition to guard and round that is set whenever there are nonzero bits to the right of the round bit. fused multiply add A floating-point instruction that performs both a multiply and an add, but rounds only once after the add.
clipped_hennesy_Page_266_Chunk5623
Bit patterns have no inherent meaning. They may represent signed integers, unsigned integers, floating-point numbers, instructions, and so on. What is represented depends on the instruction that operates on the bits in the word. The major difference between computer numbers and numbers in the real world is that computer numbers have limited size and hence limited precision; it’s possible to calculate a number too big or too small to be represented in a word. Programmers must remember these limits and write programs accordingly. C type Java type Data transfers Operations int int lw, sw, lui addu, addiu, subu, mult, div, AND, ANDi, OR, ORi, NOR, slt, slti unsigned int — lw, sw, lui addu, addiu, subu, multu, divu, AND, ANDi, OR, ORi, NOR, sltu, sltiu char — lb, sb, lui add, addi, sub, mult, div AND, ANDi, OR, ORi, NOR, slt, slti — char lh, sh, lui addu, addiu, subu, multu, divu, AND, ANDi, OR, ORi, NOR, sltu, sltiu float float lwc1, swc1 add.s, sub.s, mult.s, div.s, c.eq.s, c.lt.s, c.le.s double double l.d, s.d add.d, sub.d, mult.d, div.d, c.eq.d, c.lt.d, c.le.d In the last chapter, we presented the storage classes of the programming language C (see the Hardware/Software Interface section in Section 2.7). The table above shows some of the C and Java data types, the MIPS data transfer instructions, and instructions that operate on those types that appear in Chapter 2 and this chapter. Note that Java omits unsigned integers. Suppose there was a 16-bit IEEE 754 floating-point format with five exponent bits. What would be the likely range of numbers it could represent? 1. 1.0000 0000 00 × 20 to 1.1111 1111 11 × 231, 0 2. ±1.0000 0000 0 × 2-14 to ±1.1111 1111 1 × 215, ±0, ±∞, NaN 3. ±1.0000 0000 00 × 2-14 to ±1.1111 1111 11 × 215, ±0, ±∞, NaN 4. ±1.0000 0000 00 × 2-15 to ±1.1111 1111 11 × 214, ±0, ±∞, NaN The BIG Picture Hardware/ Software Interface Check Yourself 3.5 Floating Point 269
clipped_hennesy_Page_267_Chunk5624
270 Chapter 3 Arithmetic for Computers Elaboration: To accommodate comparisons that may include NaNs, the standard includes ordered and unordered as options for compares. Hence, the full MIPS instruction set has many flavors of compares to support NaNs. (Java does not support unordered compares.) In an attempt to squeeze every last bit of precision from a floating-point operation, the standard allows some numbers to be represented in unnormalized form. Rather than having a gap between 0 and the smallest normalized number, IEEE allows denormalized numbers (also known as denorms or subnormals). They have the same exponent as zero but a nonzero fraction. They allow a number to degrade in significance until it becomes 0, called gradual underflow. For example, the smallest positive single precision normalized number is 1.0000 0000 0000 0000 0000 000two × 2–126 but the smallest single precision denormalized number is 0.0000 0000 0000 0000 0000 001two × 2–126, or 1.0two × 2–149 For double precision, the denorm gap goes from 1.0 × 2–1022 to 1.0 × 2–1074. The possibility of an occasional unnormalized operand has given headaches to floating- point designers who are trying to build fast floating-point units. Hence, many computers cause an exception if an operand is denormalized, letting software complete the operation. Although software implementations are perfectly valid, their lower performance has lessened the popularity of denorms in portable floating-point software. Moreover, if programmers do not expect denorms, their programs may surprise them. 3.6 Parallelism and Computer Arithmetic: Associativity Programs have typically been written first to run sequentially before being rewritten to run concurrently, so a natural question is, “do the two versions get the same answer?” If the answer is no, you presume there is a bug in the parallel version that you need to track down. This approach assumes that computer arithmetic does not affect the results when going from sequential to parallel. That is, if you were to add a million numbers together, you would get the same results whether you used 1 processor or 1000 processors. This assumption holds for two’s complement integers, even if the computation overflows. Another way to say this is that integer addition is associative. Alas, because floating-point numbers are approximations of real numbers and because computer arithmetic has limited precision, it does not hold for floating- point numbers. That is, floating-point addition is not associative. Testing Associativity of Floating-Point Addition See if x + (y + z) = (x + y) + z. For example, suppose x = -1.5ten × 1038, y = 1.5ten × 1038, and z = 1.0, and that these are all single precision numbers. EXAMPLE
clipped_hennesy_Page_268_Chunk5625
Given the great range of numbers that can be represented in floating point, problems occur when adding two large numbers of opposite signs plus a small number, as we shall see: x + (y + z) = -1.5ten × 1038 + (1.5ten × 1038 + 1.0) = -1.5ten × 1038 + (1.5ten × 1038) = 0.0 (x + y) + z = (-1.5ten × 1038 + 1.5ten × 1038) + 1.0 = (0.0ten) + 1.0 = 1.0 Therefore x + (y + z) ≠ (x + y) + z, so floating-point addition is not associative. Since floating-point numbers have limited precision and result in approximations of real results, 1.5ten × 1038 is so much larger than 1.0ten that 1.5ten × 1038 + 1.0 is still 1.5ten × 1038. That is why the sum of x, y, and z is 0.0 or 1.0, depending on the order of the floating-point additions, and hence floating-point add is not associative. A more vexing version of this pitfall occurs on a parallel computer where the operating system scheduler may use a different number of processors depending on what other programs are running on a parallel computer. The unaware parallel programmer may be flummoxed by his or her program getting slightly different answers each time it is run for the same identical code and the same identical input, as the varying number of processors from each run would cause the floating-point sums to be calculated in different orders. Given this quandary, programmers who write parallel code with floating-point numbers need to verify whether the results are credible even if they don’t give the same exact answer as the sequential code. The field that deals with such issues is called numerical analysis, which is the subject of textbooks in its own right. Such concerns are one reason for the popularity of numerical libraries such as LAPACK and SCALAPAK, which have been validated in both their sequential and parallel forms. Elaboration: A subtle version of the associativity issue occurs when two processors perform a redundant computation that is executed in different order so they get slightly different answers, although both answers are considered accurate. The bug occurs if a conditional branch compares to a floating-point number and the two processors take different branches when common sense reasoning suggests they should take the same branch. ANSWER 3.6 Parallelism and Computer Arithmetic: Associativity 271
clipped_hennesy_Page_269_Chunk5626
272 Chapter 3 Arithmetic for Computers 3.7 Real Stuff: Floating Point in the x86 The x86 has regular multiply and divide instructions that operate entirely on its normal registers, unlike the reliance on separate Hi and Lo registers in MIPS. (In fact, later versions of the MIPS instruction set have added similar instructions.) The main differences are found in floating-point instructions. The x86 floating- point architecture is different from all other computers in the world. The x86 Floating-Point Architecture The Intel 8087 floating-point coprocessor was announced in 1980. This architecture extended the 8086 with about 60 floating-point instructions. Intel provided a stack architecture with its floating-point instructions: loads push numbers onto the stack, operations find operands in the two top elements of the stacks, and stores can pop elements off the stack. Intel supplemented this stack architecture with instructions and addressing modes that allow the architecture to have some of the benefits of a register-memory model. In addition to finding operands in the top two elements of the stack, one operand can be in memory or in one of the seven registers on-chip below the top of the stack. Thus, a complete stack instruction set is supplemented by a limited set of register-memory instructions. This hybrid is still a restricted register-memory model, however, since loads always move data to the top of the stack while incrementing the top-of-stack pointer, and stores can only move the top of stack to memory. Intel uses the notation ST to indicate the top of stack, and ST(i) to represent the ith register below the top of stack. Another novel feature of this architecture is that the operands are wider in the register stack than they are stored in memory, and all operations are performed at this wide internal precision. Unlike the maximum of 64 bits on MIPS, the x86 floating- point operands on the stack are 80 bits wide. Numbers are automatically converted to the internal 80-bit format on a load and converted back to the appropriate size on a store. This double extended precision is not supported by programming languages, although it has been useful to programmers of mathematical software. Memory data can be 32-bit (single precision) or 64-bit (double precision) ­floating-point numbers. The register-memory version of these instructions will then convert the memory operand to this Intel 80-bit format before perform- ing the operation. The data transfer instructions also will automatically convert 16- and 32-bit integers to floating point, and vice versa, for integer loads and stores.
clipped_hennesy_Page_270_Chunk5627
The x86 floating-point operations can be divided into four major classes: 1. Data movement instructions, including load, load constant, and store 2. Arithmetic instructions, including add, subtract, multiply, divide, square root, and absolute value 3. Comparison, including instructions to send the result to the integer processor so that it can branch 4. Transcendental instructions, including sine, cosine, log, and exponentiation Figure 3.20 shows some of the 60 floating-point operations. Note that we get even more combinations when we include the operand modes for these operations. Figure 3.21 shows the many options for floating-point add. Data transfer Arithmetic Compare Transcendental F{I}LD mem/ST(i) F{I}ADD{P} mem/ST(i) F{I}COM{P} FPATAN F{I}ST{P} mem/ ST(i) F{I}SUB{R}{P} mem/ST(i) F{I}UCOM{P}{P} F2XM1 FLDPI F{I}MUL{P} mem/ST(i) FSTSW AX/mem FCOS FLD1 F{I}DIV{R}{P} mem/ST(i) FPTAN FLDZ FSQRT FPREM FABS FSIN FRNDINT FYL2X FIGURE 3.20 The floating-point instructions of the x86. We use the curly brackets {} to show optional variations of the basic operations: {I} means there is an integer version of the instruction, {P} means this variation will pop one operand off the stack after the operation, and {R} means reverse the order of the operands in this operation. The first column shows the data transfer instructions, which move data to memory or to one of the registers below the top of the stack. The last three operations in the first column push constants on the stack: pi, 1.0, and 0.0. The second column contains the arithmetic operations described above. Note that the last three operate only on the top of stack. The third column is the compare instructions. Since there are no special floating-point branch instructions, the result of the compare must be transferred to the integer CPU via the FSTSW instruction, either into the AX register or into memory, followed by an SAHF instruction to set the condition codes. The floating-point comparison can then be tested using integer branch instructions. The final column gives the higher-level floating-point operations. Not all combinations suggested by the notation are provided. Hence, F{I}SUB{R}{P} operations represent these instructions found in the x86: FSUB, FISUB, FSUBR, FISUBR, FSUBP, FSUBRP. For the integer subtract instructions, there is no pop (FISUBP) or reverse pop (FISUBRP). The floating-point instructions are encoded using the ESC opcode of the 8086 and the postbyte address specifier (see Figure 2.47). The memory operations reserve 2 bits to decide whether the operand is a 32- or 64-bit floating point or a 16- or 32-bit integer. Those same 2 bits are used in versions that do not access memory to decide whether the stack should be popped after the operation and whether the top of stack or a lower register should get the result. 3.7 Real Stuff: Floating Point in the x86 273
clipped_hennesy_Page_271_Chunk5628
274 Chapter 3 Arithmetic for Computers Instruction Operands Comment FADD Both operands in stack; result replaces top of stack. FADD ST(i) One source operand is ith register below the top of stack; result replaces the top of stack. FADD ST(i), ST One source operand is the top of stack; result replaces ith register below the top of stack. FADD mem32 One source operand is a 32-bit location in memory; result replaces the top of stack. FADD mem64 One source operand is a 64-bit location in memory; result replaces the top of stack. FIGURE 3.21 The variations of operands for floating-point add in the x86. In the past, floating-point performance of the x86 family lagged far behind other computers. As a result, Intel created a more traditional floating-point architecture as part of SSE2. The Intel Streaming SIMD Extension 2 (SSE2) Floating-Point Architecture Chapter 2 notes that in 2001 Intel added 144 instructions to its architecture, including double precision floating-point registers and operations. It includes eight 64-bit registers that can be used for floating-point operands, giving the compiler a different target for floating-point operations than the unique stack architecture. Compilers can choose to use the eight SSE2 registers as floating-point registers like those found in other computers. AMD expanded the number to 16 registers as part of AMD64, which Intel relabeled EM64T for its use. Figure 3.22 summarizes the SSE and SSE2 instructions. In addition to holding a single precision or double precision number in a register, Intel allows multiple floating-point operands to be packed into a single 128-bit SSE2 register: four single precision or two double precision. Thus, the 16 floating- point registers for SSE2 are actually 128 bits wide. If the operands can be arranged in memory as 128-bit aligned data, then 128-bit data transfers can load and store multiple operands per instruction. This packed floating-point format is supported by arithmetic operations that can operate simultaneously on four singles (PS) or two doubles (PD). This architecture more than doubles performance over the stack architecture.
clipped_hennesy_Page_272_Chunk5629
Data transfer Arithmetic Compare MOV{A/U}{SS/PS/SD/ PD} xmm, mem/xmm ADD{SS/PS/SD/PD} xmm, mem/xmm CMP{SS/PS/SD/ PD} SUB{SS/PS/SD/PD} xmm, mem/xmm MOV {H/L} {PS/PD} xmm, mem/xmm MUL{SS/PS/SD/PD} xmm, mem/xmm DIV{SS/PS/SD/PD} xmm, mem/xmm SQRT{SS/PS/SD/PD} mem/xmm MAX {SS/PS/SD/PD} mem/xmm MIN{SS/PS/SD/PD} mem/xmm FIGURE 3.22 The SSE/SSE2 floating-point instructions of the x86. xmm means one operand is a 128-bit SSE2 register, and mem/xmm means the other operand is either in memory or it is an SSE2 register. We use the curly brackets {} to show optional variations of the basic operations: {SS} stands for Scalar Single precision floating point, or one 32-bit operand in a 128-bit register; {PS} stands for Packed Single precision floating point, or four 32-bit operands in a 128-bit register; {SD} stands for Scalar Double precision floating point, or one 64-bit operand in a 128-bit register; {PD} stands for Packed Double precision floating point, or two 64-bit operands in a 128-bit register; {A} means the 128-bit operand is aligned in memory; {U} means the 128-bit operand is unaligned in memory; {H} means move the high half of the 128-bit operand; and {L} means move the low half of the 128-bit operand. 3.8 Fallacies and Pitfalls Arithmetic fallacies and pitfalls generally stem from the difference between the limited precision of computer arithmetic and the unlimited precision of natural arithmetic. Fallacy: Just as a left shift instruction can replace an integer multiply by a power of 2, a right shift is the same as an integer division by a power of 2. Recall that a binary number x, where xi means the ith bit, represents the number . . . + (x3 × 23) + (x2 × 22) + (x1 × 21) + (x0 × 20) Shifting the bits of x right by n bits would seem to be the same as dividing by 2n. And this is true for unsigned integers. The problem is with signed integers. For example, suppose we want to divide -5ten by 4ten; the quotient should be -1ten. The two’s complement representation of -5ten is Thus mathematics may be defined as the subject in which we never know what we are talking about, nor whether what we are saying is true. Bertrand Russell, Recent Words on the Principles of Mathematics, 1901 3.8 Fallacies and Pitfalls 275
clipped_hennesy_Page_273_Chunk5630
276 Chapter 3 Arithmetic for Computers 1111 1111 1111 1111 1111 1111 1111 1011two According to this fallacy, shifting right by two should divide by 4ten (22): 0011 1111 1111 1111 1111 1111 1111 1110two With a 0 in the sign bit, this result is clearly wrong. The value created by the shift right is actually 1,073,741,822ten instead of -1ten. A solution would be to have an arithmetic right shift that extends the sign bit instead of shifting in 0s. A 2-bit arithmetic shift right of -5ten produces 1111 1111 1111 1111 1111 1111 1111 1110two The result is -2ten instead of -1ten; close, but no cigar. Pitfall: The MIPS instruction add immediate unsigned (addiu) sign-extends its 16-bit immediate field. Despite its name, add immediate unsigned (addiu) is used to add constants to signed integers when we don’t care about overflow. MIPS has no subtract immediate instruction, and negative numbers need sign extension, so the MIPS architects decided to sign-extend the immediate field. Fallacy: Only theoretical mathematicians care about floating-point accuracy. Newspaper headlines of November 1994 prove this statement is a fallacy (see Figure 3.23). The following is the inside story behind the headlines. The Pentium uses a standard floating-point divide algorithm that generates multiple quotient bits per step, using the most significant bits of divisor and dividend to guess the next 2 bits of the quotient. The guess is taken from a lookup table containing -2, -1, 0, +1, or +2. The guess is multiplied by the divisor and subtracted from the remainder to generate a new remainder. Like nonrestoring division, if a previous guess gets too large a remainder, the partial remainder is adjusted in a subsequent pass. Evidently, there were five elements of the table from the 80486 that Intel thought could never be accessed, and they optimized the PLA to return 0 instead of 2 in these situations on the Pentium. Intel was wrong: while the first 11 bits were always correct, errors would show up occasionally in bits 12 to 52, or the 4th to 15th decimal digits. The following is a timeline of the Pentium bug morality play. ■ ■July 1994: Intel discovers the bug in the Pentium. The actual cost to fix the bug was several hundred thousand dollars. Following normal bug fix procedures, it will take months to make the change, reverify, and put the corrected chip into production. Intel planned to put good chips into production in January 1995, estimating that 3 to 5 million Pentiums would be produced with the bug.
clipped_hennesy_Page_274_Chunk5631
■ ■September 1994: A math professor at Lynchburg College in Virginia, Thomas Nicely, discovers the bug. After calling Intel technical support and getting no official reaction, he posts his discovery on the Internet. It quickly gained a following, and some pointed out that even small errors become big when multiplied by big numbers: the fraction of people with a rare disease times the population of Europe, for example, might lead to the wrong estimate of the number of sick people. ■ ■November 7, 1994: Electronic Engineering Times puts the story on its front page, which is soon picked up by other newspapers. ■ ■November 22, 1994: Intel issues a press release, calling it a “glitch.” The Pentium “can make errors in the ninth digit. . . . Even most engineers and financial analysts require accuracy only to the fourth or fifth decimal point. Spreadsheet FIGURE 3.23 A sampling of newspaper and magazine articles from November 1994, including the New York Times, San Jose Mercury News, San Francisco Chronicle, and Infoworld. The Pentium floating-point divide bug even made the “Top 10 List” of the David Letterman Late Show on television. Intel eventually took a $300 million write-off to replace the buggy chips. 3.8 Fallacies and Pitfalls 277
clipped_hennesy_Page_275_Chunk5632
278 Chapter 3 Arithmetic for Computers and word processor users need not worry. . . . There are maybe several dozen people that this would affect. So far, we’ve only heard from one. . . . [Only] theoretical mathematicians (with Pentium computers purchased before the summer) should be concerned.” What irked many was that customers were told to describe their application to Intel, and then Intel would decide whether or not their application merited a new Pentium without the divide bug. ■ ■December 5, 1994: Intel claims the flaw happens once in 27,000 years for the typical spreadsheet user. Intel assumes a user does 1000 divides per day and multiplies the error rate assuming floating-point numbers are random, which is one in 9 billion, and then gets 9 million days, or 27,000 years. Things begin to calm down, despite Intel neglecting to explain why a typical customer would access floating-point numbers randomly. ■ ■December 12, 1994: IBM Research Division disputes Intel’s calculation of the rate of errors (you can access this article by visiting www.mkp.com/books_ catalog/cod/links.htm). IBM claims that common spreadsheet programs, recalculating for 15 minutes a day, could produce Pentium-related errors as often as once every 24 days. IBM assumes 5000 divides per second, for 15 minutes, yielding 4.2 million divides per day, and does not assume random distribution of numbers, instead calculating the chances as one in 100 million. As a result, IBM immediately stops shipment of all IBM personal computers based on the Pentium. Things heat up again for Intel. ■ ■December 21, 1994: Intel releases the following, signed by Intel’s president, chief executive officer, chief operating officer, and chairman of the board: “We at Intel wish to sincerely apologize for our handling of the recently publicized Pentium processor flaw. The Intel Inside symbol means that your computer has a microprocessor second to none in quality and performance. Thousands of Intel employees work very hard to ensure that this is true. But no microprocessor is ever perfect. What Intel continues to believe is technically an extremely minor problem has taken on a life of its own. Although Intel firmly stands behind the quality of the current version of the Pentium processor, we recognize that many users have concerns. We want to resolve these concerns. Intel will exchange the current version of the Pentium processor for an updated version, in which this floating- point divide flaw is corrected, for any owner who requests it, free of charge anytime during the life of their computer.” Analysts estimate that this recall cost Intel $500 million, and Intel engineers did not get a Christmas bonus that year. This story brings up a few points for everyone to ponder. How much cheaper would it have been to fix the bug in July 1994? What was the cost to repair the damage to Intel’s reputation? And what is the corporate responsibility in disclosing bugs in a product so widely used and relied upon as a microprocessor?
clipped_hennesy_Page_276_Chunk5633
MIPS core instructions Name Format MIPS arithmetic core Name Format add add R multiply mult R add immediate addi I multiply unsigned multu R add unsigned addu R divide div R add immediate unsigned addiu I divide unsigned divu R subtract sub R move from Hi mfhi R subtract unsigned subu R move from Lo mflo R AND AND R move from system control (EPC) mfc0 R AND immediate ANDi I floating-point add single add.s R OR OR R floating-point add double add.d R OR immediate ORi I floating-point subtract single sub.s R NOR NOR R floating-point subtract double sub.d R shift left logical sll R floating-point multiply single mul.s R shift right logical srl R floating-point multiply double mul.d R load upper immediate lui I floating-point divide single div.s R load word lw I floating-point divide double div.d R store word sw I load word to floating-point single lwc1 I load halfword unsigned lhu I store word to floating-point single swc1 I store halfword sh I load word to floating-point double ldc1 I load byte unsigned lbu I store word to floating-point double sdc1 I store byte sb I branch on floating-point true bc1t I load linked (atomic update) ll I branch on floating-point false bc1f I store cond. (atomic update) sc I floating-point compare single c.x.s R branch on equal beq I (x = eq, neq, lt, le, gt, ge) branch on not equal bne I floating-point compare double c.x.d R jump j J (x = eq, neq, lt, le, gt, ge) jump and link jal J jump register jr R set less than slt R set less than immediate slti I set less than unsigned sltu R set less than immediate unsigned sltiu I FIGURE 3.24 The MIPS instruction set. This book concentrates on the instructions in the left column. This information is also found in columns 1 and 2 of the MIPS Reference Data Card at the front of this book. In April 1997, another floating-point bug was revealed in the Pentium Pro and Pentium II microprocessors. When the floating-point-to-integer store instructions (fist, fistp) encounter a negative floating-point number that is too large to fit in a 16- or 32-bit word after being converted to integer, they set the wrong bit in the FPO status word (precision exception instead of invalid operation exception). To Intel’s credit, this time they publicly acknowledged the bug and offered a software patch to get around it—quite a different reaction from what they did in 1994. 3.8 Fallacies and Pitfalls 279
clipped_hennesy_Page_277_Chunk5634
280 Chapter 3 Arithmetic for Computers 3.9 Concluding Remarks A side effect of the stored-program computer is that bit patterns have no inherent meaning. The same bit pattern may represent a signed integer, unsigned integer, floating-point number, instruction, and so on. It is the instruction that operates on the word that determines its meaning. Computer arithmetic is distinguished from paper-and-pencil arithmetic by the constraints of limited precision. This limit may result in invalid operations through calculating numbers larger or smaller than the predefined limits. Such anomalies, called “overflow” or “underflow,” may result in exceptions or interrupts, emergency events similar to unplanned subroutine calls. Chapter 4 discusses exceptions in more detail. Floating-point arithmetic has the added challenge of being an approximation of real numbers, and care needs to be taken to ensure that the computer num- ber selected is the representation closest to the actual number. The challenges of imprecision and limited representation are part of the inspiration for the field of numerical analysis. The recent switch to parallelism will shine the searchlight on numerical analysis again, as solutions that were long considered safe on sequential computers must be reconsidered when trying to find the fastest algorithm for par- allel computers that still achieves a correct result. Over the years, computer arithmetic has become largely standardized, greatly enhancing the portability of programs. Two’s complement binary integer arithme- tic and IEEE 754 binary floating-point arithmetic are found in the vast majority of computers sold today. For example, every desktop computer sold since this book was first printed follows these conventions. With the explanation of computer arithmetic in this chapter comes a description of much more of the MIPS instruction set. One point of confusion is the instructions covered in these chapters versus instructions executed by MIPS chips versus the instructions accepted by MIPS assemblers. Two figures try to make this clear. Figure 3.24 lists the MIPS instructions covered in this chapter and Chapter 2. We call the set of instructions on the left-hand side of the figure the MIPS core. The instructions on the right we call the MIPS arithmetic core. On the left of Figure 3.25 are the instructions the MIPS processor executes that are not found in Figure 3.24. We call the full set of hardware instructions MIPS-32. On the right of Figure 3.25 are the instructions accepted by the assembler that are not part of MIPS-32. We call this set of instructions Pseudo MIPS. Figure 3.26 gives the popularity of the MIPS instructions for SPEC CPU2006 integer and floating-point benchmarks. All instructions are listed that were responsible for at least 0.2% of the instructions executed. Note that although programmers and compiler writers may use MIPS-32 to have a richer menu of options, MIPS core instructions dominate integer SPEC
clipped_hennesy_Page_278_Chunk5635
Remaining MIPS-32 Name Format Pseudo MIPS Name Format exclusive or (rs ⊕ rt) xor R absolute value abs rd,rs exclusive or immediate xori I negate (signed or unsigned) negs rd,rs shift right arithmetic sra R rotate left rol rd,rs,rt shift left logical variable sllv R rotate right ror rd,rs,rt shift right logical variable srlv R multiply and don’t check oflw (signed or uns.) muls rd,rs,rt shift right arithmetic variable srav R multiply and check oflw (signed or uns.) mulos rd,rs,rt move to Hi mthi R divide and check overflow div rd,rs,rt move to Lo mtlo R divide and don’t check overflow divu rd,rs,rt load halfword lh I remainder (signed or unsigned) rems rd,rs,rt load byte lb I load immediate li rd,imm load word left (unaligned) lwl I load address la rd,addr load word right (unaligned) lwr I load double ld rd,addr store word left (unaligned) swl I store double sd rd,addr store word right (unaligned) swr I unaligned load word ulw rd,addr load linked (atomic update) ll I unaligned store word usw rd,addr store cond. (atomic update) sc I unaligned load halfword (signed or uns.) ulhs rd,addr move if zero movz R unaligned store halfword ush rd,addr move if not zero movn R branch b Label multiply and add (S or uns.) madds R branch on equal zero beqz rs,L multiply and subtract (S or uns.) msubs I branch on compare (signed or unsigned) bxs rs,rt,L branch on ≥ zero and link bgezal I (x = lt, le, gt, ge) branch on < zero and link bltzal I set equal seq rd,rs,rt jump and link register jalr R set not equal sne rd,rs,rt branch compare to zero bxz I set on compare (signed or unsigned) sxs rd,rs,rt branch compare to zero likely bxzl I (x = lt, le, gt, ge) (x = lt, le, gt, ge) load to floating point (s or d) l.f rd,addr branch compare reg likely bxl I store from floating point (s or d) s.f rd,addr trap if compare reg tx R trap if compare immediate txi I (x = eq, neq, lt, le, gt, ge) return from exception rfe R system call syscall I break (cause exception) break I move from FP to integer mfc1 R move to FP from integer mtc1 R FP move (s or d) mov.f R FP move if zero (s or d) movz.f R FP move if not zero (s or d) movn.f R FP square root (s or d) sqrt.f R FP absolute value (s or d) abs.f R FP negate (s or d) neg.f R FP convert (w, s, or d) cvt.f.f R FP compare un (s or d) c.xn.f R FIGURE 3.25 Remaining MIPS-32 and Pseudo MIPS instruction sets. f means single (s) or double (d) precision floating-point instructions, and s means signed and unsigned (u) versions. MIPS-32 also has FP instructions for multiply and add/sub (madd.f/msub.f ), ceiling (ceil.f ), truncate (trunc.f ), round (round.f ), and reciprocal (recip.f ). The underscore represents the letter to include to represent that datatype. 3.9 Concluding Remarks 281
clipped_hennesy_Page_279_Chunk5636
282 Chapter 3 Arithmetic for Computers Core MIPS Name Integer Fl. pt. Arithmetic core + MIPS-32 Name Integer Fl. pt. add add 0.0% 0.0% FP add double add.d 0.0% 10.6% add immediate addi 0.0% 0.0% FP subtract double sub.d 0.0% 4.9% add unsigned addu 5.2% 3.5% FP multiply double mul.d 0.0% 15.0% add immediate unsigned addiu 9.0% 7.2% FP divide double div.d 0.0% 0.2% subtract unsigned subu 2.2% 0.6% FP add single add.s 0.0% 1.5% AND AND 0.2% 0.1% FP subtract single sub.s 0.0% 1.8% AND immediate ANDi 0.7% 0.2% FP multiply single mul.s 0.0% 2.4% OR OR 4.0% 1.2% FP divide single div.s 0.0% 0.2% OR immediate ORi 1.0% 0.2% load word to FP double l.d 0.0% 17.5% NOR NOR 0.4% 0.2% store word to FP double s.d 0.0% 4.9% shift left logical sll 4.4% 1.9% load word to FP single l.s 0.0% 4.2% shift right logical srl 1.1% 0.5% store word to FP single s.s 0.0% 1.1% load upper immediate lui 3.3% 0.5% branch on floating-point true bc1t 0.0% 0.2% load word lw 18.6% 5.8% branch on floating-point false bc1f 0.0% 0.2% store word sw 7.6% 2.0% floating-point compare double c.x.d 0.0% 0.6% load byte lbu 3.7% 0.1% multiply mul 0.0% 0.2% store byte sb 0.6% 0.0% shift right arithmetic sra 0.5% 0.3% branch on equal (zero) beq 8.6% 2.2% load half lhu 1.3% 0.0% branch on not equal (zero) bne 8.4% 1.4% store half sh 0.1% 0.0% jump and link jal 0.7% 0.2% jump register jr 1.1% 0.2% set less than slt 9.9% 2.3% set less than immediate slti 3.1% 0.3% set less than unsigned sltu 3.4% 0.8% set less than imm. uns. sltiu 1.1% 0.1% FIGURE 3.26 The frequency of the MIPS instructions for SPEC CPU2006 integer and floating point. All instructions that accounted for at least 0.2% of the instructions are included in the table. Pseudoinstructions are converted into MIPS-32 before execution, and hence do not appear here. CPU2006 execution, and the integer core plus arithmetic core dominate SPEC CPU2006 floating point, as the table below shows. Instruction subset Integer Fl. pt. MIPS core 98% 31% MIPS arithmetic core 2% 66% Remaining MIPS-32 0% 3% For the rest of the book, we concentrate on the MIPS core instructions—the integer instruction set excluding multiply and divide—to make the explanation of computer design easier. As you can see, the MIPS core includes the most popu- lar MIPS instructions; be assured that understanding a computer that runs the MIPS core will give you sufficient background to understand even more ambitious ­computers.
clipped_hennesy_Page_280_Chunk5637
Historical Perspective and Further Reading This section surveys the history of the floating point going back to von Neumann, including the surprisingly controversial IEEE standards effort, plus the rationale for the 80-bit stack architecture for floating point in the x86. See Section 3.10. 3.11 Exercises Contributed by Matthew Farrens, UC Davis Exercise 3.1 The book shows how to add and subtract binary and decimal numbers. However, other numbering systems are also very popular when dealing with computers. The octal (base 8) numbering system is one of these. The following table shows pairs of octal numbers. A B a. 3174 0522 b. 4165 1654 3.1.1 [5] <3.2> What is the sum of A and B if they represent unsigned 12-bit octal numbers? The result should be written in octal. Show your work. 3.1.2 [5] <3.2> What is the sum of A and B if they represent signed 12-bit octal numbers stored in sign-magnitude format? The result should be written in octal. Show your work. 3.1.3 [10] <3.2> Convert A into a decimal number, assuming it is unsigned. ­Repeat assuming it stored in sign-magnitude format. Show your work. The following table also shows pairs of octal numbers. A B a. 7040 0444 b. 4365 3412 3.10 Gresham’s Law (“Bad money drives out Good”) for computers would say, “The Fast drives out the Slow even if the Fast is wrong.” W. Kahan, 1992 Never give in, never give in, never, never, never—in nothing, great or small, large or petty—never give in. Winston Churchill, address at Harrow School, 1941 3.11 Exercises 283
clipped_hennesy_Page_281_Chunk5638
284 Chapter 3 Arithmetic for Computers 3.1.4 [5] <3.2> What is A – B if they represent unsigned 12-bit octal numbers? The result should be written in octal. Show your work. 3.1.5 [5] <3.2> What is A – B if they represent signed 12-bit octal numbers stored in sign-magnitude format? The result should be written in octal. Show your work. 3.1.6 [10] <3.2> Convert A into a binary number. What makes base 8 (octal) an attractive numbering system for representing values in computers? Exercise 3.2 Hexadecimal (base 16) is also a commonly used numbering system for represent- ing values in computers. In fact, it has become much more popular than octal. The following table shows pairs of hexadecimal numbers. A B a. 1446 672F b. 2460 4935 3.2.1 [5] <3.2> What is the sum of A and B if they represent unsigned 16-bit hexadecimal numbers? The result should be written in hexadecimal. Show your work. 3.2.2 [5] <3.2> What is the sum of A and B if they represent signed 16-bit hexa- decimal numbers stored in sign-magnitude format? The result should be written in hexadecimal. Show your work. 3.2.3 [10] <3.2> Convert A into a decimal number, assuming it is unsigned. ­Repeat assuming it stored in sign-magnitude format. Show your work. The following table also shows pairs of hexadecimal numbers. A B a. C352 36AE b. 5ED4 07A4 3.2.4 [5] <3.2> What is A – B if they represent unsigned 16-bit hexadecimal numbers? The result should be written in hexadecimal. Show your work.
clipped_hennesy_Page_282_Chunk5639
3.2.5 [5] <3.2> What is A – B if they represent signed 16-bit hexadecimal ­numbers stored in sign-magnitude format? The result should be written in hexa- decimal. Show your work. 3.2.6 [10] <3.2> Convert A into a binary number. What makes base 16 (hexa- decimal) an attractive numbering system for representing values in computers? Exercise 3.3 Overflow occurs when a result is too large to be represented accurately given a finite word size. Underflow occurs when a number is too small to be represented correctly—a negative result when doing unsigned arithmetic, for example. (The case when a positive result is generated by the addition of two negative integers is also referred to as underflow by many, but in this textbook, that is considered an overflow.) The following table shows pairs of decimal numbers. A B a. 216 255 b. 185 122 3.3.1 [5] <3.2> Assume A and B are unsigned 8-bit decimal integers. Calculate A – B. Is there overflow, underflow, or neither? 3.3.2 [5] <3.2> Assume A and B are signed 8-bit decimal integers stored in sign- magnitude format. Calculate A + B. Is there overflow, underflow, or neither? 3.3.3 [5] <3.2> Assume A and B are signed 8-bit decimal integers stored in sign- magnitude format. Calculate A – B. Is there overflow, underflow, or neither? The following table also shows pairs of decimal numbers. A B a. 15 139 b. 151 214 3.3.4 [10] <3.2> Assume A and B are signed 8-bit decimal integers stored in two’s complement format. Calculate A + B using saturating arithmetic. The result should be written in decimal. Show your work. 3.3.5 [10] <3.2> Assume A and B are signed 8-bit decimal integers stored in two’s complement format. Calculate A – B using saturating arithmetic. The result should be written in decimal. Show your work. 3.11 Exercises 285
clipped_hennesy_Page_283_Chunk5640
286 Chapter 3 Arithmetic for Computers 3.3.6 [10] <3.2> Assume A and B are unsigned 8-bit integers. Calculate A + B using saturating arithmetic. The result should be written in decimal. Show your work. Exercise 3.4 Let’s look in more detail at multiplication. We will use the numbers in the follow- ing table. A B a. 62 12 b. 35 26 3.4.1 [20] <3.3> Using a table similar to that shown in Figure 3.7, calculate the product of the octal unsigned 6-bit integers A and B using the hardware described in Figure 3.4. You should show the contents of each register on each step. 3.4.2 [20] <3.3> Using a table similar to that shown in Figure 3.7, calculate the product of the hexadecimal unsigned 8-bit integers A and B using the hardware described in Figure 3.6. You should show the contents of each register on each step. 3.4.3 [60] <3.3> Write an MIPS assembly language program to calculate the product of unsigned integers A and B, using the approach described in Figure 3.4. The following table shows pairs of octal numbers. A B a. 41 33 b. 60 26 3.4.4 [30] <3.3> When multiplying signed numbers, one way to get the correct answer is to convert the multiplier and multiplicand to positive numbers, save the original signs, and then adjust the final value accordingly. Using a table similar to that shown in Figure 3.7, calculate the product of A and B using the hardware ­described in Figure 3.4. You should show the contents of each register on each step, and include the step necessary to produce the correctly signed result. Assume A and B are stored in 6-bit sign-magnitude format. 3.4.5 [30] <3.3> When shifting a register one bit to the right, there are several ways to decide what the new entering bit should be. It can always be a zero, or always a one, or the incoming bit could be the one that is being pushed out of the
clipped_hennesy_Page_284_Chunk5641
right side (turning a shift into a rotate), or the value that is already in the leftmost bit can simply be retained (called an arithmetic shift right, because it preserves the sign of the number that is being shift). Using a table similar to that shown in Figure 3.7, calculate the product of the 6-bit two’s complement numbers A and B using the hardware described in Figure 3.6. The right shifts should be done using an arithmetic shift right. Note that the algorithm described in the text will need to be modified slightly to make this work—in particular, things must be done differ- ently if the multiplier is negative. You can find details by searching the web. Show the contents of each register on each step. 3.4.6 [60] <3.3> Write an MIPS assembly language program to calculate the product of the signed integers A and B. State if you are using the approach given in 3.4.4 or 3.4.5. Exercise 3.5 For many reasons, we would like to design multipliers that require less time. Many different approaches have been taken to accomplish this goal. In the following ­table, A represents the bit width of an integer, and B represents the number of time units (tu) taken to perform a step of an operation. A (bit width) B (time units) a. 8 4tu b. 64 8tu 3.5.1 [10] <3.3> Calculate the time necessary to perform a multiply using the approach given in Figures 3.4 and 3.5 if an integer is A bits wide and each step of the operation takes B time units. Assume that in step 1a an addition is always ­performed—either the multiplicand will be added, or a zero will be. Also assume that the registers have already been initialized (you are just counting how long it takes to do the multiplication loop itself). If this is being done in hardware, the shifts of the multiplicand and multiplier can be done simultaneously. If this is being done in software, they will have to be done one after the other. Solve for each case. 3.5.2 [10] <3.3> Calculate the time necessary to perform a multiply using the approach described in the text (31 adders stacked vertically) if an integer is A bits wide and an adder takes B time units. 3.5.3 [20] <3.3> Calculate the time necessary to perform a multiply using the approach given in Figure 3.8 if an integer is A bits wide and an adder takes B time units. 3.11 Exercises 287
clipped_hennesy_Page_285_Chunk5642
288 Chapter 3 Arithmetic for Computers Exercise 3.6 In this exercise we will look at a couple of other ways to improve the performance of multiplication, based primarily on doing more shifts and fewer arithmetic ­operations. The following table shows pairs of hexadecimal numbers. A B a. 33 55 b. 8a 6d 3.6.1 [20] <3.3> As discussed in the text, one possible performance enhancement is to do a shift and add instead of an actual multiplication. Since 9 × 6, for example, can be written (2 × 2 × 2 + 1) × 6, we can calculate 9 × 6 by shifting 6 to the left 3 times and then adding 6 to that result. Show the best way to calculate A × B using shifts and adds/subtracts. Assume that A and B are 8-bit unsigned integers. 3.6.2 [20] <3.3> Show the best way to calculate A × B using shifts and add, if A and B are 8-bit signed integers stored in sign-magnitude format. 3.6.3 [60] <3.3> Write an MIPS assembly language program that performs a mul- tiplication on signed integers using shifts and adds, using the approach ­described in 3.6.1. The following table shows further pairs of hexadecimal numbers. A B a. F6 7F b. 08 55 3.6.4 [30] <3.3> Booth’s algorithm is another approach to reducing the number of arithmetic operations necessary to perform a multiplication. This algorithm has been around for years and involves identifying runs of ones and zeros and per- forming only shifts instead of shifts and adds during the runs. Find a description of the algorithm on the web and explain in detail how it works. 3.6.5 [30] <3.3> Show the step-by-step result of multiplying A and B, using Booth’s algorithm. Assume A and B are 8-bit two’s complement integers, stored in hexadecimal format. 3.6.6 [60] <3.3> Write an MIPS assembly language program to perform the mul- tiplication of A and B using Booth’s algorithm.
clipped_hennesy_Page_286_Chunk5643
Exercise 3.7 Let’s look in more detail at division. We will use the octal numbers in the following table. A B a. 74 21 b. 76 52 3.7.1 [20] <3.4> Using a table similar to that shown in Figure 3.11, calculate A divided by B using the hardware described in Figure 3.9. You should show the con- tents of each register on each step. Assume A and B are unsigned 6-bit integers. 3.7.2 [30] <3.4> Using a table similar to that shown in Figure 3.11, calculate A divided by B using the hardware described in Figure 3.12. You should show the con- tents of each register on each step. Assume A and B are unsigned 6-bit integers. This algorithm requires a slightly different approach than that shown in Figure 3.10. You will want to think hard about this, do an experiment or two, or else go to the web to figure out how to make this work correctly. (Hint: one possible solution involves using the fact that Figure 3.12 implies the remainder register can be shifted either direction.) 3.7.3 [60] <3.4> Write an MIPS assembly language program to calculate A divided by B, using the approach described in Figure 3.9. Assume A and B are unsigned 6-bit integers. The following table shows further pairs of octal numbers. A B a. 72 07 b. 75 47 3.7.4 [30] <3.4> Using a table similar to that shown in Figure 3.11, calculate A divided by B using the hardware described in Figure 3.9. You should show the con- tents of each register on each step. Assume A and B are 6-bit signed integers in sign-magnitude format. Be sure to include how you are calculating the signs of the quotient and remainder. 3.7.5 [30] <3.4> Using a table similar to that shown in Figure 3.11, calculate A divided by B using the hardware described in Figure 3.12. You should show the contents of each register on each step. Assume A and B are 6-bit signed integers in sign-magnitude format. Be sure to include how you are calculating the signs of the quotient and remainder. 3.11 Exercises 289
clipped_hennesy_Page_287_Chunk5644
290 Chapter 3 Arithmetic for Computers 3.7.6 [60] <3.4> Write an MIPS assembly language program to calculate A ­divided by B, using the approach described in Figure 3.12. Assume A and B are signed integers. Exercise 3.8 Figure 3.10 describes a restoring division algorithm, because when subtracting the divisor from the remainder produces a negative result, the divisor is added back to the remainder (thus restoring the value). However, there are other algorithms that have been developed that eliminate the extra addition. Many references to these algorithms are easily found on the web. We will explore these algorithms using the pairs of octal numbers in the following table. A B a. 26 05 b. 37 15 3.8.1 [30] <3.4> Using a table similar to that shown in Figure 3.11, calculate A divided by B using non-restoring division. You should show the contents of each register on each step. Assume A and B are 6-bit unsigned integers. 3.8.2 [60] <3.4> Write an MIPS assembly language program to calculate A ­divided by B using non-restoring division. Assume A and B are 6-bit signed (two’s complement) integers. 3.8.3 [60] <3.4> How does the performance of restoring and non-restoring division compare? Demonstrate by showing the number of steps necessary to calculate A divided by B using each method. Assume A and B are 6-bit signed (sign-­magnitude) integers. Writing a program to perform the restoring and non-­ restoring divisions is acceptable. The following table shows further pairs of octal numbers. A B a. 27 06 b. 54 12 3.8.4 [30] <3.4> Using a table similar to that shown in Figure 3.11, calculate A divided by B using non-performing division. You should show the contents of each register on each step. Assume A and B are 6-bit unsigned integers.
clipped_hennesy_Page_288_Chunk5645
3.8.5 [60] <3.4> Write an MIPS assembly language program to calculate A ­divided by B using nonperforming division. Assume A and B are 6-bit two’s com- plement signed integers. 3.8.6 [60] <3.4> How does the performance of non-restoring and nonperform- ing division compare? Demonstrate by showing the number of steps necessary to calculate A divided by B using each method. Assume A and B are signed 6-bit inte- gers, stored in sign-magnitude format. Writing a program to perform the nonper- forming and non-restoring divisions is acceptable. Exercise 3.9 Division is so time-consuming and difficult that the CRAY T3E Fortran Optimiza- tion guide states, “The best strategy for division is to avoid it whenever possible.” This exercise looks at the following different strategies for performing divisions. a. non-restoring division b. division by reciprocal multiplication 3.9.1 [30] <3.4> Describe the algorithm in detail. 3.9.2 [60] <3.4> Use a flow chart (or a high-level code snippet) to describe how the algorithm works. 3.9.3 [60] <3.4> Write an MIPS assembly language program to perform division using the algorithm. Exercise 3.10 In a Von Neumann architecture, groups of bits have no intrinsic meanings by themselves. What a bit pattern represents depends entirely on how it is used. The following table shows bit patterns expressed in hexademical notation. a. 0x0C000000 b. 0xC4630000 3.10.1 [5] <3.5> What decimal number does the bit pattern represent if it is a two’s complement integer? An unsigned integer? 3.10.2 [10] <3.5> If this bit pattern is placed into the Instruction Register, what MIPS instruction will be executed? 3.11 Exercises 291
clipped_hennesy_Page_289_Chunk5646
292 Chapter 3 Arithmetic for Computers 3.10.3 [10] <3.5> What decimal number does the bit pattern represent if it is a floating point number? Use the IEEE 754 standard. The following table shows decimal numbers. a. 63.25 b. 146987.40625 3.10.4 [10] <3.5> Write down the binary representation of the decimal number, assuming the IEEE 754 single precision format. 3.10.5 [10] <3.5> Write down the binary representation of the decimal number, assuming the IEEE 754 double precision format. 3.10.6 [10] <3.5> Write down the binary representation of the decimal number assuming it was stored using the single precision IBM format (base 16, instead of base 2, with 7 bits of exponent). Exercise 3.11 In the IEEE 754 floating point standard the exponent is stored in “bias” (also known as “Excess-N”) format. This approach was selected because we want an all-zero pattern to be as close to zero as possible. Because of the use of a hidden 1, if we were to represent the exponent in two’s complement format an all-zero pattern would actually be the number 1! (Remember, anything raised to the zeroth power is 1, so 1.00 = 1.) There are many other aspects of the IEEE 754 standard that exist in order to help hardware floating point units work more quickly. However, in many older machines floating point calculations were handled in software, and therefore other formats were used. The following table shows decimal numbers. a. –1.5625 × 10–1 b. 9.356875 × 102 3.11.1 [20] <3.5> Write down the binary bit pattern assuming a format similar to that employed by the DEC PDP-8 (the leftmost 12 bits are the exponent stored as a two’s complement number, and the rightmost 24 bits are the mantissa stored as a two’s complement number ). No hidden 1 is used. Comment on how the range and accuracy of this 36-bit pattern compares to the single and double precision IEEE 754 standards. 3.11.2 [20] <3.5> NVIDIA has a “half” format, which is similar to IEEE 754 ­except that it is only 16 bits wide. The leftmost bit is still the sign bit, the exponent is 5 bits wide and stored in excess-56 format, and the mantissa is 10 bits long.
clipped_hennesy_Page_290_Chunk5647
A hidden 1 is assumed. Write down the bit pattern assuming a modified version of this format, which uses an excess-16 format to store the exponent. Comment on how the range and accuracy of this 16-bit floating point format compares to the single precision IEEE 754 standard. 3.11.3 [20] <3.5> The Hewlett-Packard 2114, 2115, and 2116 used a format with the leftmost 16 bits being the mantissa stored in two’s complement format, followed by another 16-bit field which had the leftmost 8 bits as an extension of the mantissa (making the mantissa 24 bits long), and the rightmost 8 bits repre- senting the exponent. However, in an interesting twist, the exponent was stored in sign-magnitude format with the sign bit on the far right! Write down the bit pat- tern ­assuming this format. No hidden 1 is used. Comment on how the range and ­accuracy of this 32-bit pattern compares to the single precision IEEE 754 standard. The following table shows pairs of decimal numbers. A B a. 2.6125 × 101 4.150390625 × 10–1 b. –4.484375 × 101 1.3953125 × 101 3.11.4 [20] <3.5> Calculate the sum of A and B by hand, assuming A and B are stored in the modified 16-bit NVIDIA format described in 3.11.2. Assume 1 guard, 1 round bit, and 1 sticky bit, and round to the nearest even. Show all the steps. 3.11.5 [60] <3.5> Write an MIPS assembly language program to calculate the sum of A and B, assuming they are stored in the modified 16-bit NVIDIA format described in 3.11.2. Assume 1 guard, 1 round bit, and 1 sticky bit, and round to the nearest even. 3.11.6 [60] <3.5> Write an MIPS assembly language program to calculate the sum of A and B, assuming they are stored using the format described in 3.11.1. Now modify the program to calculate the sum assuming the format described in 3.11.3. Which format is easier for a programmer to deal with? How do they each compare to the IEEE 754 format? (Do not worry about sticky bits for this question.) Exercise 3.12 Floating point multiplication is even more complicated and challenging than float- ing point addition, and both pale in comparison to floating point division. The following table shows pairs of decimal numbers. 3.11 Exercises 293
clipped_hennesy_Page_291_Chunk5648
294 Chapter 3 Arithmetic for Computers A B a. –8.0546875 × 100 –1.79931640625 × 10–1 b. 8.59375 × 10–2 8.125 × 10–1 3.12.1 [30] <3.5> Calculate the product of A and B by hand, assuming A and B are stored in the modified 16-bit NVIDIA format described in 3.11.2. Assume 1 guard, 1 round bit, and 1 sticky bit, and round to the nearest even. Show all the steps; however, as is done in the example in the text, you can do the multiplication in human-readable format instead of using the techniques described in Exercises 3.4 through 3.6. Indicate if there is overflow or underflow. Write your answer as a 16-bit pattern, and also as a decimal number. How accurate is your result? How does it compare to the number you get if you do the multiplication on a calculator? 3.12.2 [60] <3.5> Write an MIPS assembly language program to calculate the product of A and B, assuming they are stored in IEEE 754 format. Indicate if there is overflow or underflow. (Remember, IEEE 754 assumes 1 guard, 1 round bit, and 1 sticky bit, and rounds to the nearest even.) 3.12.3 [60] <3.5> Write an MIPS assembly language program to calculate the product of A and B, assuming they are stored using the format described in 3.11.1. Now modify the program to calculate the sum assuming the format described in 3.11.3. Which format is easier for a programmer to deal with? How do they each compare to the IEEE 754 format? (Do not worry about sticky bits for this ­question.) The following table shows further pairs of decimal numbers. A B a. 8.625 × 101 –4.875 × 100 b. 1.84375 × 100 1.3203125 × 100 3.12.4 [30] <3.5> Calculate by hand A divided by B. Show all the steps neces- sary to achieve your answer. Assume there is a guard, a round bit, and a sticky bit, and use them if necessary. Write the final answer in both the 16-bit floating point format described in 3.11.2 and in decimal and compare the decimal result to that which you get if you use a calculator. The Livermore Loops are a set of floating point–intensive kernels taken from ­scientific programs run at Lawrence Livermore Laboratory. The following table identifies individual kernels from the set. a. Livermore Loop 3 b. Livermore Loop 9
clipped_hennesy_Page_292_Chunk5649
3.12.5 [60] <3.5> Write the loop in MIPS assembly language. 3.12.6 [60] <3.5> Describe in detail one technique for performing floating point division in a digital computer. Be sure to include references to the sources you used. Exercise 3.13 Operations performed on fixed-point integers behave the way one expects—the commutative, associative, and distributive laws all hold. This is not always the case when working with floating point numbers, however. Let’s first look at the associa- tive law. The following table shows sets of decimal numbers. A B C a. 3.984375 × 10–1 3.4375 × 10–1 1.771 × 103 b. 3.96875 × 100 8.46875 × 100 2.1921875 × 101 3.13.1 [20] <3.2, 3.5, 3.6> Calculate (A + B) + C by hand, assuming A, B, and C are stored in the modified 16-bit NVIDIA format described in 3.11.2 (and also ­described in the text). Assume 1 guard, 1 round bit, and 1 sticky bit, and round to the nearest even. Show all the steps, and write your answer in both the 16-bit float- ing point format and in decimal. 3.13.2 [20] <3.2, 3.5, 3.6> Calculate A + (B + C) by hand, assuming A, B, and C are stored in the modified 16-bit NVIDIA format described in 3.11.2 (and also ­described in the text). Assume 1 guard, 1 round bit, and 1 sticky bit, and round to the nearest even. Show all the steps, and write your answer in both the 16-bit float- ing point format and in decimal. 3.13.3 [10] <3.2, 3.5, 3.6> Based on your answers to 3.13.1 and 3.13.2, does (A + B) + C = A + (B + C)? The following table shows further sets of decimal numbers. A B C a. 3.41796875 10–3 6.34765625 × 10–3 1.05625 × 102 b. 1.140625 × 102 –9.135 × 102 9.84375 × 10–1 3.13.4 [30] <3.3, 3.5, 3.6> Calculate (A × B) × C by hand, assuming A, B, and C are stored in the modified 16-bit NVIDIA format described in 3.11.2 (and also ­described in the text). Assume 1 guard, 1 round bit, and 1 sticky bit, and round to the nearest even. Show all the steps, and write your answer in both the 16-bit float- ing point format and in decimal. 3.11 Exercises 295
clipped_hennesy_Page_293_Chunk5650
296 Chapter 3 Arithmetic for Computers 3.13.5 [30] <3.3, 3.5, 3.6> Calculate A × (B × C) by hand, assuming A, B, and C are stored in the modified 16-bit NVIDIA format described in 3.11.2 (and also ­described in the text). Assume 1 guard, 1 round bit, and 1 sticky bit, and round to the nearest even. Show all the steps, and write your answer in both the 16-bit float- ing point format and in decimal. 3.13.6 [10] <3.3, 3.5, 3.6> Based on your answers to 3.13.4 and 3.13.5, does (A × B) × C = A × (B × C)? Exercise 3.14 The Associative law is not the only one that does not always hold in dealing with floating point numbers. There are other oddities that occur as well. The following table shows sets of decimal numbers. A B C a. 1.666015625 × 100 1.9760 × 104 –1.9744 × 104 b. 3.48 × 102 6.34765625 × 10–2 –4.052734375 × 10–2 3.14.1 [30] <3.2, 3.3, 3.5, 3.6> Calculate A × (B + C) by hand, assuming A, B, and C are stored in the modified 16-bit NVIDIA format described in 3.11.2 (and also described in the text). Assume 1 guard, 1 round bit, and 1 sticky bit, and round to the nearest even. Show all the steps, and write your answer in both the 16-bit float- ing point format and in decimal. 3.14.2 [30] <3.2, 3.3, 3.5, 3.6> Calculate (A × B) + (A × C) by hand, assuming A, B, and C are stored in the modified 16-bit NVIDIA format described in 3.11.2 (and also described in the text). Assume 1 guard, 1 round bit, and 1 sticky bit, and round to the nearest even. Show all the steps, and write your answer in both the 16-bit floating point format and in decimal. 3.14.3 [10] <3.2, 3.3, 3.5, 3.6> Based on your answers to 3.14.1. and 3.14.2, does (A × B) + (A × C) = A × (B + C)? The following table shows pairs, each consisting of a fraction and an integer. A B a. –1/4 4 b. 1/10 10 3.14.4 [10] <3.5> Using the IEEE 754 floating point format, write down the bit pattern that would represent A. Can you represent A exactly?
clipped_hennesy_Page_294_Chunk5651
3.14.5 [10] <3.2, 3.3, 3.5, 3.6> What do you get if you add A to itself B times? What is A × B? Are they the same? What should they be? 3.14.6 [60] <3.2, 3.3, 3.4, 3.5, 3.6> What do you get if you take the square root of B and then multiply that value by itself? What should you get? Do for both single and double precision floating point numbers. (Write a program to do these calculations.) Exercise 3.15 Binary numbers are used in the mantissa field, but they do not have to be. IBM used base 16 numbers, for example, in some of their floating point formats. There are other approaches that are possible as well, each with their own particular ­advantages and disadvantages. The following table shows fractions to be repre- sented in various floating point formats. a. 1/3 b. 1/10 3.15.1 [10] <3.5, 3.6> Write down the bit pattern in the mantissa assuming a floating point format that uses binary numbers in the mantissa (essentially what you have been doing in this chapter). Assume there are 24 bits, and you do not need to normalize. Is this representation exact? 3.15.2 [10] <3.5, 3.6> Write down the bit pattern in the mantissa assuming a floating point format that uses Binary Coded Decimal (base 10) numbers in the mantissa instead of base 2. Assume there are 24 bits, and you do not need to nor- malize. Is this representation exact? 3.15.3 [10] <3.5, 3.6> Write down the bit pattern assuming that we are using base 15 numbers in the mantissa instead of base 2. (Base 16 numbers use the sym- bols 0–9 and A–F. Base 15 numbers would use 0–9 and A–E.) Assume there are 24 bits, and you do not need to normalize. Is this representation exact? 3.15.4 [20] <3.5, 3.6> Write down the bit pattern assuming that we are using base 30 numbers in the mantissa instead of base 2. (Base 16 numbers use the sym- bols 0–9 and A–F. Base 30 numbers would use 0–9 and A–T.) Assume there are 20 bits, and you do not need to normalize. Is this representation exact? Do you see any advantage to using this approach? §3.2, page 229: 2. §3.5, page 269: 3. Answers to Check Yourself 3.11 Exercises 297
clipped_hennesy_Page_295_Chunk5652
4 In a major matter, no details are small. French Proverb The Processor 4.1 Introduction 300 4.2 Logic Design Conventions 303 4.3 Building a Datapath 307 4.4 A Simple Implementation Scheme 316 4.5 An Overview of Pipelining 330 4.6 Pipelined Datapath and Control 344 4.7 Data Hazards: Forwarding versus Stalling 363 4.8 Control Hazards 375 4.9 Exceptions 384 Computer Organization and Design. DOI: 10.1016/B978-0-12-374750-1.00004-9 © 2012 Elsevier, Inc. All rights reserved.
clipped_hennesy_Page_296_Chunk5653
4.10 Parallelism and Advanced Instruction-Level Parallelism 391 4.11 Real Stuff: the AMD Opteron X4 (Barcelona) Pipeline 404 4.12 Advanced Topic: an Introduction to Digital Design Using a Hardware Design Language to Describe and Model a Pipeline and More Pipelining Illustrations 406 4.13 Fallacies and Pitfalls 407 4.14 Concluding Remarks 408 4.15 Historical Perspective and Further Reading 409 4.16 Exercises 409 The Five Classic Components of a Computer
clipped_hennesy_Page_297_Chunk5654
300 Chapter 4 The Processor 4.1 Introduction Chapter 1 explains that the performance of a computer is determined by three key factors: instruction count, clock cycle time, and clock cycles per instruction (CPI). Chapter 2 explains that the compiler and the instruction set architec­ture determine the instruction count required for a given program. However, the implementation of the processor determines both the clock cycle time and the number of clock cycles per instruction. In this chapter, we construct the datapath and control unit for two different implementations of the MIPS instruction set. This chapter contains an explanation of the principles and techniques used in implementing a processor, starting with a highly abstract and simplified overview in this section. It is followed by a section that builds up a datapath and constructs a simple version of a processor sufficient to implement an instruction set like MIPS. The bulk of the chapter covers a more realistic pipelined MIPS implementation, followed by a section that develops the concepts necessary to implement more complex instruction sets, like the x86. For the reader interested in understanding the high-level interpretation of instructions and its impact on program performance, this initial section and Section 4.5 present the basic concepts of pipelining. Recent trends are covered in Section 4.10, and Section 4.11 describes the recent AMD Opteron X4 (Barcelona) microprocessor. These sections provide enough background to understand the pipeline concepts at a high level. For the reader interested in understanding the processor and its performance in more depth, Sections 4.3, 4.4, and 4.6 will be useful. Those interested in learn­ ing how to build a processor should also cover 4.2, 4.7, 4.8, and 4.9. For readers with an interest in modern hardware design, Section 4.12 on the CD describes how hardware design languages and CAD tools are used to implement hardware, and then how to use a hardware design language to describe a pipelined imple- mentation. It also gives several more illustrations of how pipelining hardware executes. A Basic MIPS Implementation We will be examining an implementation that includes a subset of the core MIPS instruction set: ■ ■The memory-reference instructions load word (lw) and store word (sw) ■ ■The arithmetic-logical instructions add, sub, AND, OR, and slt ■ ■The instructions branch equal (beq) and jump (j), which we add last
clipped_hennesy_Page_298_Chunk5655
4.1 Introduction 301 This subset does not include all the integer instructions (for example, shift, ­multiply, and divide are missing), nor does it include any floating-point instructions. How- ever, the key principles used in creating a datapath and designing the control are illustrated. The implementation of the remaining instructions is similar. In examining the implementation, we will have the opportunity to see how the instruction set architecture determines many aspects of the implementation, and how the choice of various implementation strategies affects the clock rate and CPI for the computer. Many of the key design principles introduced in Chapter 1 can be illustrated by looking at the implementation, such as the guidelines Make the com­mon case fast and Simplicity favors regularity. In addition, most concepts used to implement the MIPS subset in this chapter are the same basic ideas that are used to construct a broad spectrum of computers, from high-­performance servers to gen­eral-purpose microprocessors to embedded processors. An Overview of the Implementation In Chapter 2, we looked at the core MIPS instructions, including the inte­ger arithmetic-logical instructions, the memory-reference instructions, and the branch instructions. Much of what needs to be done to implement these instruc­tions is the same, independent of the exact class of instruction. For every instruc­tion, the first two steps are identical: 1. Send the program counter (PC) to the memory that contains the code and fetch the instruction from that memory. 2. Read one or two registers, using fields of the instruction to select the registers to read. For the load word instruction, we need to read only one regis­ter, but most other instructions require that we read two registers. After these two steps, the actions required to complete the instruction depend on the instruction class. Fortunately, for each of the three instruction classes (memory-reference, arithmetic-logical, and branches), the actions are largely the same, independent of the exact instruction. The simplicity and regularity of the MIPS instruction set simplifies the implementation by making the execution of many of the instruction classes similar. For example, all instruction classes, except jump, use the arithmetic-logical unit (ALU) after reading the registers. The memory-reference instructions use the ALU for an address calculation, the arithmetic-logical instructions for the opera­tion execution, and branches for comparison. After using the ALU, the actions required to complete various instruction classes differ. A memory-reference instruction will need to access the memory either to read data for a load or write data for a store. An arithmetic-logical or load instruction must write the data from the ALU or memory back into a register. Lastly, for a branch instruction, we may need to change the next instruction address based on the comparison; other­wise, the PC should be incremented by 4 to get the address of the next instruction.
clipped_hennesy_Page_299_Chunk5656
302 Chapter 4 The Processor Figure 4.1 shows the high-level view of a MIPS implementation, focusing on the various functional units and their interconnection. Although this figure shows most of the flow of data through the processor, it omits two important aspects of instruction execution. FIGURE 4.1 An abstract view of the implementation of the MIPS subset showing the major functional units and the major connections between them. All instructions start by using the pro­gram counter to supply the instruction address to the instruction memory. After the instruction is fetched, the register operands used by an instruction are specified by fields of that instruction. Once the register operands have been fetched, they can be operated on to compute a memory address (for a load or store), to compute an arithmetic result (for an integer arithmetic-logical instruction), or a compare (for a branch). If the instruction is an arithmetic-logical instruction, the result from the ALU must be written to a register. If the operation is a load or store, the ALU result is used as an address to either store a value from the registers or load a value from memory into the registers. The result from the ALU or memory is written back into the register file. Branches require the use of the ALU output to determine the next instruction address, which comes either from the ALU (where the PC and branch offset are summed) or from an adder that increments the current PC by 4. The thick lines interconnecting the functional units represent buses, which consist of multiple signals. The arrows are used to guide the reader in knowing how information flows. Since signal lines may cross, we explicitly show when crossing lines are connected by the presence of a dot where the lines cross. Data PC Address Instruction Instruction memory Registers ALU Address Data Data memory Add Add 4 Register # Register # Register # First, in several places, Figure 4.1 shows data going to a particular unit as coming from two different sources. For example, the value written into the PC can come from one of two adders, the data written into the register file can come from either the ALU or the data memory, and the second input to the ALU can come from a register or the immediate field of the instruction. In practice, these data lines can­not simply be wired together; we must add a logic element that chooses from among the multiple sources and steers one of those sources to its destination. This selection is commonly done with a device called a multiplexor, although this device
clipped_hennesy_Page_300_Chunk5657
might better be called a data selector. Appendix C describes the multi­plexor, which selects from among several inputs based on the setting of its con­trol lines. The control lines are set based primarily on information taken from the instruction being executed. The second omission in Figure 4.1 is that several of the units must be con­trolled depending on the type of instruction. For example, the data memory must read on a load and write on a store. The register file must be written on a load and an arithmetic-logical instruction. And, of course, the ALU must perform one of several operations, as we saw in Chapter 2. ( Appendix C describes the detailed design of the ALU.) Like the multiplexors, these operations are directed by control lines that are set on the basis of various fields in the instruction. Figure 4.2 shows the datapath of Figure 4.1 with the three required multiplexors added, as well as control lines for the major functional units. A control unit, which has the instruction as an input, is used to determine how to set the control lines for the functional units and two of the multiplexors. The third multiplexor, which determines whether PC + 4 or the branch destination address is written into the PC, is set based on the Zero output of the ALU, which is used to perform the comparison of a beq instruction. The regularity and simplicity of the MIPS instruction set means that a simple decoding process can be used to determine how to set the control lines. In the remainder of the chapter, we refine this view to fill in the details, which requires that we add further functional units, increase the number of connections between units, and, of course, enhance a control unit to control what actions are taken for different instruction classes. Sections 4.3 and 4.4 describe a simple imple- mentation that uses a single long clock cycle for every instruction and follows the gen­eral form of Figures 4.1 and 4.2. In this first design, every instruction begins execution on one clock edge and completes execution on the next clock edge. While easier to understand, this approach is not practical, since the clock cycle must be stretched to accommodate the longest instruction. After designing the control for this simple computer, we will look at pipelined implementation with all its complexities, including exceptions. How many of the five classic components of a computer—shown on page 299—do Figures 4.1 and 4.2 include? 4.2 Logic Design Conventions To discuss the design of a computer, we must decide how the logic implementing the computer will operate and how the computer is clocked. This section reviews a few key ideas in digital logic that we will use extensively in this chapter. If Check Yourself 4.2 Logic Design Conventions 303
clipped_hennesy_Page_301_Chunk5658
304 Chapter 4 The Processor you have little or no background in digital logic, you will find it helpful to read Appendix C before continuing. The datapath elements in the MIPS implementation consist of two different types of logic elements: elements that operate on data values and elements that contain state. The elements that operate on data values are all combina­tional, which means that their outputs depend only on the current inputs. ­Given the same input, a combinational element always produces the same output. The ALU shown in Figure 4.1 and discussed in Appendix C is an example of a combina­tional combinational element An operational element, such as an AND gate or an ALU. FIGURE 4.2 The basic implementation of the MIPS subset, including the necessary multiplexors and control lines. The top multiplexor (“Mux”) controls what value replaces the PC (PC + 4 or the branch destination address); the multi­plexor is controlled by the gate that “ANDs” together the Zero output of the ALU and a control signal that indicates that the instruc­tion is a branch. The middle multiplexor, whose output returns to the register file, is used to steer the output of the ALU (in the case of an arithmetic-logical instruction) or the output of the data memory (in the case of a load) for writing into the register file. Finally, the bottommost multiplexor is used to determine whether the second ALU input is from the registers (for an arithmetic-logical instruction OR a branch) or from the offset field of the instruction (for a load or store). The added control lines are straightforward and determine the operation performed at the ALU, whether the data memory should read or write, and whether the registers should perform a write operation. The control lines are shown in color to make them easier to see. Data PC Address Instruction Instruction memory Registers ALU Address Data Data memory Add Add 4 MemWrite MemRead M u x M u x M u x Control RegWrite Zero Branch ALU operation Register # Register # Register #
clipped_hennesy_Page_302_Chunk5659
element. Given a set of inputs, it always produces the same output because it has no internal storage. Other elements in the design are not combinational, but instead contain state. An element contains state if it has some internal storage. We call these elements state elements because, if we pulled the power plug on the computer, we could restart it by loading the state elements with the values they contained before we pulled the plug. Furthermore, if we saved and restored the state elements, it would be as if the computer had never lost power. Thus, these state elements completely characterize the computer. In Figure 4.1, the instruction and data memories, as well as the registers, are all examples of state elements. A state element has at least two inputs and one output. The required inputs are the data value to be written into the element and the clock, which determines when the data value is written. The output from a state element provides the value that was written in an earlier clock cycle. For example, one of the logically sim­plest state elements is a D-type flip-flop (see Appendix C), which has exactly these two inputs (a value and a clock) and one output. In addition to flip-flops, our MIPS implementation also uses two other types of state elements: memories and registers, both of which appear in Figure 4.1. The clock is used to determine when the state element should be written; a state ­element can be read at any time. Logic components that contain state are also called sequential, because their outputs depend on both their inputs and the contents of the internal state. For example, the output from the functional unit representing the registers depends both on the register numbers supplied and on what was written into the registers previously. The operation of both the combinational and sequential elements and their construction are discussed in more detail in Appendix C. We will use the word asserted to indicate a signal that is logically high and assert to specify that a signal should be driven logically high, and deassert or deas­serted to represent logically low. Clocking Methodology A clocking methodology defines when signals can be read and when they can be written. It is important to specify the timing of reads and writes, because if a signal is written at the same time it is read, the value of the read could correspond to the old value, the newly written value, or even some mix of the two! Computer designs cannot tolerate such unpredictability. A clocking methodology is designed to ensure predictability. For simplicity, we will assume an edge-triggered clocking methodology. An edge-triggered clocking methodology means that any values stored in a sequential logic element are updated only on a clock edge. Because only state elements can store a data value, any collection of combinational logic must have its inputs come from a set of state elements and its outputs written into a set of state elements. state element A memory element, such as a register or a memory. asserted The signal is logically high or true. clocking methodology The approach used to determine when data is valid and stable rel­ative to the clock. edge-triggered clocking A clocking scheme in which all state changes occur on a clock edge. 4.2 Logic Design Conventions 305 deasserted The signal is logi­cally low or false.
clipped_hennesy_Page_303_Chunk5660
306 Chapter 4 The Processor The inputs are values that were written in a previous clock cycle, while the outputs are values that can be used in a following clock cycle. Figure 4.3 shows the two state elements surrounding a block of combinational logic, which operates in a single clock cycle: all signals must propagate from state element 1, through the combinational logic, and to state element 2 in the time of one clock cycle. The time necessary for the signals to reach state element 2 defines the length of the clock cycle. FIGURE 4.3 Combinational logic, state elements, and the clock are closely related. In a synchronous digital system, the clock determines when elements with state will write values into internal storage. Any inputs to a state element must reach a stable value (that is, have reached a value from which they will not change until after the clock edge) before the active clock edge causes the state to be updated. All state elements in this chapter, including memory, are assumed to be edge-triggered. State element 1 State element 2 Combinational logic Clock cycle For simplicity, we do not show a write control signal when a state element is written on every active clock edge. In contrast, if a state element is not updated on every clock, then an explicit write control signal is required. Both the clock signal and the write control signal are inputs, and the state element is changed only when the write control signal is asserted and a clock edge occurs. An edge-triggered methodology allows us to read the contents of a register, send the value through some combinational logic, and write that register in the same clock cycle. Figure 4.4 gives a generic example. It doesn’t matter whether we assume that all writes take place on the rising clock edge or on the falling clock edge, since the inputs to the combinational logic block cannot change except on control signal A signal used for multiplexor selection or for directing the operation of a functional unit; contrasts with a data signal, which contains information that is operated on by a functional unit. FIGURE 4.4 An edge-triggered methodology allows a state element to be read and writ­ ten in the same clock cycle without creating a race that could lead to indeterminate data values. Of course, the clock cycle still must be long enough so that the input values are stable when the active clock edge occurs. Feedback cannot occur within one clock cycle because of the edge-triggered update of the state element. If feedback were possible, this design could not work properly. Our designs in this chapter and the next rely on the edge-triggered timing methodology and on structures like the one shown in this figure. State element Combinational logic
clipped_hennesy_Page_304_Chunk5661
the chosen clock edge. With an edge-triggered timing methodology, there is no feedback within a single clock cycle, and the logic in Figure 4.4 works correctly. In Appendix C, we briefly discuss additional timing constraints (such as setup and hold times) as well as other timing methodologies. For the 32-bit MIPS architecture, nearly all of these state and logic elements will have inputs and outputs that are 32 bits wide, since that is the width of most of the data handled by the processor. We will make it clear whenever a unit has an input or output that is other than 32 bits in width. The figures will indicate buses, which are signals wider than 1 bit, with thicker lines. At times, we will want to combine several buses to form a wider bus; for example, we may want to obtain a 32-bit bus by combining two 16-bit buses. In such cases, labels on the bus lines will make it clear that we are concatenating buses to form a wider bus. Arrows are also ­added to help clarify the direction of the flow of data between elements. Finally, color indicates a control signal as opposed to a signal that carries data; this distinction will become clearer as we proceed through this chapter. True or false: Because the register file is both read and written on the same clock cycle, any MIPS datapath using edge-triggered writes must have more than one copy of the register file. Elaboration: There is also a 64-bit version of the MIPS architecture, and, naturally enough, most paths in its implementation would be 64 bits wide. Also, we use the terms assert and deassert because at times 1 represents logically high and at times it can represent logically low. 4.3 Building a Datapath A reasonable way to start a datapath design is to examine the major components required to execute each class of MIPS instructions. Let’s start by looking at which datapath elements each instruction needs. When we show the datapath elements, we will also show their control signals. Figure 4.5a shows the first element we need: a memory unit to store the instructions of a program and supply instructions given an address. Figure 4.5b also shows the program counter (PC), which as we saw in Chapter 2 is a register that holds the address of the current instruction. Lastly, we will need an adder to increment the PC to the address of the next instruction. This adder, which is combinational, can be built from the ALU described in detail in Appendix C simply by wiring the control lines so that the control always specifies an add Check Yourself datapath element A unit used to operate on or hold data within a processor. In the MIPS ­implementation, the datapath elements include the instruc­tion and data memories, the reg­ister file, the ALU, and adders. program counter (PC) The register containing the ­address of the instruction in the program being ­executed. 4.3 Building a Datapath 307
clipped_hennesy_Page_305_Chunk5662
308 Chapter 4 The Processor operation. We will draw such an ALU with the label Add, as in Figure 4.5, to indicate that it has been permanently made an adder and cannot perform the other ALU functions. To execute any instruction, we must start by fetching the instruction from memory. To prepare for executing the next instruction, we must also increment the program counter so that it points at the next instruction, 4 bytes later. Figure 4.6 shows how to combine the three elements from Figure 4.5 to form a datapath that fetches instructions and increments the PC to obtain the address of the next sequential instruction. Now let’s consider the R-format instructions (see Figure 2.20 on page 136). They all read two registers, perform an ALU operation on the contents of the registers, and write the result to a register. We call these instructions either R-type instruc­ tions or ­arithmetic-logical instructions (since they perform arithmetic or logical operations). This instruction class includes add, sub, AND, OR, and slt, which were introduced in Chapter 2. Recall that a typical instance of such an instruction is add $t1,$t2,$t3, which reads $t2 and $t3 and writes $t1. The processor’s 32 general-purpose registers are stored in a structure called a register file. A register file is a collection of registers in which any register can be read or written by specifying the number of the register in the file. The register file contains the register state of the computer. In addition, we will need an ALU to operate on the values read from the registers. R-format instructions have three register operands, so we will need to read two data words from the register file and write one data word into the register file for each instruction. For each data word to be read from the registers, we need an register file A state element that consists of a set of ­registers that can be read and written by supplying a register number to be accessed. FIGURE 4.5 Two state elements are needed to store and access instructions, and an adder is needed to compute the next instruction address. The state elements are the instruction memory and the program counter. The instruction memory need only provide read access because the datapath does not write instructions. Since the instruction memory only reads, we treat it as combinational logic: the output at any time reflects the contents of the location specified by the address input, and no read control signal is needed. (We will need to write the instruction memory when we load the program; this is not hard to add, and we ignore it for simplicity.) The program counter is a 32‑bit register that is written at the end of every clock cycle and thus does not need a write control signal. The adder is an ALU wired to always add its two 32‑bit inputs and place the sum on its output. Instruction address Instruction Instruction memory a. Instruction memory PC b. Program counter Add Sum c. Adder
clipped_hennesy_Page_306_Chunk5663
input to the register file that specifies the register number to be read and an out­put from the register file that will carry the value that has been read from the reg­isters. To write a data word, we will need two inputs: one to specify the register number to be written and one to supply the data to be written into the register. The register file always outputs the contents of whatever register numbers are on the Read register inputs. Writes, however, are controlled by the write control sig­nal, which must be asserted for a write to occur at the clock edge. Figure 4.7a shows the result; we need a total of four inputs (three for register numbers and one for data) and two outputs (both for data). The register number inputs are 5 bits wide to specify one of 32 registers (32 = 25), whereas the data input and two data output buses are each 32 bits wide. Figure 4.7b shows the ALU, which takes two 32‑bit inputs and produces a 32‑bit result, as well as a 1-bit signal if the result is 0. The 4-bit control signal of the ALU is described in detail in Appendix C; we will review the ALU control shortly when we need to know how to set it. Next, consider the MIPS load word and store word instructions, which have the general form lw $t1,offset_value($t2) or sw $t1,offset_value ($t2). These instructions compute a memory address by adding the base regis­ter, which is $t2, to the 16‑bit signed offset field contained in the instruction. If the instruction is a store, the value to be stored must also be read from the register file where it resides in $t1. If the instruction is a load, the value read from mem­ory must be written into the register file in the specified register, which is $t1. Thus, we will need both the register file and the ALU from Figure 4.7. FIGURE 4.6 A portion of the datapath used for fetching instructions and incrementing the program counter. The fetched instruction is used by other parts of the datapath. PC Read address Instruction Instruction memory Add 4 4.3 Building a Datapath 309
clipped_hennesy_Page_307_Chunk5664
310 Chapter 4 The Processor In addition, we will need a unit to sign-extend the 16‑bit offset field in the instruction to a 32‑bit signed value, and a data memory unit to read from or write to. The data memory must be written on store instructions; hence, data memory has read and write control signals, an address input, and an input for the data to be written into memory. Figure 4.8 shows these two elements. The beq instruction has three operands, two registers that are compared for equality, and a 16‑bit offset used to compute the branch target address relative to the branch instruction address. Its form is beq $t1,$t2,offset. To implement this instruction, we must compute the branch target address by adding the sign-extended offset field of the instruction to the PC. There are two details in the definition of branch instructions (see Chapter 2) to which we must pay attention: ■ ■The instruction set architecture specifies that the base for the branch address calculation is the address of the instruction following the branch. Since we compute PC + 4 (the address of the next instruction) in the instruction fetch datapath, it is easy to use this value as the base for computing the branch target address. sign-extend To increase the size of a data item by replicating the high-order sign bit of the original data item in the high- order bits of the larger, destina­tion data item. branch target address The address specified in a branch, which becomes the new program counter (PC) if the branch is taken. In the MIPS architecture the branch target is given by the sum of the offset field of the instruction and the address of the instruction following the branch. FIGURE 4.7 The two elements needed to implement R-format ALU operations are the register file and the ALU. The register file contains all the registers and has two read ports and one write port. The design of multiported register files is discussed in Section C.8 of Appendix C. The register file always outputs the contents of the registers corresponding to the Read register inputs on the outputs; no other control inputs are needed. In contrast, a register write must be explicitly indicated by asserting the write control signal. Remember that writes are edge-t­riggered, so that all the write inputs (i.e., the value to be written, the register number, and the write control signal) must be valid at the clock edge. Since writes to the register file are edge-t­riggered, our design can legally read and write the same register within a clock cycle: the read will get the value written in an earlier clock cycle, while the value written will be available to a read in a subsequent clock cycle. The inputs carrying the register number to the register file are all 5 bits wide, whereas the lines carrying data values are 32 bits wide. The operation to be performed by the ALU is controlled with the ALU operation signal, which will be 4 bits wide, using the ALU designed in Appendix C. We will use the Zero detection output of the ALU shortly to implement branches. The overflow output will not be needed until Section 4.9, when we discuss exceptions; we omit it until then. Read register 1 Registers ALU Data Data Zero ALU result RegWrite a. Registers b. ALU 5 5 5 Register numbers Read data 1 Read data 2 ALU operation 4 Read register 2 Write register Write Data
clipped_hennesy_Page_308_Chunk5665
■ ■The architecture also states that the offset field is shifted left 2 bits so that it is a word offset; this shift increases the effective range of the offset field by a factor of 4. To deal with the latter complication, we will need to shift the offset field by 2. As well as computing the branch target address, we must also determine whether the next instruction is the instruction that follows sequentially or the instruction at the branch target address. When the condition is true (i.e., the ­operands are equal), the branch target address becomes the new PC, and we say that the branch is taken. If the operands are not equal, the incremented PC should replace the current PC (just as for any other normal instruction); in this case, we say that the branch is not taken. Thus, the branch datapath must do two operations: compute the branch target address and compare the register contents. (Branches also affect the instruction fetch portion of the datapath, as we will deal with shortly.) Figure 4.9 shows the structure of the datapath segment that handles branches. To compute the branch target address, the branch datapath includes a sign extension unit, from Figure 4.8 and an adder. To perform the compare, we need to use the register file shown in Figure 4.7a to supply the two register operands (although we will not need to write into the register file). In addition, the comparison can be done using the ALU we designed in Appendix C. Since that ALU provides an output signal that indicates whether the result was 0, we can send the two register operands to the ALU with the branch taken A branch where the branch condition is satisfied and the program counter (PC) becomes the branch target. All unconditional branches are taken branches. branch not taken or (untaken branch) A branch where the branch condition is false and the program counter (PC) becomes the address of the instruction that sequentially follows the branch. FIGURE 4.8 The two units needed to implement loads and stores, in addition to the register file and ALU of Figure 4.7, are the data memory unit and the sign extension unit. The memory unit is a state element with inputs for the address and the write data, and a single output for the read result. There are separate read and write controls, although only one of these may be asserted on any given clock. The memory unit needs a read signal, since, unlike the register file, reading the value of an invalid address can cause problems, as we will see in Chapter 5. The sign extension unit has a 16‑bit input that is sign-extended into a 32‑bit result appearing on the output (see Chapter 2). We assume the data memory is edge-triggered for writes. Standard memory chips actually have a write enable signal that is used for writes. Although the write enable is not edge-triggered, our edge-triggered design could easily be adapted to work with real memory chips. See Section C.8 of Appendix C for further discussion of how real memory chips work. Address Read data Data memory a. Data memory unit Write data MemRead MemWrite b. Sign extension unit Sign- extend 16 32 4.3 Building a Datapath 311
clipped_hennesy_Page_309_Chunk5666
312 Chapter 4 The Processor FIGURE 4.9 The datapath for a branch uses the ALU to evaluate the branch condition and a separate adder to compute the branch target as the sum of the incremented PC and the sign-extended, lower 16 bits of the instruction (the branch displacement), shifted left 2 bits. The unit labeled Shift left 2 is simply a routing of the signals between input and output that adds 00two to the low-order end of the sign-extended offset field; no actual shift hardware is needed, since the amount of the “shift” is constant. Since we know that the offset was sign-extended from 16 bits, the shift will throw away only “sign bits.” Control logic is used to decide whether the incremented PC or branch target should replace the PC, based on the Zero output of the ALU. Read register 1 Registers ALU Zero RegWrite Read data 1 Read data 2 ALU operation 4 To branch control logic Add Sum Branch target PC+ 4 from instruction datapath Sign- extend 16 32 Instruction Shift left 2 Read register 2 Write register Write data control set to do a subtract. If the Zero ­signal out of the ALU unit is asserted, we know that the two values are equal. Although the Zero output always signals if the result is 0, we will be using it only to implement the equal test of branches. Later, we will show exactly how to connect the control signals of the ALU for use in the datapath. The jump instruction operates by replacing the lower 28 bits of the PC with the lower 26 bits of the instruction shifted left by 2 bits. This shift is accomplished simply by concatenating 00 to the jump offset, as described in Chapter 2.
clipped_hennesy_Page_310_Chunk5667
Elaboration: In the MIPS instruction set, branches are delayed, meaning that the instruc­tion immediately following the branch is always executed, independent of whether the branch condition is true or false. When the condition is false, the execution looks like a nor­mal branch. When the condition is true, a delayed branch first executes the instruction imme­diately following the branch in sequential instruction order before jumping to the specified branch target address. The motivation for delayed branches arises from how pipelining affects branches (see Section 4.8). For simplicity, we generally ignore delayed branches in this chapter and implement a nondelayed beq instruction. Creating a Single Datapath Now that we have examined the datapath components needed for the individual instruction classes, we can combine them into a single datapath and add the control to complete the implementation. This simplest datapath will attempt to exe­cute all instructions in one clock cycle. This means that no datapath resource can be used more than once per instruction, so any element needed more than once must be duplicated. We therefore need a memory for instructions separate from one for data. Although some of the functional units will need to be duplicated, many of the elements can be shared by different instruction flows. To share a datapath element between two different instruction classes, we may need to allow multiple connections to the input of an element, using a multi­plexor and control signal to select among the multiple inputs. Building a Datapath The operations of arithmetic-logical (or R-type) instructions and the memory instructions datapath are quite similar. The key differences are the following: ■ ■The arithmetic-logical instructions use the ALU, with the inputs coming from the two registers. The memory instructions can also use the ALU to do the address calculation, although the second input is the sign-­ extended 16-bit offset field from the instruction. ■ ■The value stored into a destination register comes from the ALU (for an R-type instruction) or the memory (for a load). Show how to build a datapath for the operational portion of the memory- reference and arithmetic-logical instructions that uses a single register file and a single ALU to handle both types of instructions, adding any necessary multiplexors. delayed branch A type of branch where the instruction immediately following the branch is always exe­cuted, inde­ pendent of whether the branch condition is true or false. EXAMPLE 4.3 Building a Datapath 313
clipped_hennesy_Page_311_Chunk5668
314 Chapter 4 The Processor To create a datapath with only a single register file and a single ALU, we must support two different sources for the second ALU input, as well as two differ­ent sources for the data stored into the register file. Thus, one multiplexor is placed at the ALU input and another at the data input to the register file. Figure 4.10 shows the operational portion of the combined datapath. ANSWER FIGURE 4.10 The datapath for the memory instructions and the R-type instructions. This example shows how a single datapath can be assembled from the pieces in Figures 4.7 and 4.8 by adding multiplexors. Two multiplexors are needed, as described in the example. Read register 1 Read register 2 Write register Write data Write data Registers ALU Zero RegWrite MemRead MemWrite MemtoReg Read data 1 Read data 2 ALU operation 4 Sign- extend 16 32 Instruction ALU result M u x 0 1 M u x 1 0 ALUSrc Address Data memory Read data Now we can combine all the pieces to make a simple datapath for the MIPS architecture by adding the datapath for instruction fetch (Figure 4.6), the datapath from R-type and memory instructions (Figure 4.10), and the datapath for branches (Figure 4.9). Figure 4.11 shows the datapath we obtain by composing the ­separate pieces. The branch instruction uses the main ALU for comparison of the register operands, so we must keep the adder from Figure 4.9 for computing the branch target address. An additional multiplexor is required to select either the sequen- tially following instruction address (PC + 4) or the branch target address to be written into the PC. Now that we have completed this simple datapath, we can add the control unit. The control unit must be able to take inputs and generate a write signal for each state element, the selector control for each multiplexor, and the ALU control. The
clipped_hennesy_Page_312_Chunk5669
ALU control is different in a number of ways, and it will be useful to design it first before we design the rest of the control unit. I. Which of the following is correct for a load instruction? Refer to Figure 4.10. a. MemtoReg should be set to cause the data from memory to be sent to the register file. b. MemtoReg should be set to cause the correct register destination to be sent to the register file. c. We do not care about the setting of MemtoReg for loads. II. The single-cycle datapath conceptually described in this section must have sepa- rate instruction and data memories, because a. the formats of data and instructions are different in MIPS, and hence different memories are needed. Check Yourself FIGURE 4.11 The simple datapath for the MIPS architecture combines the elements required by different instruction classes. The components come from Figures 4.6, 4.9, and 4.10. This datapath can execute the basic instructions (load-store word, ALU operations, and branches) in a single clock cycle. An additional multiplexor is needed to integrate branches. The support for jumps will be added later. Read register 1 Write data Registers ALU Add Zero RegWrite MemRead MemWrite PCSrc MemtoReg Read data 1 Read data 2 ALU operation 4 Sign- extend 16 32 Instruction ALU result Add ALU result M u x M u x M u x ALUSrc Address Data memory Read data Shift left 2 4 Read address Instruction memory PC Read register 2 Write register Write data 4.3 Building a Datapath 315
clipped_hennesy_Page_313_Chunk5670
316 Chapter 4 The Processor b. having separate memories is less expensive. c. the processor operates in one cycle and cannot use a single-ported memory for two different accesses within that cycle 4.4 A Simple Implementation Scheme In this section, we look at what might be thought of as the simplest possible imple- mentation of our MIPS subset. We build this simple implementation using the datapath of the last section and adding a simple control function. This simple implementation covers load word (lw), store word (sw), branch equal (beq), and the arithmetic-logical instructions add, sub, AND, OR, and set on less than. We will later enhance the design to include a jump instruction (j). The ALU Control The MIPS ALU in Appendix C defines the 6 following combinations of four control inputs: ALU control lines Function 0000 AND 0001 OR 0010 add 0110 subtract 0111 set on less than 1100 NOR Depending on the instruction class, the ALU will need to perform one of these first five functions. (NOR is needed for other parts of the MIPS instruction set not found in the subset we are implementing.) For load word and store word instructions, we use the ALU to compute the memory address by addition. For the R-type instructions, the ALU needs to perform one of the five actions (AND, OR, subtract, add, or set on less than), depending on the value of the 6‑bit funct (or function) field in the low-order bits of the instruction (see Chapter 2). For branch equal, the ALU must perform a subtraction. We can generate the 4‑bit ALU control input using a small control unit that has as inputs the function field of the instruction and a 2‑bit control field, which we call ALUOp. ALUOp indicates whether the operation to be performed should be add (00) for loads and stores, subtract (01) for beq, or determined by the operation encoded in the funct field (10). The output of the ALU control unit is a 4‑bit signal
clipped_hennesy_Page_314_Chunk5671
that directly controls the ALU by generating one of the 4‑bit combinations shown previously. In Figure 4.12, we show how to set the ALU control inputs based on the 2‑bit ALUOp control and the 6‑bit function code. Later in this chapter we will see how the ALUOp bits are generated from the main control unit. Instruction opcode ALUOp Instruction operation Funct field Desired ALU action ALU control input LW 00 load word XXXXXX add 0010 SW 00 store word XXXXXX add 0010 Branch equal 01 branch equal XXXXXX subtract 0110 R-type 10 add 100000 add 0010 R-type 10 subtract 100010 subtract 0110 R-type 10 AND 100100 AND 0000 R-type 10 OR 100101 OR 0001 R-type 10 set on less than 101010 set on less than 0111 FIGURE 4.12 How the ALU control bits are set depends on the ALUOp control bits and the different function codes for the R-type instruction. The opcode, listed in the first column, determines the setting of the ALUOp bits. All the encodings are shown in binary. Notice that when the ALUOp code is 00 or 01, the desired ALU action does not depend on the function code field; in this case, we say that we “don’t care” about the value of the function code, and the funct field is shown as XXXXXX. When the ALUOp value is 10, then the function code is used to set the ALU control input. See Appendix C. This style of using multiple levels of decoding—that is, the main control unit generates the ALUOp bits, which then are used as input to the ALU control that generates the actual signals to control the ALU unit—is a common implementation technique. Using multiple levels of control can reduce the size of the main control unit. Using several smaller control units may also potentially increase the speed of the control unit. Such optimizations are important, since the speed of the control unit is often critical to clock cycle time. There are several different ways to implement the mapping from the 2‑bit ALUOp field and the 6‑bit funct field to the four ALU operation control bits. Because only a small number of the 64 possible values of the function field are of interest and the function field is used only when the ALUOp bits equal 10, we can use a small piece of logic that recognizes the subset of possible values and causes the correct setting of the ALU control bits. As a step in designing this logic, it is useful to create a truth table for the inter­ esting combinations of the function code field and the ALUOp bits, as we’ve done in Figure 4.13; this truth table shows how the 4‑bit ALU control is set depending on these two input fields. Since the full truth table is very large (28 = 256 entries) and we don’t care about the value of the ALU control for many of these input truth table From logic, a rep­resentation of a logical opera­tion by listing all the values of the inputs and then in each case showing what the resulting out­puts should be. 4.4 A Simple Implementation Scheme 317
clipped_hennesy_Page_315_Chunk5672
318 Chapter 4 The Processor combinations, we show only the truth table entries for which the ALU control must have a specific value. Throughout this chapter, we will use this practice of showing only the truth table entries for outputs that must be asserted and not showing those that are all deasserted or don’t care. (This practice has a disadvantage, which we discuss in Section D.2 of Appendix D.) Because in many instances we do not care about the values of some of the inputs, and because we wish to keep the tables compact, we also include don’t-care terms. A don’t-care term in this truth table (represented by an X in an input column) indicates that the output does not depend on the value of the input corresponding to that column. For example, when the ALUOp bits are 00, as in the first row of Figure 4.13, we always set the ALU control to 0010, independent of the function code. In this case, then, the function code inputs will be don’t cares in this line of the truth table. Later, we will see examples of another type of don’t-care term. If you are unfamiliar with the concept of don’t-care terms, see Appendix C for more information. Once the truth table has been constructed, it can be optimized and then turned into gates. This process is completely mechanical. Thus, rather than show the final steps here, we describe the process and the result in Section D.2 of Appendix D. Designing the Main Control Unit Now that we have described how to design an ALU that uses the function code and a 2‑bit signal as its control inputs, we can return to looking at the rest of the control. To start this process, let’s identify the fields of an instruction and the con­trol lines that are needed for the datapath we constructed in Figure 4.11. To understand how to connect the fields of an instruction to the datapath, it is useful to review the formats of the three instruction classes: the R-type, branch, and load-store instructions. Figure 4.14 shows these formats. don’t-care term An element of a logical function in which the output does not depend on the values of all the inputs. Don’t-care terms may be specified in different ways. ALUOp Funct field Operation ALUOp1 ALUOp0 F5 F4 F3 F2 F1 F0 0 0 X X X X X X 0010 0 1 X X X X X X 0110 1 0 X X 0 0 0 0 0010 1 X X X 0 0 1 0 0110 1 0 X X 0 1 0 0 0000 1 0 X X 0 1 0 1 0001 1 X X X 1 0 1 0 0111 FIGURE 4.13 The truth table for the 4 ALU control bits (called Operation). The inputs are the ALUOp and function code field. Only the entries for which the ALU control is asserted are shown. Some don’t-care entries have been added. For example, the ALUOp does not use the encoding 11, so the truth table can contain entries 1X and X1, rather than 10 and 01. Note that when the function field is used, the first 2 bits (F5 and F4) of these instructions are always 10, so they are don’t-care terms and are replaced with XX in the truth table.
clipped_hennesy_Page_316_Chunk5673
Field 0 rs rt rd shamt funct Bit positions 31:26 25:21 20:16 15:11 10:6 5:0 a. R-type instruction Field 35 or 43 rs rt address Bit positions 31:26 25:21 20:16 15:0 b. Load or store instruction Field 4 rs rt address Bit positions 31:26 25:21 20:16 15:0 c. Branch instruction FIGURE 4.14 The three instruction classes (R-type, load and store, and branch) use two different instruction formats. The jump instructions use another format, which we will discuss shortly. (a) Instruction format for R-format instructions, which all have an opcode of 0. These instructions have three register operands: rs, rt, and rd. Fields rs and rt are sources, and rd is the destination. The ALU function is in the funct field and is decoded by the ALU control design in the previous section. The R-type instructions that we implement are add, sub, AND, OR, and slt. The shamt field is used only for shifts; we will ignore it in this chapter. (b) Instruction format for load (opcode = 35ten) and store (opcode = 43ten) instructions. The register rs is the base register that is added to the 16‑bit address field to form the memory address. For loads, rt is the destination register for the loaded value. For stores, rt is the source register whose value should be stored into memory. (c) Instruction format for branch equal (opcode = 4). The reg­isters rs and rt are the source registers that are compared for equality. The 16‑bit address field is sign-extended, shifted, and added to the PC+4 to compute the branch target address. There are several major observations about this instruction format that we will rely on: ■ ■The op field, also called the opcode, is always contained in bits 31:26. We will refer to this field as Op[5:0]. ■ ■The two registers to be read are always specified by the rs and rt fields, at positions 25:21 and 20:16. This is true for the R-type instructions, branch equal, and store. ■ ■The base register for load and store instructions is always in bit positions 25:21 (rs). ■ ■The 16‑bit offset for branch equal, load, and store is always in positions 15:0. ■ ■The destination register is in one of two places. For a load it is in bit ­positions 20:16 (rt), while for an R-type instruction it is in bit positions 15:11 (rd). Thus, we will need to add a multiplexor to select which field of the instruction is used to indicate the register number to be written. The first design principle from Chapter 2—simplicity favors regularity—pays off here in specifying control. opcode The field that denotes the operation and format of an instruction. 4.4 A Simple Implementation Scheme 319
clipped_hennesy_Page_317_Chunk5674
320 Chapter 4 The Processor Using this information, we can add the instruction labels and extra multiplexor (for the Write register number input of the register file) to the simple datapath. Figure 4.15 shows these additions plus the ALU control block, the write signals for state elements, the read signal for the data memory, and the control signals for the multiplexors. Since all the multiplexors have two inputs, they each require a single control line. Figure 4.15 shows seven single‑bit control lines plus the 2‑bit ALUOp control signal. We have already defined how the ALUOp control signal works, and it is useful to define what the seven other control signals do informally before we deter- mine how to set these control signals during instruction execution. Figure 4.16 describes the function of these seven control lines. FIGURE 4.15 The datapath of Figure 4.11 with all necessary multiplexors and all control lines identified. The control lines are shown in color. The ALU control block has also been added. The PC does not require a write control, since it is written once at the end of every clock cycle; the branch control logic determines whether it is written with the incremented PC or the branch target address. Read register 1 Write data Registers ALU Add Zero MemRead MemWrite RegWrite PCSrc MemtoReg Read data 1 Read data 2 Sign- extend 16 32 Instruction [31:0] ALU result Add ALU result Mux Mux Mux ALUSrc Address Data memory Read data Shift left 2 4 Read address Instruction memory PC 1 0 0 1 0 1 Mux 0 1 ALU control ALUOp Instruction [5:0] Instruction [25:21] Instruction [15:11] Instruction [20:16] Instruction [15:0] RegDst Read register 2 Write register Write data
clipped_hennesy_Page_318_Chunk5675
Signal name Effect when deasserted Effect when asserted RegDst The register destination number for the Write register comes from the rt field (bits 20:16). The register destination number for the Write register comes from the rd field (bits 15:11). RegWrite None. The register on the Write register input is written with the value on the Write data input. ALUSrc The second ALU operand comes from the second register file output (Read data 2). The second ALU operand is the sign- extended, lower 16 bits of the instruction. PCSrc The PC is replaced by the output of the adder that computes the value of PC + 4. The PC is replaced by the output of the adder that computes the branch target. MemRead None. Data memory contents designated by the address input are put on the Read data output. MemWrite None. Data memory contents designated by the address input are replaced by the value on the Write data input. MemtoReg The value fed to the register Write data input comes from the ALU. The value fed to the register Write data input comes from the data memory. FIGURE 4.16 The effect of each of the seven control signals. When the 1‑bit control to a two- way multiplexor is asserted, the multiplexor selects the input corresponding to 1. Otherwise, if the control is deasserted, the multiplexor selects the 0 input. Remember that the state elements all have the clock as an implicit input and that the clock is used in controlling writes. Gating the clock externally to a state element can create timing problems. (See Appendix C for further discussion of this problem.) Now that we have looked at the function of each of the control signals, we can look at how to set them. The control unit can set all but one of the control signals based solely on the opcode field of the instruction. The PCSrc control line is the exception. That control line should be asserted if the instruction is branch on equal (a decision that the control unit can make) and the Zero output of the ALU, which is used for equality comparison, is asserted. To generate the PCSrc ­signal, we will need to AND together a signal from the control unit, which we call Branch, with the Zero signal out of the ALU. These nine control signals (seven from Figure 4.16 and two for ALUOp) can now be set on the basis of six input signals to the control unit, which are the opcode bits 31 to 26. Figure 4.17 shows the datapath with the control unit and the control signals. Before we try to write a set of equations or a truth table for the control unit, it will be useful to try to define the control function informally. Because the setting of the control lines depends only on the opcode, we define whether each control signal should be 0, 1, or don’t care (X) for each of the opcode values. Figure 4.18 defines how the control signals should be set for each opcode; this information follows directly from Figures 4.12, 4.16, and 4.17. Operation of the Datapath With the information contained in Figures 4.16 and 4.18, we can design the control unit logic, but before we do that, let’s look at how each instruction uses the 4.4 A Simple Implementation Scheme 321
clipped_hennesy_Page_319_Chunk5676
322 Chapter 4 The Processor FIGURE 4.17 The simple datapath with the control unit. The input to the control unit is the 6‑bit opcode field from the instruction. The outputs of the control unit consist of three 1‑bit signals that are used to control multiplexors (RegDst, ALUSrc, and MemtoReg), three signals for con­trolling reads and writes in the register file and data memory (RegWrite, MemRead, and MemWrite), a 1‑bit signal used in determining whether to possibly branch (Branch), and a 2‑bit control signal for the ALU (ALUOp). An AND gate is used to combine the branch control signal and the Zero output from the ALU; the AND gate output controls the selection of the next PC. Notice that PCSrc is now a derived signal, rather than one coming directly from the control unit. Thus, we drop the signal name in subsequent figures. Read register 1 Write data Registers ALU Add Zero Read data 1 Read data 2 Sign- extend 16 32 Instruction [31–0] ALU result Add ALU result Mux Mux Mux Address Data memory Read data Shift left 2 4 Read address Instruction memory PC 1 0 0 1 0 1 Mux 0 1 ALU control Instruction [5–0] Instruction [25–21] Instruction [31–26] Instruction [15–11] Instruction [20–16] Instruction [15–0] RegDst Branch MemRead MemtoReg ALUOp MemWrite ALUSrc RegWrite Control Read register 2 Write register Write data datapath. In the next few figures, we show the flow of three different instruction classes through the datapath. The asserted control signals and active datapath elements are highlighted in each of these. Note that a multiplexor whose control is 0 has a definite action, even if its control line is not highlighted. Multiple‑bit control signals are highlighted if any constituent ­signal is asserted.
clipped_hennesy_Page_320_Chunk5677
Figure 4.19 shows the operation of the datapath for an R-type instruction, such as add $t1,$t2,$t3. Although everything occurs in one clock cycle, we can think of four steps to execute the instruction; these steps are ordered by the flow of information: 1. The instruction is fetched, and the PC is incremented. 2. Two registers, $t2 and $t3, are read from the register file; also, the main control unit computes the setting of the control lines during this step. 3. The ALU operates on the data read from the register file, using the function code (bits 5:0, which is the funct field, of the instruction) to generate the ALU function. 4. The result from the ALU is written into the register file using bits 15:11 of the instruction to select the destination register ($t1). Similarly, we can illustrate the execution of a load word, such as lw $t1, ­offset($t2) in a style similar to Figure 4.19. Figure 4.20 shows the active functional units and asserted control lines for a load. We can think of a load instruction as operating in five steps (similar to the R-type executed in four): 1. An instruction is fetched from the instruction memory, and the PC is incremented. 2. A register ($t2) value is read from the register file. Instruction RegDst ALUSrc Memto- Reg Reg- Write Mem- Read Mem- Write Branch ALUOp1 ALUOp0 R-format 1 0 0 1 0 0 0 1 0 lw 0 1 1 1 1 0 0 0 0 sw X 1 X 0 0 1 0 0 0 beq X 0 X 0 0 0 1 0 1 FIGURE 4.18 The setting of the control lines is completely determined by the opcode fields of the instruction. The first row of the table corresponds to the R-format instructions (add, sub, AND, OR, and slt). For all these instructions, the source register fields are rs and rt, and the destination register field is rd; this defines how the signals ALUSrc and RegDst are set. Furthermore, an R-type instruction writes a register (Reg­Write = 1), but neither reads nor writes data memory. When the Branch control signal is 0, the PC is unconditionally replaced with PC + 4; otherwise, the PC is replaced by the branch target if the Zero output of the ALU is also high. The ALUOp field for R‑type instructions is set to 10 to indicate that the ALU control should be generated from the funct field. The second and third rows of this table give the control signal settings for lw and sw. These ALUSrc and ALUOp fields are set to perform the address calculation. The MemRead and MemWrite are set to perform the memory access. Finally, RegDst and RegWrite are set for a load to cause the result to be stored into the rt register. The branch instruction is similar to an R-format operation, since it sends the rs and rt registers to the ALU. The ALUOp field for branch is set for a subtract (ALU control = 01), which is used to test for equality. Notice that the MemtoReg field is irrelevant when the RegWrite signal is 0: since the register is not being written, the value of the data on the register data write port is not used. Thus, the entry MemtoReg in the last two rows of the table is replaced with X for don’t care. Don’t cares can also be added to RegDst when RegWrite is 0. This type of don’t care must be added by the designer, since it depends on knowledge of how the datapath works. 4.4 A Simple Implementation Scheme 323
clipped_hennesy_Page_321_Chunk5678
324 Chapter 4 The Processor 3. The ALU computes the sum of the value read from the register file and the sign-extended, lower 16 bits of the instruction (offset). 4. The sum from the ALU is used as the address for the data memory. 5. The data from the memory unit is written into the register file; the register destination is given by bits 20:16 of the instruction ($t1) . FIGURE 4.19 The datapath in operation for an R-type instruction, such as add $t1,$t2,$t3. The control lines, datapath units, and connections that are active are highlighted. Read register 1 Write data Registers ALU Add Zero Read data 1 Read data 2 Sign- extend 16 32 Instruction [31–0] ALU result Add ALU result Mux Mux Mux Address Data memory Read data Shift left 2 4 Read address Instruction memory PC 1 0 0 1 0 1 Mux 0 1 ALU control Instruction [5–0] Instruction [25–21] Instruction [31–26] Instruction [15–11] Instruction [20–16] Instruction [15–0] RegDst Branch MemRead MemtoReg ALUOp MemWrite ALUSrc RegWrite Control Read register 2 Write register Write data
clipped_hennesy_Page_322_Chunk5679
Finally, we can show the operation of the branch-on-equal instruction, such as beq $t1,$t2,offset, in the same fashion. It operates much like an R‑format instruction, but the ALU output is used to determine whether the PC is written with PC + 4 or the branch target address. Figure 4.21 shows the four steps in execution: 1. An instruction is fetched from the instruction memory, and the PC is incremented. 2. Two registers, $t1 and $t2, are read from the register file. FIGURE 4.20 The datapath in operation for a load instruction. The control lines, datapath units, and connections that are active are high­lighted. A store instruction would operate very similarly. The main difference would be that the memory control would indicate a write rather than a read, the second register value read would be used for the data to store, and the operation of writing the data memory value to the register file would not occur. Read register 1 Write data Registers ALU Add Zero Read data 1 Read data 2 Sign- extend 16 32 Instruction [31–0] ALU result Add ALU result Mux Mux Mux Address Data memory Read data Shift left 2 4 Read address Instruction memory PC 1 0 0 1 0 1 Mux 0 1 ALU control Instruction [5–0] Instruction [25–21] Instruction [31–26] Instruction [15–11] Instruction [20–16] Instruction [15–0] RegDst Branch MemRead MemtoReg ALUOp MemWrite ALUSrc RegWrite Control Read register 2 Write register Write data 4.4 A Simple Implementation Scheme 325
clipped_hennesy_Page_323_Chunk5680
326 Chapter 4 The Processor 3. The ALU performs a subtract on the data values read from the register file. The value of PC + 4 is added to the sign-extended, lower 16 bits of the instruction (offset) shifted left by two; the result is the branch target address. 4. The Zero result from the ALU is used to decide which adder result to store into the PC. FIGURE 4.21 The datapath in operation for a branch-on-equal instruction. The control lines, datapath units, and connections that are active are highlighted. After using the register file and ALU to perform the compare, the Zero output is used to select the next program counter from between the two candidates. Read register 1 Write data Registers ALU Add Zero Read data 1 Read data 2 Sign- extend 16 32 Instruction [31–0] ALU result Add ALU result Mux Mux Mux Address Data memory Read data Shift left 2 4 Read address Instruction memory PC 1 0 0 1 0 1 Mux 0 1 ALU control Instruction [5–0] Instruction [25–21] Instruction [31–26] Instruction [15–11] Instruction [20–16] Instruction [15–0] RegDst Branch MemRead MemtoReg ALUOp MemWrite ALUSrc RegWrite Control Read register 2 Write register Write data
clipped_hennesy_Page_324_Chunk5681
Finalizing Control Now that we have seen how the instructions operate in steps, let’s continue with the control implementation. The control function can be precisely defined using the contents of Figure 4.18. The outputs are the control lines, and the input is the 6‑bit opcode field, Op [5:0]. Thus, we can create a truth table for each of the outputs based on the binary encoding of the opcodes. Figure 4.22 shows the logic in the control unit as one large truth table that combines all the outputs and that uses the opcode bits as inputs. It completely specifies the control function, and we can implement it directly in gates in an automated fashion. We show this final step in Section D.2 in Appendix D. Now that we have a single-cycle implementation of most of the MIPS core instruction set, let’s add the jump instruction to show how the basic datapath and control can be extended to handle other instructions in the instruction set. Input or output Signal name R-format lw sw beq Inputs Op5 0 1 1 0 Op4 0 0 0 0 Op3 0 0 1 0 Op2 0 0 0 1 Op1 0 1 1 0 Op0 0 1 1 0 Outputs RegDst 1 0 X X ALUSrc 0 1 1 0 MemtoReg 0 1 X X RegWrite 1 1 0 0 MemRead 0 1 0 0 MemWrite 0 0 1 0 Branch 0 0 0 1 ALUOp1 1 0 0 0 ALUOp0 0 0 0 1 FIGURE 4.22 The control function for the simple single-cycle implementation is com­ pletely specified by this truth table. The top half of the table gives the combinations of input signals that correspond to the four opcodes, one per column, that determine the control output settings. (Remem­ ber that Op [5:0] corresponds to bits 31:26 of the instruction, which is the op field.) The bottom portion of the table gives the outputs for each of the four opcodes. Thus, the output RegWrite is asserted for two dif­ferent combinations of the inputs. If we consider only the four opcodes shown in this table, then we can simplify the truth table by using don’t cares in the input portion. For example, we can detect an R-format instruction with the expression Op5 • Op2, since this is sufficient to distinguish the ­R-format instructions from lw, sw, and beq. We do not take advantage of this simplification, since the rest of the MIPS opcodes are used in a full implementation. single-cycle implementation Also called single clock cycle implementa­tion. An implementation in which an instruction is executed in one clock cycle. 4.4 A Simple Implementation Scheme 327
clipped_hennesy_Page_325_Chunk5682
328 Chapter 4 The Processor Implementing Jumps Figure 4.17 shows the implementation of many of the instruc­tions we looked at in Chapter 2. One class of instructions missing is that of the jump instruction. Extend the datapath and control of Figure 4.17 to in­clude the jump instruction. Describe how to set any new control lines. The jump instruction, shown in Figure 4.23, looks somewhat like a branch instruc­tion but computes the target PC differently and is not conditional. Like a branch, the low-order 2 bits of a jump address are always 00two. The next lower 26 bits of this 32‑bit address come from the 26‑bit immediate field in the instruction. The upper 4 bits of the address that should replace the PC come from the PC of the jump instruction plus 4. Thus, we can implement a jump by storing into the PC the concatenation of ■ ■the upper 4 bits of the current PC + 4 (these are bits 31:28 of the sequen- tially following instruction address) ■ ■the 26‑bit immediate field of the jump instruction ■ ■the bits 00two Figure 4.24 shows the addition of the control for jump added to Figure 4.17. An additional multiplexor is used to select the source for the new PC value, which is either the incremented PC (PC + 4), the branch target PC, or the jump target PC. One additional control signal is needed for the addi­tional multi- plexor. This control signal, called Jump, is asserted only when the instruction is a jump—that is, when the opcode is 2. EXAMPLE ANSWER Field 000010 address Bit positions 31:26 25:0 FIGURE 4.23 Instruction format for the jump instruction (opcode = 2). The destination address for a jump instruction is formed by concatenating the upper 4 bits of the current PC + 4 to the 26‑bit address field in the jump instruction and adding 00 as the 2 low-order bits. Why a Single-Cycle Implementation Is Not Used Today Although the single-cycle design will work correctly, it would not be used in modern designs because it is inefficient. To see why this is so, notice that the clock cycle must have the same length for every instruction in this single-cycle design. Of course,
clipped_hennesy_Page_326_Chunk5683
the clock cycle is determined by the longest possible path in the processor. This path is almost certainly a load instruction, which uses five functional units in series: the instruction memory, the register file, the ALU, the data memory, and the register file. Although the CPI is 1 (see Chapter 1), the overall performance of a ­single-cycle implementation is likely to be poor, since the clock cycle is too long. FIGURE 4.24 The simple control and datapath are extended to handle the jump instruction. An additional multiplexor (at the upper right) is used to choose between the jump target and either the branch target or the sequential instruction following this one. This multiplexor is controlled by the jump control signal. The jump target address is obtained by shifting the lower 26 bits of the jump instruction left 2 bits, effectively adding 00 as the low-order bits, and then concatenating the upper 4 bits of PC + 4 as the high-order bits, thus yielding a 32-bit address. Read register 1 Write data Registers ALU Add Zero Read data 1 Read data 2 Sign- extend 16 32 Instruction [31–0] ALU result Add ALU result Mux Mux Mux Address Data memory Read data Shift left 2 4 Read address Instruction memory PC 1 0 0 1 0 1 Mux 0 1 ALU control Instruction [5–0] Instruction [25–21] Instruction [31–26] Instruction [15–11] Instruction [20–16] Instruction [15–0] RegDst Jump Branch MemRead MemtoReg ALUOp MemWrite ALUSrc RegWrite Control Read register 2 Write register Write data Mux 1 0 Shift left 2 Instruction [25–0] Jump address [31–0] 26 28 PC + 4 [31–28] 4.4 A Simple Implementation Scheme 329
clipped_hennesy_Page_327_Chunk5684
330 Chapter 4 The Processor The penalty for using the single-cycle design with a fixed clock cycle is ­signifi­cant, but might be considered acceptable for this small instruction set. Histori­cally, early computers with very simple instruction sets did use this implementation technique. However, if we tried to implement the floating-point unit or an instruction set with more complex instructions, this single-cycle design wouldn’t work well at all. Because we must assume that the clock cycle is equal to the worst-case delay for all instructions, it’s useless to try implementation techniques that reduce the delay of the common case but do not improve the worst-case cycle time. A single-cycle implementation thus violates our key design principle from Chapter 2 of making the common case fast. In next section, we’ll look at another implementation technique, called pipelin- ing, that uses a datapath very similar to the single-cycle datapath but is much more efficient by having a much higher throughput. Pipelining improves efficiency by executing multiple instructions simultaneously. Look at the control signals in Figure 4.22. Can you combine any together? Can any control signal output in the figure be replaced by the inverse of another? (Hint: take into account the don’t cares.) If so, can you use one signal for the other without adding an inverter? 4.5 An Overview of Pipelining Pipelining is an implementation technique in which multiple in­structions are overlapped in execution. Today, pipelining is nearly universal. This section relies heavily on one analogy to give an overview of the pipelining terms and issues. If you are interested in just the big picture, you should concen­ trate on this section and then skip to Sections 4.10 and 4.11 to see an introduction to the advanced pipelining techniques used in recent processors such as the AMD Opteron X4 (Barcelona) or Intel Core. If you are interested in exploring the anatomy of a pipe­lined computer, this section is a good introduction to Sections 4.6 through 4.9. Anyone who has done a lot of laundry has intuitively used pipelining. The non­ pipelined approach to laundry would be 1. Place one dirty load of clothes in the washer. 2. When the washer is finished, place the wet load in the dryer. 3. When the dryer is finished, place the dry load on a table and fold. 4. When folding is finished, ask your roommate to put the clothes away. When your roommate is done, then start over with the next dirty load. Check Yourself Never waste time. American proverb pipelining An implementation technique in which multi­ple instructions are overlapped in execution, much like an assembly line.
clipped_hennesy_Page_328_Chunk5685
The pipelined approach takes much less time, as Figure 4.25 shows. As soon as the washer is finished with the first load and placed in the dryer, you load the washer with the second dirty load. When the first load is dry, you place it on the table to start folding, move the wet load to the dryer, and the next dirty load into the washer. Next you have your roommate put the first load away, you start fold- ing the second load, the dryer has the third load, and you put the fourth load into the washer. At this point all steps—called stages in pipe­lining—are operating con- currently. As long as we have separate resources for each stage, we can pipeline the tasks. The pipelining paradox is that the time from placing a single dirty sock in the washer until it is dried, folded, and put away is not shorter for pipelining; the reason pipelining is faster for many loads is that everything is working in parallel, so more loads are finished per hour. Pipelining improves throughput of our laundry system. Hence, pipelining would not decrease the time to complete one load of laundry, but when we have many loads of laundry to do, the improvement in throughput decreases the total time to complete the work. 4.5 An Overview of Pipelining 331 FIGURE 4.25 The laundry analogy for pipelining. Ann, Brian, Cathy, and Don each have dirty clothes to be washed, dried, folded, and put away. The washer, dryer, “folder,” and “storer” each take 30 minutes for their task. Sequential laundry takes 8 hours for 4 loads of wash, while pipelined laundry takes just 3.5 hours. We show the pipeline stage of different loads over time by showing copies of the four resources on this two‑dimensional time line, but we really have just one of each resource. Time Task order A B C D 6 PM 7 8 9 10 11 12 1 2 AM Time Task order A B C D 6 PM 7 8 9 10 11 12 1 2 AM
clipped_hennesy_Page_329_Chunk5686
332 Chapter 4 The Processor If all the stages take about the same amount of time and there is enough work to do, then the speed-up due to pipelining is equal to the number of stages in the pipeline, in this case four: washing, drying, folding, and putting away. There- fore, pipelined laundry is potentially four times faster than nonpipelined: 20 loads would take about 5 times as long as 1 load, while 20 loads of sequential laundry takes 20 times as long as 1 load. It’s only 2.3 times faster in Figure 4.25, because we only show 4 loads. Notice that at the beginning and end of the workload in the pipelined version in Figure 4.25, the pipeline is not completely full; this start-up and wind-down affects performance when the number of tasks is not large com- pared to the number of stages in the pipeline. If the number of loads is much larger than 4, then the stages will be full most of the time and the increase in throughput will be very close to 4. The same principles apply to processors where we pipeline instruction ­execution. MIPS instructions classically take five steps: 1. Fetch instruction from memory. 2. Read registers while decoding the instruction. The regular format of MIPS instructions allows reading and decoding to occur simultaneously. 3. Execute the operation or calculate an address. 4. Access an operand in data memory. 5. Write the result into a register. Hence, the MIPS pipeline we explore in this chapter has five stages. The following example shows that pipelining speeds up instruction execution just as it speeds up the laundry. Single-Cycle versus Pipelined Performance To make this discussion concrete, let’s create a pipeline. In this example, and in the rest of this chapter, we limit our attention to eight instructions: load word (lw), store word (sw), add (add), subtract (sub), AND (and), OR (or), set less than (slt), and branch on equal (beq). Compare the average time between instructions of a single-cycle imple- mentation, in which all instructions take one clock cycle, to a pipelined imple- mentation. The operation times for the major functional units in this ex­ample are 200 ps for memory access, 200 ps for ALU operation, and 100 ps for register file read or write. In the single-cycle model, every instruction takes exact­ly one clock cycle, so the clock cycle must be stretched to accommodate the slow­est instruction. EXAMPLE
clipped_hennesy_Page_330_Chunk5687
Figure 4.26 shows the time required for each of the eight instructions. The ­single-cycle design must allow for the slowest instruction—in Figure 4.26 it is lw—so the time required for every instruction is 800 ps. Similarly to Figure 4.25, Figure 4.27 compares nonpipelined and pipelined execution of three load word instructions. Thus, the time between the first and fourth instruc­tions in the nonpipelined design is 3 × 800 ns or 2400 ps. All the pipeline stages take a single clock cycle, so the clock cycle must be long enough to accommodate the slowest operation. Just as the single-cycle design must take the worst-case clock cycle of 800 ps, even though some instructions can be as fast as 500 ps, the pipelined execution clock cycle must have the worst-case clock cycle of 200 ps, even though some stages take only 100 ps. Pipelining still offers a fourfold performance improvement: the time between the first and fourth instructions is 3 × 200 ps or 600 ps. Instruction class Instruction fetch Register read ALU operation Data access Register write Total time Load word (lw) 200 ps 100 ps 200 ps 200 ps 100 ps 800 ps Store word (sw) 200 ps 100 ps 200 ps 200 ps 700 ps R-format (add, sub, AND, OR, slt) 200 ps 100 ps 200 ps 100 ps 600 ps Branch (beq) 200 ps 100 ps 200 ps 500 ps FIGURE 4.26 Total time for each instruction calculated from the time for each component. This calculation assumes that the multiplexors, control unit, PC accesses, and sign extension unit have no delay. We can turn the pipelining speed-up discussion above into a formula. If the stages are perfectly balanced, then the time between instructions on the pipelined processor—assuming ideal conditions—is equal to Time between instructionspipelined = ​ Time between instructionsnonpipelined  Number of pipe stages ​ Under ideal conditions and with a large number of instructions, the speed-up from pipelining is approximately equal to the number of pipe stages; a five-stage pipe­line is nearly five times faster. The formula suggests that a five-stage pipeline should offer nearly a fivefold improvement over the 800 ps nonpipelined time, or a 160 ps clock cycle. The example shows, however, that the stages may be imperfectly balanced. In addition, pipelining involves some overhead, the source of which will be more clear shortly. Thus, the time per instruction in the pipelined processor will exceed the mini­mum possible, and speed-up will be less than the number of pipeline stages. ANSWER 4.5 An Overview of Pipelining 333
clipped_hennesy_Page_331_Chunk5688
334 Chapter 4 The Processor Moreover, even our claim of fourfold improvement for our example is not reflected in the total execution time for the three instructions: it’s 1400 ps versus 2400 ps. Of course, this is because the number of instructions is not large. What would happen if we increased the number of instructions? We could extend the previous figures to 1,000,003 instructions. We would add 1,000,000 instructions in the pipelined example; each instruction adds 200 ps to the total execution time. The total execution time would be 1,000,000 × 200 ps + 1400 ps, or 200,001,400 ps. In the nonpipelined ­example, we would add 1,000,000 instructions, each tak­ ing 800 ps, so total execution time would be 1,000,000 × 800 ps + 2400 ps, or 800,002,400 ps. Under these conditions, the ratio of total execution times for real programs on nonpipelined to pipelined processors is close to the ratio of times between instructions: ​ 800,002,400 ps  200,001,400 ps ​ ≈ ​ 800 ps  200 ps ​ ≈ 4.00 FIGURE 4.27 Single-cycle, nonpipelined execution in top versus pipelined execution in bottom. Both use the same hardware components, whose time is listed in Figure 4.26. In this case, we see a fourfold speed-up on average time between instructions, from 800 ps down to 200 ps. Compare this figure to Figure 4.25. For the laundry, we assumed all stages were equal. If the dryer were slowest, then the dryer stage would set the stage time. The pipeline stage times of a computer are also limited by the slowest resource, either the ALU operation or the memory access. We assume the write to the register file occurs in the first half of the clock cycle and the read from the register file occurs in the second half. We use this assumption throughout this chapter. Program execution order (in instructions) lw $1, 100($0) lw $2, 200($0) lw $3, 300($0) Time 1000 1200 1400 200 400 600 800 1000 1200 1400 200 400 600 800 1600 1800 Instruction fetch Data access Reg Instruction fetch Data access Reg Instruction fetch 800 ps 800 ps 800 ps Program execution order (in instructions) lw $1, 100($0) lw $2, 200($0) lw $3, 300($0) Time Instruction fetch Data access Reg Instruction fetch Instruction fetch Data access Reg Data access Reg 200 ps 200 ps 200 ps 200 ps 200 ps 200 ps 200 ps ALU Reg ALU Reg ALU ALU ALU Reg Reg Reg
clipped_hennesy_Page_332_Chunk5689
Pipelining improves performance by increasing instruction throughput, as opposed to decreasing the execution time of an individual instruction, but instruction throughput is the important metric because real programs execute billions of instructions. Designing Instruction Sets for Pipelining Even with this simple explanation of pipelining, we can get insight into the design of the MIPS instruction set, which was designed for pipelined execution. First, all MIPS instructions are the same length. This restriction makes it much easier to fetch instructions in the first pipeline stage and to decode them in the second stage. In an instruction set like the x86, where instructions vary from 1 byte to 17 bytes, pipelining is considerably more challenging. Recent implementa­tions of the x86 architecture actually translate x86 instructions into simple opera­tions that look like MIPS instructions and then pipeline the simple operations rather than the native x86 instructions! (See Section 4.10.) Second, MIPS has only a few instruction formats, with the source register fields being located in the same place in each instruction. This symmetry means that the second stage can begin reading the register file at the same time that the hardware is determining what type of instruction was fetched. If MIPS instruction formats were not symmetric, we would need to split stage 2, resulting in six pipeline stages. We will shortly see the downside of longer pipelines. Third, memory operands only appear in loads or stores in MIPS. This restric­ tion means we can use the execute stage to calculate the memory address and then access memory in the following stage. If we could operate on the operands in memory, as in the x86, stages 3 and 4 would expand to an address stage, memory stage, and then execute stage. Fourth, as discussed in Chapter 2, operands must be aligned in memory. Hence, we need not worry about a single data transfer instruction requiring two data memory accesses; the requested data can be transferred between processor and memory in a single pipeline stage. Pipeline Hazards There are situations in pipelining when the next instruction cannot execute in the following clock cycle. These events are called hazards, and there are three different types. Structural Hazards The first hazard is called a structural hazard. It means that the hardware cannot support the combination of instructions that we want to execute in the same clock cycle. A structural hazard in the laundry room would occur if we used a washer- dryer combination instead of a separate washer and dryer, or if our roommate was busy doing something else and wouldn’t put clothes away. Our carefully scheduled pipeline plans would then be foiled. structural hazard When a planned ­instruction cannot exe­cute in the proper clock cycle because the hardware does not support the combination of instructions that are set to exe­cute. 4.5 An Overview of Pipelining 335
clipped_hennesy_Page_333_Chunk5690
336 Chapter 4 The Processor As we said above, the MIPS instruction set was designed to be pipelined, mak­ing it fairly easy for designers to avoid structural hazards when designing a pipe­line. Suppose, however, that we had a single memory instead of two memories. If the pipeline in Figure 4.27 had a fourth instruction, we would see that in the same clock cycle the first instruction is accessing data from memory while the fourth instruction is fetching an instruction from that same memory. Without two mem­ ories, our pipeline could have a structural hazard. Data Hazards Data hazards occur when the pipeline must be stalled because one step must wait for another to complete. Suppose you found a sock at the folding station for which no match existed. One possible strategy is to run down to your room and search through your clothes bureau to see if you can find the match. Obviously, while you are doing the search, loads that have completed drying and are ready to fold and those that have finished washing and are ready to dry must wait. In a computer pipeline, data hazards arise from the dependence of one instruc­ tion on an earlier one that is still in the pipeline (a relationship that does not really exist when doing laundry). For example, suppose we have an add instruction fol­ lowed immediately by a subtract instruction that uses the sum ($s0): add $s0, $t0, $t1 sub $t2, $s0, $t3 Without intervention, a data hazard could severely stall the pipeline. The add instruction doesn’t write its result until the fifth stage, meaning that we would have to waste three clock cycles in the pipeline. Although we could try to rely on compilers to remove all such hazards, the results would not be satisfactory. These dependences happen just too often and the delay is just too long to expect the compiler to rescue us from this dilemma. The primary solution is based on the observation that we don’t need to wait for the instruction to complete before trying to resolve the data hazard. For the code sequence above, as soon as the ALU creates the sum for the add, we can supply it as an input for the subtract. Adding extra hardware to retrieve the missing item early from the internal resources is called forwarding or bypassing. Forwarding with Two Instructions For the two instructions above, show what pipeline stages would be con­nected by forwarding. Use the drawing in Figure 4.28 to represent the datap­ath during the five stages of the pipeline. Align a copy of the datapath for each instruction, similar to the laundry pipeline in Figure 4.25. data hazard Also called a pipe­line data hazard. When a planned instruction cannot exe­ cute in the proper clock cycle because data that is needed to execute the instruction is not yet available. forwarding Also called ­bypassing. A method of ­resolving a data hazard by retrieving the missing data ­element from internal buffers rather than waiting for it to arrive from ­programmer- visible registers or memory. EXAMPLE
clipped_hennesy_Page_334_Chunk5691
Figure 4.29 shows the connection to forward the value in $s0 after the execu­ tion stage of the add instruction as input to the execution stage of the sub instruction. ANSWER FIGURE 4.28 Graphical representation of the instruction pipeline, similar in spirit to the laundry pipeline in Figure 4.25. Here we use symbols representing the physical resources with the abbreviations for pipeline stages used throughout the chapter. The symbols for the five stages: IF for the instruction fetch stage, with the box representing instruction memory; ID for the instruc­tion decode/register file read stage, with the drawing showing the register file being read; EX for the execu­tion stage, with the drawing representing the ALU; MEM for the memory access stage, with the box representing data memory; and WB for the write-back stage, with the drawing showing the register file being written. The shading indicates the element is used by the instruction. Hence, MEM has a white back­ground because add does not access the data memory. Shading on the right half of the register file or mem­ory means the element is read in that stage, and shading of the left half means it is written in that stage. Hence the right half of ID is shaded in the second stage because the register file is read, and the left half of WB is shaded in the fifth stage because the register file is written. Time add $s0, $t0, $t1 IF MEM ID WB EX 200 400 600 800 1000 Time add $s0, $t0, $t1 sub $t2, $s0, $t3 IF MEM ID WB EX IF MEM ID WB EX Program execution order (in instructions) 200 400 600 800 1000 FIGURE 4.29 Graphical representation of forwarding. The connection shows the forwarding path from the output of the EX stage of add to the input of the EX stage for sub, replacing the value from register $s0 read in the second stage of sub. In this graphical representation of events, forwarding paths are valid only if the destination stage is later in time than the source stage. For example, there cannot be a valid forwarding path from the output of the memory access stage in the first instruction to the input of the execution stage of the following, since that would mean going backward in time. Forwarding works very well and is described in detail in Section 4.7. It cannot prevent all pipeline stalls, however. For example, suppose the first instruction was a 4.5 An Overview of Pipelining 337
clipped_hennesy_Page_335_Chunk5692
338 Chapter 4 The Processor load of $s0 instead of an add. As we can imagine from looking at Figure 4.29, the desired data would be available only after the fourth stage of the first instruc­tion in the dependence, which is too late for the input of the third stage of sub. Hence, even with forwarding, we would have to stall one stage for a load-use data hazard, as Figure 4.30 shows. This figure shows an important pipeline concept, officially called a pipeline stall, but often given the nickname bubble. We shall see stalls elsewhere in the pipeline. Section 4.7 shows how we can handle hard cases like these, using either hardware detection and stalls or software that reorders code to try to avoid load-use pipeline stalls, as this example illustrates. Reordering Code to Avoid Pipeline Stalls Consider the following code segment in C: a = b + e; c = b + f; Here is the generated MIPS code for this segment, assuming all variables are in memory and are addressable as offsets from $t0: load-use data hazard A spe­cific form of data hazard in which the data being loaded by a load instruction has not yet become available when it is needed by another instruction. pipeline stall Also called bub­ble. A stall initiated in ­order to resolve a hazard. EXAMPLE FIGURE 4.30 We need a stall even with forwarding when an R-format instruction follow­ing a load tries to use the data. Without the stall, the path from memory access stage output to exe­cution stage input would be going backward in time, which is impossible. This figure is actually a simplification, since we cannot know until after the subtract instruction is fetched and decoded whether or not a stall will be necessary. Section 4.7 shows the details of what really happens in the case of a hazard. 200 400 600 800 1000 1200 1400 Time lw $s0, 20($t1) sub $t2, $s0, $t3 IF MEM ID WB EX IF MEM ID WB EX Program execution order (in instructions) bubble bubble bubble bubble bubble
clipped_hennesy_Page_336_Chunk5693
lw $t1, 0($t0) lw $t2, 4($t0) add $t3, $t1,$t2 sw $t3, 12($t0) lw $t4, 8($t0) add $t5, $t1,$t4 sw $t5, 16($t0) Find the hazards in the preceding code segment and reorder the instructions to avoid any pipeline stalls. Both add instructions have a hazard because of their respective dependence on the immediately preceding lw instruction. Notice that bypassing elimi­nates several other potential hazards, including the dependence of the first add on the first lw and any hazards for store instructions. Moving up the third lw instruction to become the third instruction eliminates both haz­ards: lw $t1, 0($t0) lw $t2, 4($t0) lw $t4, 8($t0) add $t3, $t1,$t2 sw $t3, 12($t0) add $t5, $t1,$t4 sw $t5, 16($t0) On a pipelined processor with forwarding, the reordered sequence will com- plete in two fewer cycles than the original version. Forwarding yields another insight into the MIPS architecture, in addition to the four mentioned on page 335. Each MIPS instruction writes at most one result and does this in the last stage of the pipeline. Forwarding is harder if there are multiple results to forward per instruction or they need to write a result early on in instruc­ tion execution. Elaboration: The name “forwarding” comes from the idea that the result is passed forward from an earlier instruction to a later instruction. “Bypassing” comes from pass- ing the result around the register file to the desired unit. Control Hazards The third type of hazard is called a control hazard, arising from the need to make a decision based on the results of one instruction while others are executing. Suppose our laundry crew was given the happy task of cleaning the uniforms of a football team. Given how filthy the laundry is, we need to determine whether the detergent and water temperature setting we select is strong enough to get the uni­forms clean but not so strong that the uniforms wear out sooner. In our laundry ANSWER control hazard Also called branch hazard. When the proper instruction cannot exe­cute in the proper pipeline clock cycle because the instruction that was fetched is not the one that is needed; that is, the flow of instruction addresses is not what the pipeline expected. 4.5 An Overview of Pipelining 339
clipped_hennesy_Page_337_Chunk5694
340 Chapter 4 The Processor pipeline, we have to wait until the second stage to examine the dry uniform to see if we need to change the washer setup or not. What to do? Here is the first of two solutions to control hazards in the laundry room and its computer equivalent. Stall: Just operate sequentially until the first batch is dry and then repeat until you have the right formula. This conservative option certainly works, but it is slow. The equivalent decision task in a computer is the branch instruction. Notice that we must begin fetching the instruction following the branch on the very next clock cycle. Nevertheless, the pipeline cannot possibly know what the next instruction should be, since it only just received the branch instruction from mem­ory! Just as with laundry, one possible solution is to stall immediately after we fetch a branch, waiting until the pipeline determines the outcome of the branch and knows what instruction address to fetch from. Let’s assume that we put in enough extra hardware so that we can test registers, calculate the branch address, and update the PC during the second stage of the pipeline (see Section 4.8 for details). Even with this extra hardware, the pipeline involving conditional branches would look like Figure 4.31. The lw instruction, executed if the branch fails, is stalled one extra 200 ps clock cycle before starting. FIGURE 4.31 Pipeline showing stalling on every conditional branch as solution to control hazards. This example assumes the conditional branch is taken, and the instruction at the destina­tion of the branch is the OR instruction. There is a one-stage pipeline stall, or bubble, after the branch. In reality, the process of creating a stall is slightly more complicated, as we will see in Section 4.8. The effect on performance, however, is the same as would occur if a bubble were inserted. add $4, $5, $6 beq $1, $2, 40 or $7, $8, $9 Time Instruction fetch Data access Data access Data access Reg Instruction fetch Instruction fetch Reg Reg 200 ps 400 ps bubble bubble bubble bubble bubble 200 400 600 800 1000 1200 1400 Program execution order (in instructions) Reg ALU Reg ALU Reg ALU
clipped_hennesy_Page_338_Chunk5695
Performance of “Stall on Branch” Estimate the impact on the clock cycles per instruction (CPI) of stalling on branches. Assume all other instructions have a CPI of 1. Figure 3.27 in Chapter 3 shows that branches are 17% of the instructions executed in SPECint2006. Since the other instructions run have a CPI of 1, and branches took one extra clock cycle for the stall, then we would see a CPI of 1.17 and hence a slowdown of 1.17 versus the ideal case. If we cannot resolve the branch in the second stage, as is often the case for longer pipelines, then we’d see an even larger slowdown if we stall on branches. The cost of this option is too high for most computers to use and motivates a second solution to the control hazard: Predict: If you’re pretty sure you have the right formula to wash uniforms, then just predict that it will work and wash the second load while waiting for the first load to dry. This option does not slow down the pipeline when you are correct. When you are wrong, however, you need to redo the load that was washed while guessing the decision. Computers do indeed use prediction to handle branches. One simple approach is to predict always that branches will be untaken. When you’re right, the pipeline proceeds at full speed. Only when branches are taken does the pipeline stall. Figure 4.32 shows such an example. A more sophisticated version of branch prediction would have some branches predicted as taken and some as untaken. In our analogy, the dark or home uni­ forms might take one formula while the light or road uniforms might take another. In the case of programming, at the bottom of loops are branches that jump back to the top of the loop. Since they are likely to be taken and they branch backward, we could always predict taken for branches that jump to an earlier address. Such rigid approaches to branch prediction rely on stereotypical behavior and don’t account for the individuality of a specific branch instruction. Dynamic hard­ ware predictors, in stark contrast, make their guesses depending on the behavior of each branch and may change predictions for a branch over the life of a pro­gram. Following our analogy, in dynamic prediction a person would look at how dirty the uniform was and guess at the formula, adjusting the next guess depend­ing on the success of recent guesses. EXAMPLE ANSWER branch prediction A method of resolving a branch ­hazard that assumes a given outcome for the branch and proceeds from that assumption rather than ­waiting to ascertain the actual outcome. 4.5 An Overview of Pipelining 341
clipped_hennesy_Page_339_Chunk5696
342 Chapter 4 The Processor One popular approach to dynamic prediction of branches is keeping a history for each branch as taken or untaken, and then using the recent past behavior to predict the future. As we will see later, the amount and type of history kept have become extensive, with the result being that dynamic branch predictors can cor­ rectly predict branches with more than 90% accuracy (see Section 4.8). When the guess is wrong, the pipeline control must ensure that the instructions following the wrongly guessed branch have no effect and must restart the pipeline from the proper branch address. In our laundry analogy, we must stop taking new loads so that we can restart the load that we incorrectly predicted. As in the case of all other solutions to control hazards, longer pipelines exacer­ bate the problem, in this case by raising the cost of misprediction. Solutions to control hazards are described in more detail in Section 4.8. FIGURE 4.32 Predicting that branches are not taken as a solution to control hazard. The top drawing shows the pipeline when the branch is not taken. The bottom drawing shows the pipeline when the branch is taken. As we noted in Figure 4.31, the insertion of a bubble in this fashion simplifies what actually happens, at least during the first clock cycle immediately following the branch. Section 4.8 will reveal the details. add $4, $5, $6 beq $1, $2, 40 lw $3, 300($0) Time Instruction fetch Instruction fetch Data access Reg Instruction fetch Data access Data access Reg Reg Reg ALU Reg ALU Reg ALU Reg ALU Reg ALU Reg ALU 200 ps 200 ps add $4, $5, $6 beq $1, $2, 40 or $7, $8, $9 Time Instruction fetch Data access Reg Instruction fetch Instruction fetch Data access Reg Data access Reg 200 ps 400 ps bubble bubble bubble bubble bubble 200 400 600 800 1000 1200 1400 Program execution order (in instructions) 200 400 600 800 1000 1200 1400 Program execution order (in instructions)
clipped_hennesy_Page_340_Chunk5697
Elaboration: There is a third approach to the control hazard, called delayed decision mentioned above. In our analogy, whenever you are going to make such a decision about laundry, just place a load of nonfootball clothes in the washer while waiting for football uniforms to dry. As long as you have enough dirty clothes that are not affected by the test, this solution works fine. Called the delayed branch in computers, this is the solution actually used by the MIPS architecture. The delayed branch always executes the next sequential instruc- tion, with the branch taking place after that one instruction delay. It is hidden from the MIPS assembly lan­guage programmer because the assembler can automatically arrange the instructions to get the branch behavior desired by the programmer. MIPS software will place an instruction immedi­ately after the delayed branch instruction that is not affected by the branch, and a taken branch changes the address of the instruction that follows this safe instruction. In our example, the add instruction before the branch in Figure 4.31 does not affect the branch and can be moved after the branch to fully hide the branch delay. Since delayed branches are useful when the branches are short, no processor uses a delayed branch of more than one cycle. For longer branch delays, ­hardware-based branch prediction is usually used. Pipeline Overview Summary Pipelining is a technique that exploits parallelism among the instructions in a sequential instruction stream. It has the substantial ad­vantage that, unlike pro­ gramming a multiprocessor, it is fundamentally invisible to the programmer. In the next sections of this chapter, we cover the concept of pipelining using the MIPS instruction subset from the single-cycle implementation in Section 4.4 and show a simplified version of its pipeline. We then look at the problems that pipe­ lining introduces and the performance attainable under typical sit­uations. If you wish to focus more on the software and the performance implications of pipelining, you now have sufficient background to skip to Section 4.10. Section 4.10 introduces advanced pipelining concepts, such as superscalar and dynamic scheduling, and Section 4.11 examines the pipelines of recent microprocessors. Alternatively, if you are interested in understanding how pipelining is imple­ mented and the challenges of dealing with hazards, you can proceed to examine the design of a pipelined datapath and the basic control, explained in Section 4.6. You can then use this understanding to explore the implementation of forwarding and stalls in Section 4.7. You can then read Section 4.8 to learn more about solu­tions to branch hazards, and then see how exceptions are handled in Section 4.9. For each code sequence below, state whether it must stall, can avoid stalls using only forwarding, or can execute without stalling or forwarding. Check Yourself Sequence 1 Sequence 2 Sequence 3 lw $t0,0($t0) add $t1,$t0,$t0 add $t1,$t0,$t0 addi $t2,$t0,#5 addi $t4,$t1,#5 addi $t1,$t0,#1 addi $t2,$t0,#2 addi $t3,$t0,#2 addi $t3,$t0,#4 addi $t5,$t0,#5 4.5 An Overview of Pipelining 343
clipped_hennesy_Page_341_Chunk5698
344 Chapter 4 The Processor Outside the memory system, the effective operation of the pipeline is usually the most important factor in determining the CPI of the processor and hence its performance. As we will see in Section 4.10, understanding the performance of a modern multiple-issue pipelined processor is complex and requires understand­ing more than just the issues that arise in a simple pipelined processor. Nonethe­less, structural, data, and control hazards remain important in both simple pipelines and more sophisticated ones. For modern pipelines, structural hazards usually revolve around the floating- point unit, which may not be fully pipelined, while control hazards are usually more of a problem in integer programs, which tend to have higher branch frequencies as well as less predictable branches. Data hazards can be performance bottlenecks in both integer and floating-point programs. Often it is easier to deal with data hazards in floating-point programs because the lower branch frequency and more regular memory access patterns allow the compiler to try to schedule instructions to avoid hazards. It is more difficult to perform such optimizations in integer programs that have less regular memory access, involving more use of pointers. As we will see in Section 4.10, there are more ambitious compiler and hardware techniques for reducing data dependences through scheduling. Pipelining increases the number of simultaneously executing instructions and the rate at which instructions are started and completed. Pipelining does not reduce the time it takes to complete an individual instruction, also called the latency. For example, the five-stage pipeline still takes 5 clock cycles for the instruction to complete. In the terms used in Chapter 1, pipelining improves instruction throughput rather than individual instruction execution time or latency. Instruction sets can either simplify or make life harder for pipeline designers, who must already cope with structural, control, and data hazards. Branch prediction and forwarding help make a computer fast while still getting the right answers. 4.6 Pipelined Datapath and Control Figure 4.33 shows the single-cycle datapath from Section 4.4 with the pipeline stages identified. The division of an instruction into five stages means a five-stage Understanding Program Performance The BIG Picture latency (pipeline) The num­ber of stages in a pipeline or the number of stages between two instructions ­during execution. There is less in this than meets the eye. Tallulah Bankhead, remark to Alexander Woollcott, 1922
clipped_hennesy_Page_342_Chunk5699
pipeline, which in turn means that up to five instructions will be in execution during any single clock cycle. Thus, we must separate the datapath into five pieces, with each piece named corresponding to a stage of instruction execution: 1. IF: Instruction fetch 2. ID: Instruction decode and register file read 3. EX: Execution or address calculation 4. MEM: Data memory access 5. WB: Write back In Figure 4.33, these five components correspond roughly to the way the data­­ path is drawn; instructions and data move generally from left to right through the five stages as they complete execution. Returning to our laundry analogy, clothes get cleaner, drier, and more organized as they move through the line, and they never move backward. FIGURE 4.33 The single-cycle datapath from Section 4.4 (similar to Figure 4.17). Each step of the instruction can be mapped onto the datapath from left to right. The only exceptions are the update of the PC and the write-back step, shown in color, which sends either the ALU result or the data from memory to the left to be written into the register file. (Normally we use color lines for control, but these are data lines.) WB: Write back MEM: Memory access IF: Instruction fetch EX: Execute/ address calculation 1 M u x 0 0 M u x 1 Address Write data Read data Data memory Read register 1 Read register 2 Write register Write data Registers Read data 1 Read data 2 ALU Zero ALU result ADD Add result Shift left 2 Address Instruction Instruction memory Add 4 PC Sign- extend 0 M u x 1 32 ID: Instruction decode/ register file read 16 4.6 Pipelined Datapath and Control 345
clipped_hennesy_Page_343_Chunk5700