text
stringlengths
1
7.76k
source
stringlengths
17
81
146 Chapter 2 Instructions: Language of the Computer ■ ■The library routines become part of the executable code. If a new version of the library is released that fixes bugs or supports new hardware devices, the statically linked program keeps using the old version. ■ ■It loads all routines in the library that are called anywhere in the executable, even if those calls are not executed. The library can be large relative to the program; for example, the standard C library is 2.5 MB. These disadvantages lead to dynamically linked libraries (DLLs), where the library routines are not linked and loaded until the program is run. Both the pro­ gram and library routines keep extra information on the location of nonlocal pro­ cedures and their names. In the initial version of DLLs, the loader ran a dynamic linker, using the extra information in the file to find the appropriate libraries and to update all external references. The downside of the initial version of DLLs was that it still linked all routines of the library that might be called, versus only those that are called during the running of the program. This observation led to the lazy procedure linkage version of DLLs, where each routine is linked only after it is called. Like many innovations in our field, this trick relies on a level of indirection. Figure 2.22 shows the technique. It starts with the nonlocal routines calling a set of dummy routines at the end of the program, with one entry per nonlocal rou­tine. These dummy entries each contain an indirect jump. The first time the library routine is called, the program calls the dummy entry and follows the indirect jump. It points to code that puts a number in a register to identify the desired library routine and then jumps to the dynamic linker/loader. The linker/loader finds the desired routine, remaps it, and changes the address in the indirect jump location to point to that routine. It then jumps to it. When the routine completes, it returns to the original calling site. Thereafter, the call to the library routine jumps indirectly to the routine without the extra hops. In summary, DLLs require extra space for the information needed for dynamic linking, but do not require that whole libraries be copied or linked. They pay a good deal of overhead the first time a routine is called, but only a single indirect jump thereafter. Note that the return from the library pays no extra overhead. Microsoft’s Windows relies extensively on dynamically linked libraries, and it is also the default when executing programs on UNIX systems today. Starting a Java Program The discussion above captures the traditional model of executing a program, where the emphasis is on fast execution time for a program targeted to a specific instruction set architecture, or even a specific implementation of that architec­ture. Indeed, it is possible to execute Java programs just like C. Java was invented with a different set of goals, however. One was to run safely on any computer, even if it might slow execution time. dynamically linked libraries (DLLs) Library routines that are linked to a program during execution.
clipped_hennesy_Page_144_Chunk5501
FIGURE 2.22 Dynamically linked library via lazy procedure linkage. (a) Steps for the first time a call is made to the DLL routine. (b) The steps to find the routine, remap it, and link it are skipped on subsequent calls. As we will see in Chapter 5, the operating system may avoid copying the desired routine by remapping it using virtual memory management. Text jal a. First call to DLL routine b. Subsequent calls to DLL routine lw jr ... ... Data Text li ID j ... ... Text Data/Text Dynamic linker/loader Remap DLL routine j... DLL routine jr ... Text jal lw jr ... ... Data DLL routine jr ... Text Figure 2.23 shows the typical translation and execution steps for Java. Rather than compile to the assembly language of a target computer, Java is compiled first to instructions that are easy to interpret: the Java bytecode instruction set (see Section 2.15 on the CD). This instruction set is designed to be close to the Java language so that this compilation step is trivial. Virtually no optimizations are performed. Like the C compiler, the Java compiler checks the types of data and produces the proper operation for each type. Java programs are distributed in the binary version of these bytecodes. A software interpreter, called a Java Virtual Machine (JVM), can execute Java bytecodes. An interpreter is a program that simulates an instruction set architec­ ture. For example, the MIPS simulator used with this book is an interpreter. There is no need for a separate assembly step since either the translation is so simple that the compiler fills in the addresses or JVM finds them at runtime. Java bytecode Instruction from an instruction set designed to interpret Java programs. Java Virtual Machine (JVM) The program that inter­prets Java bytecodes. 2.12 Translating and Starting a Program 147
clipped_hennesy_Page_145_Chunk5502
148 Chapter 2 Instructions: Language of the Computer The upside of interpretation is portability. The availability of software Java vir­ tual machines meant that most people could write and run Java programs shortly after Java was announced. Today, Java virtual machines are found in hundreds of millions of devices, in everything from cell phones to Internet browsers. The downside of interpretation is lower performance. The incredible advances in performance of the 1980s and 1990s made interpretation viable for many important applications, but the factor of 10 slowdown when compared to tradi­ tionally compiled C programs made Java unattractive for some applications. To preserve portability and improve execution speed, the next phase of Java development was compilers that translated while the program was running. Such Just In Time compilers (JIT) typically profile the running program to find where the “hot” methods are and then compile them into the native instruction set on which the virtual machine is running. The compiled portion is saved for the next time the program is run, so that it can run faster each time it is run. This balance of interpretation and compilation evolves over time, so that frequently run Java programs suffer little of the overhead of interpretation. As computers get faster so that compilers can do more, and as researchers invent betters ways to compile Java on the fly, the performance gap between Java and C or C++ is closing. Section 2.15 on the CD goes into much greater depth on the implementation of Java, Java bytecodes, JVM, and JIT compilers. Which of the advantages of an interpreter over a translator do you think was most important for the designers of Java? 1. Ease of writing an interpreter 2. Better error messages 3. Smaller object code 4. Machine independence Just In Time compiler (JIT) The name commonly given to a compiler that operates at runtime, translating the inter­preted code segments into the native code of the computer. Check Yourself FIGURE 2.23 A translation hierarchy for Java. A Java program is first compiled into a binary version of Java bytecodes, with all addresses defined by the compiler. The Java program is now ready to run on the interpreter, called the Java Virtual Machine (JVM). The JVM links to desired methods in the Java library while the program is running. To achieve greater performance, the JVM can invoke the JIT compiler, which selectively compiles methods into the native machine language of the machine on which it is running. Java program Compiler Class files (Java bytecodes) Java Virtual Machine Compiled Java methods (machine language) Java library routines (machine language) Just In Time compiler
clipped_hennesy_Page_146_Chunk5503
2.13 A C Sort Example to Put It All Together One danger of showing assembly language code in snippets is that you will have no idea what a full assembly language program looks like. In this section, we derive the MIPS code from two procedures written in C: one to swap array ele­ments and one to sort them. The Procedure swap Let’s start with the code for the procedure swap in Figure 2.24. This procedure simply swaps two locations in memory. When translating from C to assembly lan­ guage by hand, we follow these general steps: 1. Allocate registers to program variables. 2. Produce code for the body of the procedure. 3. Preserve registers across the procedure invocation. This section describes the swap procedure in these three pieces, concluding by putting all the pieces together. Register Allocation for swap As mentioned on pages 112–113, the MIPS convention on parameter passing is to use registers $a0, $a1, $a2, and $a3. Since swap has just two parameters, v and k, they will be found in registers $a0 and $a1. The only other variable is temp, which we associate with register $t0 since swap is a leaf procedure (see page 116). void swap(int v[], int k) { int temp; temp = v[k]; v[k] = v[k+1]; v[k+1] = temp; } FIGURE 2.24 A C procedure that swaps two locations in memory. This subsection uses this procedure in a sorting example. 2.13 A C Sort Example to Put It All Together 149
clipped_hennesy_Page_147_Chunk5504
150 Chapter 2 Instructions: Language of the Computer This register allocation corresponds to the variable declarations in the first part of the swap procedure in Figure 2.24. Code for the Body of the Procedure swap The remaining lines of C code in swap are temp = v[k]; v[k] = v[k+1]; v[k+1] = temp; Recall that the memory address for MIPS refers to the byte address, and so words are really 4 bytes apart. Hence we need to multiply the index k by 4 before adding it to the address. Forgetting that sequential word addresses differ by 4 instead of by 1 is a common mistake in assembly language programming. Hence the first step is to get the address of v[k] by multiplying k by 4 via a shift left by 2: sll $t1, $a1,2 # reg $t1 = k * 4 add $t1, $a0,$t1 # reg $t1 = v + (k * 4) # reg $t1 has the address of v[k] Now we load v[k] using $t1, and then v[k+1] by adding 4 to $t1: lw $t0, 0($t1) # reg $t0 (temp) = v[k] lw $t2, 4($t1) # reg $t2 = v[k + 1] # refers to next element of v Next we store $t0 and $t2 to the swapped addresses: sw $t2, 0($t1) # v[k] = reg $t2 sw $t0, 4($t1) # v[k+1] = reg $t0 (temp) Now we have allocated registers and written the code to perform the operations of the procedure. What is missing is the code for preserving the saved registers used within swap. Since we are not using saved registers in this leaf procedure, there is nothing to preserve. The Full swap Procedure We are now ready for the whole routine, which includes the procedure label and the return jump. To make it easier to follow, we identify in Figure 2.25 each block of code with its purpose in the procedure. The Procedure sort To ensure that you appreciate the rigor of programming in assembly language, we’ll try a second, longer example. In this case, we’ll build a routine that calls the swap procedure. This program sorts an array of integers, using bubble or exchange sort, which is one of the simplest if not the fastest sorts. Figure 2.26 shows the C
clipped_hennesy_Page_148_Chunk5505
version of the program. Once again, we present this procedure in sev­eral steps, concluding with the full procedure. Register Allocation for sort The two parameters of the procedure sort, v and n, are in the parameter registers $a0 and $a1, and we assign register $s0 to i and register $s1 to j. Code for the Body of the Procedure sort The procedure body consists of two nested for loops and a call to swap that includes parameters. Let’s unwrap the code from the outside to the middle. The first translation step is the first for loop: for (i = 0; i < n; i += 1) { Recall that the C for statement has three parts: initialization, loop test, and itera­ tion increment. It takes just one instruction to initialize i to 0, the first part of the for statement: move $s0, $zero # i = 0 void sort (int v[], int n) { int i, j; for (i = 0; i < n; i += 1) { for (j = i – 1; j >= 0 && v[j] > v[j + 1]; j ­= 1) { swap(v,j); } } } FIGURE 2.26 A C procedure that performs a sort on the array v. Procedure body swap: sll $t1, $a1, 2 # reg $t1 = k * 4 add $t1, $a0, $t1 # reg $t1 = v + (k * 4) # reg $t1 has the address of v[k] lw $t0, 0($t1) # reg $t0 (temp) = v[k] lw $t2, 4($t1) # reg $t2 = v[k + 1] # refers to next element of v sw $t2, 0($t1) # v[k] = reg $t2 sw $t0, 4($t1) # v[k+1] = reg $t0 (temp) Procedure return jr $ra # return to calling routine FIGURE 2.25 MIPS assembly code of the procedure swap in Figure 2.24. 2.13 A C Sort Example to Put It All Together 151
clipped_hennesy_Page_149_Chunk5506
152 Chapter 2 Instructions: Language of the Computer (Remember that move is a pseudoinstruction provided by the assembler for the convenience of the assembly language programmer; see page 141.) It also takes just one instruction to increment i, the last part of the for statement: addi $s0, $s0, 1 # i += 1 The loop should be exited if i < n is not true or, said another way, should be exited if i ≥ n. The set on less than instruction sets register $t0 to 1 if $s0 < $a1 and to 0 otherwise. Since we want to test if $s0 ≥ $a1, we branch if register $t0 is 0. This test takes two instructions: for1tst:slt $t0, $s0, $a1 # reg $t0 = 0 if $s0 ≥ $a1 (i≥n) beq $t0, $zero,exit1 # go to exit1 if $s0 ≥ $a1 (i≥n) The bottom of the loop just jumps back to the loop test: j for1tst # jump to test of outer loop exit1: The skeleton code of the first for loop is then move $s0, $zero # i = 0 for1tst:slt $t0, $s0, $a1 # reg $t0 = 0 if $s0 ≥ $a1 (i≥n) beq $t0, $zero,exit1 # go to exit1 if $s0 ≥ $a1 (i≥n) . . . (body of first for loop) . . . addi $s0, $s0, 1 # i += 1 j for1tst # jump to test of outer loop exit1: Voila! (The exercises explore writing faster code for similar loops.) The second for loop looks like this in C: for (j = i – 1; j >= 0 && v[j] > v[j + 1]; j –= 1) { The initialization portion of this loop is again one instruction: addi $s1, $s0, –1 # j = i – 1 The decrement of j at the end of the loop is also one instruction: addi $s1, $s1, –1 # j –= 1 The loop test has two parts. We exit the loop if either condition fails, so the first test must exit the loop if it fails (j < 0): for2tst: slti $t0, $s1, 0 # reg $t0 = 1 if $s1 < 0 (j < 0) bne $t0, $zero, exit2 # go to exit2 if $s1 < 0 (j < 0) This branch will skip over the second condition test. If it doesn’t skip, j ≥ 0.
clipped_hennesy_Page_150_Chunk5507
The second test exits if v[j] > v[j + 1] is not true, or exits if v[j] ≤ v[j + 1]. First we create the address by multiplying j by 4 (since we need a byte address) and add it to the base address of v: sll $t1, $s1, 2 # reg $t1 = j * 4 add $t2, $a0, $t1 # reg $t2 = v + (j * 4) Now we load v[j]: lw $t3, 0($t2) # reg $t3 = v[j] Since we know that the second element is just the following word, we add 4 to the address in register $t2 to get v[j + 1]: lw $t4, 4($t2) # reg $t4 = v[j + 1] The test of v[j] ≤ v[j + 1] is the same as v[j + 1] ≥ v[j], so the two instructions of the exit test are slt $t0, $t4, $t3 # reg $t0 = 0 if $t4 ≥ $t3 beq $t0, $zero, exit2 # go to exit2 if $t4 ≥ $t3 The bottom of the loop jumps back to the inner loop test: j for2tst # jump to test of inner loop Combining the pieces, the skeleton of the second for loop looks like this: addi $s1, $s0, –1 # j = i – 1 for2tst:slti $t0, $s1, 0 # reg $t0 = 1 if $s1 < 0 (j < 0) bne $t0, $zero, exit2 # go to exit2 if $s1 < 0 (j < 0) sll $t1, $s1, 2 # reg $t1 = j * 4 add $t2, $a0, $t1 # reg $t2 = v + (j * 4) lw $t3, 0($t2) # reg $t3 = v[j] lw $t4, 4($t2) # reg $t4 = v[j + 1] slt $t0, $t4, $t3 # reg $t0 = 0 if $t4 ≥ $t3 beq $t0, $zero, exit2 # go to exit2 if $t4 ≥ $t3 . . . (body of second for loop) . . . addi $s1, $s1, –1 # j –= 1 j for2tst # jump to test of inner loop exit2: The Procedure Call in sort The next step is the body of the second for loop: swap(v,j); Calling swap is easy enough: jal swap 2.13 A C Sort Example to Put It All Together 153
clipped_hennesy_Page_151_Chunk5508
154 Chapter 2 Instructions: Language of the Computer Passing Parameters in sort The problem comes when we want to pass parameters because the sort proce­dure needs the values in registers $a0 and $a1, yet the swap procedure needs to have its parameters placed in those same registers. One solution is to copy the parameters for sort into other registers earlier in the procedure, making registers $a0 and $a1 available for the call of swap. (This copy is faster than saving and restoring on the stack.) We first copy $a0 and $a1 into $s2 and $s3 during the procedure: move $s2, $a0 # copy parameter $a0 into $s2 move $s3, $a1 # copy parameter $a1 into $s3 Then we pass the parameters to swap with these two instructions: move $a0, $s2 # first swap parameter is v move $a1, $s1 # second swap parameter is j Preserving Registers in sort The only remaining code is the saving and restoring of registers. Clearly, we must save the return address in register $ra, since sort is a procedure and is called itself. The sort procedure also uses the saved registers $s0, $s1, $s2, and $s3, so they must be saved. The prologue of the sort procedure is then addi $sp,$sp,–20 # make room on stack for 5 reg­isters sw $ra,16($sp) # save $ra on stack sw $s3,12($sp) # save $s3 on stack sw $s2, 8($sp) # save $s2 on stack sw $s1, 4($sp) # save $s1 on stack sw $s0, 0($sp) # save $s0 on stack The tail of the procedure simply reverses all these instructions, then adds a jr to return. The Full Procedure sort Now we put all the pieces together in Figure 2.27, being careful to replace refer­ences to registers $a0 and $a1 in the for loops with references to registers $s2 and $s3. Once again, to make the code easier to follow, we identify each block of code with its purpose in the procedure. In this example, nine lines of the sort procedure in C became 35 lines in the MIPS assembly language. Elaboration: One optimization that works with this example is procedure inlining. Instead of passing arguments in parameters and invoking the code with a jal instruction, the compiler would copy the code from the body of the swap procedure where the call to swap appears in the code. Inlining would avoid four instructions in this example. The downside of the inlining optimization is that the compiled code would be bigger if the inlined procedure is called from several locations. Such a code expansion might turn into lower performance if it increased the cache miss rate; see Chapter 5.
clipped_hennesy_Page_152_Chunk5509
Saving registers sort: addi $sp,$sp, –20 # make room on stack for 5 registers sw $ra, 16($sp)# save $ra on stack sw $s3,12($sp) # save $s3 on stack sw $s2, 8($sp)# save $s2 on stack sw $s1, 4($sp)# save $s1 on stack sw $s0, 0($sp)# save $s0 on stack Procedure body Move parameters move $s2, $a0 # copy parameter $a0 into $s2 (save $a0) move $s3, $a1 # copy parameter $a1 into $s3 (save $a1) Outer loop move $s0, $zero# i = 0 for1tst: slt$t0, $s0, $s3 # reg $t0 = 0 if $s0 Š $s3 (i Š n) beq $t0, $zero, exit1# go to exit1 if $s0 Š $s3 (i Š n) Inner loop addi $s1, $s0, –1# j = i – 1 for2tst: slti$t0, $s1, 0 # reg $t0 = 1 if $s1 < 0 (j < 0) bne $t0, $zero, exit2# go to exit2 if $s1 < 0 (j < 0) sll $t1, $s1, 2# reg $t1 = j * 4 add $t2, $s2, $t1# reg $t2 = v + (j * 4) lw $t3, 0($t2)# reg $t3 = v[j] lw $t4, 4($t2)# reg $t4 = v[j + 1] slt $t0, $t4, $t3 # reg $t0 = 0 if $t4 Š $t3 beq $t0, $zero, exit2# go to exit2 if $t4 Š $t3 Pass parameters and call move $a0, $s2 # 1st parameter of swap is v (old $a0) move $a1, $s1 # 2nd parameter of swap is j jal swap # swap code shown in Figure 2.25 Inner loop addi $s1, $s1, –1# j –= 1 j for2tst # jump to test of inner loop Outer loop exit2: addi $s0, $s0, 1 # i += 1 j for1tst # jump to test of outer loop Restoring registers exit1: lw $s0, 0($sp) # restore $s0 from stack lw $s1, 4($sp)# restore $s1 from stack lw $s2, 8($sp)# restore $s2 from stack lw $s3,12($sp) # restore $s3 from stack lw $ra,16($sp) # restore $ra from stack addi $sp,$sp, 20 # restore stack pointer Procedure return jr $ra # return to calling routine FIGURE 2.27 MIPS assembly version of procedure sort in Figure 2.26. 2.13 A C Sort Example to Put It All Together 155
clipped_hennesy_Page_153_Chunk5510
156 Chapter 2 Instructions: Language of the Computer Figure 2.28 shows the impact of compiler optimization on sort program perfor­ mance, compile time, clock cycles, instruction count, and CPI. Note that unopti­ mized code has the best CPI, and O1 optimization has the lowest instruction count, but O3 is the fastest, reminding us that time is the only accurate measure of program performance. Figure 2.29 compares the impact of programming languages, compilation versus interpretation, and algorithms on performance of sorts. The fourth col­ umn shows that the unoptimized C program is 8.3 times faster than the inter­ preted Java code for Bubble Sort. Using the JIT compiler makes Java 2.1 times faster than the unoptimized C and within a factor of 1.13 of the highest optimized C code. ( Section 2.15 on the CD gives more details on inter­pretation versus compilation of Java and the Java and MIPS code for Bubble Sort.) The ratios aren’t as close for Quicksort in Column 5, presumably because it is harder to amortize the cost of runtime compilation over the shorter execu­tion time. The last column demonstrates the impact of a better algorithm, offer­ing three orders of magnitude a performance increases by when sorting 100,000 items. Even comparing interpreted Java in Column 5 to the C compiler at highest optimization in Column 4, Quicksort beats Bubble Sort by a factor of 50 (0.05 × 2468, or 123 times faster than the unoptimized C code versus 2.41 times faster). Elaboration: The MIPS compilers always save room on the stack for the arguments in case they need to be stored, so in reality they always decrement $sp by 16 to make room for all four argument registers (16 bytes). One reason is that C provides a vararg option that allows a pointer to pick, say, the third argument to a procedure. When the compiler encounters the rare vararg, it copies the four argument registers onto the stack into the four reserved locations. gcc optimization Relative performance Clock cycles (millions) Instruction count (millions) CPI None 1.00 158,615 114,938 1.38 O1 (medium) 2.37 66,990 37,470 1.79 O2 (full) 2.38 66,521 39,993 1.66 O3 (procedure integration) 2.41 65,747 44,993 1.46 FIGURE 2.28 Comparing performance, instruction count, and CPI using compiler optimi­ zation for Bubble Sort. The programs sorted 100,000 words with the array initialized to random values. These programs were run on a Pentium 4 with a clock rate of 3.06 GHz and a 533 MHz system bus with 2 GB of PC2100 DDR SDRAM. It used Linux version 2.4.20. Understanding Program Performance
clipped_hennesy_Page_154_Chunk5511
2.14 Arrays versus Pointers A challenge for any new C programmer is understanding pointers. Comparing assembly code that uses arrays and array indices to the assembly code that uses pointers offers insights about pointers. This section shows C and MIPS assembly versions of two procedures to clear a sequence of words in memory: one using array indices and one using pointers. Figure 2.30 shows the two C procedures. The purpose of this section is to show how pointers map into MIPS instructions, and not to endorse a dated programming style. We’ll see the impact of modern com­ piler optimization on these two procedures at the end of the section. Array Version of Clear Let’s start with the array version, clear1, focusing on the body of the loop and ignoring the procedure linkage code. We assume that the two parameters array and size are found in the registers $a0 and $a1, and that i is allocated to register $t0. The initialization of i, the first part of the for loop, is straightforward: move $t0,$zero # i = 0 (register $t0 = 0) To set array[i] to 0 we must first get its address. Start by multiplying i by 4 to get the byte address: loop1: sll $t1,$t0,2 # $t1 = i * 4 Since the starting address of the array is in a register, we must add it to the index to get the address of array[i] using an add instruction: add $t2,$a0,$t1 # $t2 = address of array[i] Finally, we can store 0 in that address: Language Execution method Optimization Bubble Sort relative performance Quicksort relative performance Speedup Quicksort vs. Bubble Sort C Compiler None 1.00 1.00 2468 Compiler O1 2.37 1.50 1562 Compiler O2 2.38 1.50 1555 Compiler O3 2.41 1.91 1955 Java Interpreter – 0.12 0.05 1050 JIT compiler – 2.13 0.29 338 FIGURE 2.29 Performance of two sort algorithms in C and Java using interpretation and optimizing compilers relative to unoptimized C version. The last column shows the advantage in performance of Quicksort over Bubble Sort for each language and execution option. These programs were run on the same system as Figure 2.28. The JVM is Sun version 1.3.1, and the JIT is Sun Hotspot version 1.3.1. 2.14 Arrays versus Pointers 157
clipped_hennesy_Page_155_Chunk5512
158 Chapter 2 Instructions: Language of the Computer sw $zero, 0($t2) # array[i] = 0 This instruction is the end of the body of the loop, so the next step is to increment i: addi $t0,$t0,1 # i = i + 1 The loop test checks if i is less than size: slt $t3,$t0,$a1 # $t3 = (i < size) bne $t3,$zero,loop1 # if (i < size) go to loop1 We have now seen all the pieces of the procedure. Here is the MIPS code for clearing an array using indices: move $t0,$zero # i = 0 loop1: sll $t1,$t0,2 # $t1 = i * 4 add $t2,$a0,$t1 # $t2 = address of array[i] sw $zero, 0($t2) # array[i] = 0 addi $t0,$t0,1 # i = i + 1 slt $t3,$t0,$a1 # $t3 = (i < size) bne $t3,$zero,loop1 # if (i < size) go to loop1 (This code works as long as size is greater than 0; ANSI C requires a test of size before the loop, but we’ll skip that legality here.) clear1(int array[], int size) { int i; for (i = 0; i < size; i += 1) array[i] = 0; } clear2(int *array, int size) { int *p; for (p = &array[0]; p < &array[size]; p = p + 1) *p = 0; } FIGURE 2.30 Two C procedures for setting an array to all zeros. Clear1 uses indices, while clear2 uses pointers. The second procedure needs some explanation for those unfamiliar with C. The address of a variable is indicated by &, and the object pointed to by a pointer is indicated by *. The declara- tions declare that array and p are pointers to integers. The first part of the for loop in clear2 assigns the address of the first element of array to the pointer p. The second part of the for loop tests to see if the pointer is pointing beyond the last element of array. Incrementing a pointer by one, in the last part of the for loop, means moving the pointer to the next sequential object of its declared size. Since p is a pointer to integers, the compiler will generate MIPS instructions to increment p by four, the number of bytes in a MIPS integer. The assignment in the loop places 0 in the object pointed to by p.
clipped_hennesy_Page_156_Chunk5513
Pointer Version of Clear The second procedure that uses pointers allocates the two parameters array and size to the registers $a0 and $a1 and allocates p to register $t0. The code for the second procedure starts with assigning the pointer p to the address of the first element of the array: move $t0,$a0 # p = address of array[0] The next code is the body of the for loop, which simply stores 0 into p: loop2: sw $zero,0($t0) # Memory[p] = 0 This instruction implements the body of the loop, so the next code is the iteration increment, which changes p to point to the next word: addi $t0,$t0,4 # p = p + 4 Incrementing a pointer by 1 means moving the pointer to the next sequential object in C. Since p is a pointer to integers, each of which uses 4 bytes, the compiler increments p by 4. The loop test is next. The first step is calculating the address of the last element of array. Start with multiplying size by 4 to get its byte address: sll $t1,$a1,2 # $t1 = size * 4 and then we add the product to the starting address of the array to get the address of the first word after the array: add $t2,$a0,$t1 # $t2 = address of array[size] The loop test is simply to see if p is less than the last element of array: slt $t3,$t0,$t2 # $t3 = (p<&array[size]) bne $t3,$zero,loop2 # if (p<&array[size]) go to loop2 With all the pieces completed, we can show a pointer version of the code to zero an array: move $t0,$a0 # p = address of array[0] loop2:sw$zero,0($t0) # Memory[p] = 0 addi $t0,$t0,4 # p = p + 4 sll $t1,$a1,2 # $t1 = size * 4 add $t2,$a0,$t1 # $t2 = address of array[size] slt $t3,$t0,$t2 # $t3 = (p<&array[size]) bne $t3,$zero,loop2 # if (p<&array[size]) go to loop2 As in the first example, this code assumes size is greater than 0. 2.14 Arrays versus Pointers 159
clipped_hennesy_Page_157_Chunk5514
160 Chapter 2 Instructions: Language of the Computer Note that this program calculates the address of the end of the array in every iteration of the loop, even though it does not change. A faster version of the code moves this calculation outside the loop: move $t0,$a0 # p = address of array[0] sll $t1,$a1,2 # $t1 = size * 4 add $t2,$a0,$t1 # $t2 = address of array[size] loop2:sw$zero,0($t0) # Memory[p] = 0 addi $t0,$t0,4 # p = p + 4 slt $t3,$t0,$t2 # $t3 = (p<&array[size]) bne $t3,$zero,loop2 # if (p<&array[size]) go to loop2 Comparing the Two Versions of Clear Comparing the two code sequences side by side illustrates the difference between array indices and pointers (the changes introduced by the pointer version are highlighted): The version on the left must have the “multiply” and add inside the loop because i is incremented and each address must be recalculated from the new index. The memory pointer version on the right increments the pointer p directly. The pointer version moves them outside the loop, thereby reducing the instruc­ tions executed per iteration from 6 to 4. This manual optimization corresponds to the compiler optimization of strength reduction (shift instead of multiply) and induction variable elimina­tion (eliminating array address calculations within loops). Section 2.15 on the CD describes these two and many other optimizations. Elaboration: As mentioned ealier, a C compiler would add a test to be sure that size is greater than 0. One way would be to add a jump just before the first instruction of the loop to the slt instruction. move $t0,$zero # i = 0 loop1: sll $t1,$t0,2 # $t1 = i * 4 add $t2,$a0,$t1 # $t2 = &array[i] sw $zero, 0($t2) # array[i] = 0 addi $t0,$t0,1 # i = i + 1 slt $t3,$t0,$a1 # $t3 = (i < size) bne $t3,$zero,loop1# if () go to loop1 move $t0,$a0 # p = & array[0] sll $t1,$a1,2 # $t1 = size * 4 add $t2,$a0,$t1 # $t2 = &array[size] loop2: sw $zero,0($t0) # Memory[p] = 0 addi $t0,$t0,4 # p = p + 4 slt $t3,$t0,$t2 # $t3=(p<&array[size]) bne $t3,$zero,loop2# if () go to loop2
clipped_hennesy_Page_158_Chunk5515
People used to be taught to use pointers in C to get greater efficiency than that available with arrays: “Use pointers, even if you can’t understand the code.” Mod­ ern optimizing compilers can produce code for the array version that is just as good. Most programmers today prefer that the compiler do the heavy lifting. Advanced Material: Compiling C and Interpreting Java This section gives a brief overview of how the C compiler works and how Java is executed. Be­cause the compiler will significantly affect the performance of a com- puter, understanding compiler technology today is critical to understanding per- formance. Keep in mind that the subject of compiler construction is usually taught in a one- or two-semester course, so our introduction will necessarily only touch on the basics. The second part of this section is for readers interested in seeing how an objected oriented language like Java executes on a MIPS architecture. It shows the Java bytecodes used for interpretation and the MIPS code for the Java version of some of the C segments in prior sections, including Bubble Sort. It covers both the Java Virtual Machine and JIT compilers. The rest of this section is on the CD. 2.16 Real Stuff: ARM Instructions ARM is the most popular instruction set architecture for embedded devices, with more than three billion devices per year using ARM. Standing originally for the Acorn RISC Machine, later changed to Advanced RISC Machine, ARM came out the same year as MIPS and followed similar philosophies. Figure 2.31 lists the similar­ities. The principle difference is that MIPS has more registers and ARM has more addressing modes. There is a similar core of instruction sets for arithmetic-logical and data trans­fer instructions for MIPS and ARM, as Figure 2.32 shows. Addressing Modes Figure 2.33 shows the data addressing modes supported by ARM. Unlike MIPS, ARM does not reserve a register to contain 0. Although MIPS has just three simple data addressing modes (see Figure 2.18), ARM has nine, including fairly complex calculations. For example, ARM has an addressing mode that can shift one register Understanding Program Performance 2.15 object oriented language A programming language that is oriented around objects rather than actions, or data versus logic. 2.16 Real Stuff: ARM Instructions 161
clipped_hennesy_Page_159_Chunk5516
162 Chapter 2 Instructions: Language of the Computer ARM MIPS Date announced 1985 1985 Instruction size (bits) 32 32 Address space (size, model) 32 bits, flat 32 bits, flat Data alignment Aligned Aligned Data addressing modes 9 3 Integer registers (number, model, size) 15 GPR ´ 32 bits 31 GPR ´ 32 bits I/O Memory mapped Memory mapped FIGURE 2.31 Similarities in ARM and MIPS instruction sets. Instruction name ARM MIPS Register-register Add add addu, addiu Add (trap if overflow) adds; swivs add Subtract sub subu Subtract (trap if overflow) subs; swivs sub Multiply mul mult, multu Divide — div, divu And and and Or orr or Xor eor xor Load high part register — lui Shift left logical lsl1 sllv, sll Shift right logical lsr1 srlv, srl Shift right arithmetic asr1 srav, sra Compare cmp, cmn, tst, teq slt/i, slt/iu Data transfer Load byte signed ldrsb lb Load byte unsigned ldrb lbu Load halfword signed ldrsh lh Load halfword unsigned ldrh lhu Load word ldr lw Store byte strb sb Store halfword strh sh Store word str sw Read, write special registers mrs, msr move Atomic Exchange swp, swpb ll;sc FIGURE 2.32 ARM register-register and data transfer instructions equivalent to MIPS core. Dashes mean the operation is not available in that architecture or not synthesized in a few instruc­ tions. If there are several choices of instructions equivalent to the MIPS core, they are separated by commas. ARM includes shifts as part of every data operation instruction, so the shifts with superscript 1 are just a variation of a move instruction, such as lsr1. Note that ARM has no divide instruction.
clipped_hennesy_Page_160_Chunk5517
by any amount, add it to the other registers to form the address, and then update one register with this new address. Compare and Conditional Branch MIPS uses the contents of registers to evaluate conditional branches. ARM uses the traditional four condition code bits stored in the program status word: neg­ative, zero, carry, and overflow. They can be set on any arithmetic or logical instruction; unlike earlier architectures, this setting is optional on each instruc­ tion. An explicit option leads to fewer problems in a pipelined implementation. ARM uses conditional branches to test condition codes to determine all possible unsigned and signed relations. CMP subtracts one operand from the other and the difference sets the condi­ tion codes. Compare negative (CMN) adds one operand to the other, and the sum sets the condition codes. TST performs logical AND on the two operands to set all condition codes but overflow, while TEQ uses exclusive OR to set the first three condition codes. One unusual feature of ARM is that every instruction has the option of execut­ ing conditionally, depending on the condition codes. Every instruction starts with a 4-bit field that determines whether it will act as a no operation instruction (nop) or as a real instruction, depending on the condition codes. Hence, conditional branches are properly con­sidered as conditionally executing the unconditional branch instruction. Condi­tional execution allows avoiding a branch to jump over a single instruction. It takes less code space and time to simply conditionally execute one instruction. Figure 2.34 shows the instruction formats for ARM and MIPS. The principal differences are the 4-bit conditional execution field in every instruction and the smaller register field, because ARM has half the number of registers. 2.16 Real Stuff: ARM Instructions 163 FIGURE 2.33 Summary of data addressing modes. ARM has separate register indirect and register + offset addressing modes, rather than just putting 0 in the offset of the latter mode. To get greater addressing range, ARM shifts the offset left 1 or 2 bits if the data size is halfword or word. Addressing mode ARM v.4 MIPS Register operand X X Immediate operand X X Register + offset (displacement or based) X X Register + register (indexed) X — Register + scaled register (scaled) X — Register + offset and update register X — Register + register and update register X — Autoincrement, autodecrement X — PC-relative data X —
clipped_hennesy_Page_161_Chunk5518
164 Chapter 2 Instructions: Language of the Computer Unique Features of ARM Figure 2.35 shows a few arithmetic-logical instructions not found in MIPS. Since it does not have a dedicated register for 0, it has separate opcodes to perform some operations that MIPS can do with $zero. In addition, ARM has support for multiword arithmetic. ARM’s 12-bit immediate field has a novel interpretation. The eight least- significant bits are zero-extended to a 32-bit value, then rotated right the number of bits specified in the first four bits of the field multiplied by two. One advantage is that this scheme can represent all powers of two in a 32-bit word. Whether this split actually catches more immediates than a simple 12-bit field would be an interesting study. Operand shifting is not limited to immediates. The second register of all arithmetic and logical processing operations has the option of being shifted before being operated on. The shift options are shift left logical, shift right logical, shift right arithmetic, and rotate right. FIGURE 2.34 Instruction formats, ARM, and MIPS. The differences result from whether the architecture has 16 or 32 registers. Register Constant Opcode ARM Register-register Opx4 31 28 27 28 27 28 27 28 27 19 16 15 16 15 16 15 16 15 16 15 11 12 4 3 0 Op8 Rs14 Rd4 Rs24 Opx8 Data transfer ARM Opx4 31 11 12 0 Op8 Rs14 Rd4 Const12 Branch ARM Jump/Call Opx4 31 23 24 0 Op4 Const24 ARM Opx4 31 23 24 0 Op4 Const24 MIPS 31 25 26 20 21 20 25 26 21 20 21 20 19 20 11 10 6 5 0 Const5 Rs15 Rs25 Rd5 Opx6 Op6 MIPS 31 0 Const16 Rs15 Rd5 Op6 MIPS 31 25 26 25 26 0 Rs15 Opx5/Rs25 Const16 Op6 31 0 Op6 MIPS Const26
clipped_hennesy_Page_162_Chunk5519
ARM also has instructions to save groups of registers, called block loads and stores. Under control of a 16-bit mask within the instructions, any of the 16 regis­ ters can be loaded or stored into memory in a single instruction. These instruc­tions can save and restore registers on procedure entry and return. These instructions can also be used for block memory copy, and today block copies are the most important use of this instruction. 2.17 Real Stuff: x86 Instructions Designers of instruction sets sometimes provide more powerful operations than those found in ARM and MIPS. The goal is generally to reduce the number of instructions executed by a program. The danger is that this reduction can occur at the cost of simplicity, increasing the time a program takes to execute because the instructions are slower. This slowness may be the result of a slower clock cycle time or of requiring more clock cycles than a simpler sequence. The path toward operation complexity is thus fraught with peril. To avoid these problems, designers have moved toward simpler instructions. Section 2.18 dem­ onstrates the pitfalls of complexity. Evolution of the Intel x86 ARM and MIPS were the vision of single small groups in 1985; the pieces of these architectures fit nicely together, and the whole architecture can be described suc­ cinctly. Such is not the case for the x86; it is the product of several independent groups who evolved the architecture over 30 years, adding new features to the original instruction set as someone might add clothing to a packed bag. Here are important x86 milestones. Beauty is altogether in the eye of the beholder. Margaret Wolfe Hungerford, Molly Bawn, 1877 2.17 Real Stuff: x86 Instructions 165 Name Definition ARM v.4 MIPS Load immediate Rd = Imm mov addi, $0, Not Rd = ~(Rs1) mvn nor, $0, Move Rd = Rs1 mov or, $0, Rotate right Rd = Rs i >> i Rd0. . . i–1 = Rs31–i. . . 31 ror And not Rd = Rs1 & ~(Rs2) bic Reverse subtract Rd = Rs2 - Rs1 rsb, rsc Support for multiword integer add CarryOut, Rd = Rd + Rs1 + OldCarryOut adcs — Support for multiword integer sub CarryOut, Rd = Rd – Rs1 + OldCarryOut sbcs — FIGURE 2.35 ARM arithmetic/logical instructions not found in MIPS.
clipped_hennesy_Page_163_Chunk5520
166 Chapter 2 Instructions: Language of the Computer ■ ■1978: The Intel 8086 architecture was announced as an assembly language– com­patible extension of the then successful Intel 8080, an 8-bit microproces­ sor. The 8086 is a 16-bit architecture, with all internal registers 16 bits wide. Unlike MIPS, the registers have dedicated uses, and hence the 8086 is not con­ sidered a general-purpose register architecture. ■ ■1980: The Intel 8087 floating-point coprocessor is announced. This archi­ tecture extends the 8086 with about 60 floating-point instructions. Instead of using registers, it relies on a stack (see Section 2.20 and Section 3.7). ■ ■1982: The 80286 extended the 8086 architecture by increasing the address space to 24 bits, by creating an elaborate memory-mapping and protection model (see Chapter 5), and by adding a few instructions to round out the instruction set and to manipulate the protection model. ■ ■1985: The 80386 extended the 80286 architecture to 32 bits. In addition to a 32-bit architecture with 32-bit registers and a 32-bit address space, the 80386 added new addressing modes and additional operations. The added instructions make the 80386 nearly a general-purpose register machine. The 80386 also added paging support in addition to segmented addressing (see Chapter 5). Like the 80286, the 80386 has a mode to execute 8086 programs without change. ■ ■1989–95: The subsequent 80486 in 1989, Pentium in 1992, and Pentium Pro in 1995 were aimed at higher performance, with only four instructions added to the user-visible instruction set: three to help with multiprocessing (Chapter 7) and a conditional move instruction. ■ ■1997: After the Pentium and Pentium Pro were shipping, Intel announced that it would expand the Pentium and the Pentium Pro architectures with MMX (Multi Media Extensions). This new set of 57 instructions uses the floating-point stack to accelerate multimedia and communication applica­ tions. MMX instructions typically operate on multiple short data elements at a time, in the tradition of single instruction, multiple data (SIMD) archi­ tectures (see Chapter 7). Pentium II did not introduce any new instructions. ■ ■1999: Intel added another 70 instructions, labeled SSE (Streaming SIMD Extensions) as part of Pentium III. The primary changes were to add eight separate registers, double their width to 128 bits, and add a single precision floating-point data type. Hence, four 32-bit floating-point operations can be performed in parallel. To improve memory performance, SSE includes cache prefetch instructions plus streaming store instructions that bypass the caches and write directly to memory. ■ ■2001: Intel added yet another 144 instructions, this time labeled SSE2. The new data type is double precision arithmetic, which allows pairs of 64-bit ­floating-point operations in parallel. Almost all of these 144 instructions are general-purpose register (GPR) A register that can be used for addresses or for data with virtually any ­instruction.
clipped_hennesy_Page_164_Chunk5521
versions of existing MMX and SSE instructions that operate on 64 bits of data in parallel. Not only does this change enable more multimedia opera­ tions, it gives the compiler a different target for floating-point operations than the unique stack architecture. Compilers can choose to use the eight SSE registers as floating-point registers like those found in other computers. This change boosted the floating-point performance of the Pentium 4, the first microprocessor to include SSE2 instructions. ■ ■2003: A company other than Intel enhanced the x86 architecture this time. AMD announced a set of architectural extensions to increase the address space from 32 to 64 bits. Similar to the transition from a 16- to 32-bit address space in 1985 with the 80386, AMD64 widens all registers to 64 bits. It also increases the number of registers to 16 and increases the number of 128-bit SSE regis­ters to 16. The primary ISA change comes from adding a new mode called long mode that redefines the execution of all x86 instructions with 64-bit addresses and data. To address the larger number of registers, it adds a new prefix to instructions. Depending how you count, long mode also adds four to ten new instructions and drops 27 old ones. PC-relative data addressing is another extension. AMD64 still has a mode that is identical to x86 (legacy mode) plus a mode that restricts user programs to x86 but allows operating systems to use AMD64 (compatibility mode). These modes allow a more graceful transition to 64-bit addressing than the HP/Intel IA-64 architecture. ■ ■2004: Intel capitulates and embraces AMD64, relabeling it Extended Memory 64 Technology (EM64T). The major difference is that Intel added a 128-bit atomic compare and swap instruction, which probably should have been included in AMD64. At the same time, Intel announced another generation of media extensions. SSE3 adds 13 instructions to support complex arithmetic, graphics operations on arrays of structures, video encoding, floating-point conversion, and thread synchronization (see Section 2.11). AMD will offer SSE3 in subsequent chips and it will almost certainly add the missing atomic swap instruction to AMD64 to maintain binary compatibility with Intel. ■ ■2006: Intel announces 54 new instructions as part of the SSE4 instruction set extensions. These extensions perform tweaks like sum of absolute differences, dot products for arrays of structures, sign or zero extension of narrow data to wider sizes, population count, and so on. They also added support for virtual machines (see Chapter 5). ■ ■2007: AMD announces 170 instructions as part of SSE5, including 46 instruc­ tions of the base instruction set that adds three operand instructions like MIPS. ■ ■2008: Intel announces the Advanced Vector Extension that expands the SSE register width from 128 to 256 bits, thereby redefining about 250 instructions and adding 128 new instructions. 2.17 Real Stuff: x86 Instructions 167
clipped_hennesy_Page_165_Chunk5522
168 Chapter 2 Instructions: Language of the Computer This history illustrates the impact of the “golden handcuffs” of compatibility on the x86, as the existing software base at each step was too important to jeopar­dize with significant architectural changes. If you looked over the life of the x86, on average the architecture has been extended by one instruction per month! Whatever the artistic failures of the x86, keep in mind that there are more instances of this architectural family on desktop computers than of any other architecture, increasing by more than 250 million per year. Nevertheless, this checkered ancestry has led to an architecture that is difficult to explain and impossible to love. Brace yourself for what you are about to see! Do not try to read this section with the care you would need to write x86 programs; the goal instead is to give you familiarity with the strengths and weaknesses of the world’s most popular desktop architecture. Rather than show the entire 16-bit and 32-bit instruction set, in this section we concentrate on the 32-bit subset that originated with the 80386, as this portion of the architecture is what is used today. We start our explanation with the registers and addressing modes, move on to the integer operations, and conclude with an examination of instruction encoding. x86 Registers and Data Addressing Modes The registers of the 80386 show the evolution of the instruction set (Figure 2.36). The 80386 extended all 16-bit registers (except the segment registers) to 32 bits, prefixing an E to their name to indicate the 32-bit version. We’ll refer to them generically as GPRs (general-purpose registers). The 80386 contains only eight GPRs. This means MIPS programs can use four times as many and ARM twice as many. Figure 2.37 shows the arithmetic, logical, and data transfer instructions are two- operand instructions. There are two important differences here. The x86 arith- metic and logical instructions must have one operand act as both a source and a destination; ARM and MIPS allow separate registers for source and destination. This restriction puts more pressure on the limited registers, since one source regis- ter must be modified. The second important difference is that one of the operands can be in memory. Thus, virtually any instruction may have one operand in mem­ ory, unlike ARM and MIPS. Data memory-addressing modes, described in detail below, offer two sizes of addresses within the instruction. These so-called displacements can be 8 bits or 32 bits. Although a memory operand can use any addressing mode, there are restric­ tions on which registers can be used in a mode. Figure 2.38 shows the x86 address­ ing modes and which GPRs cannot be used with each mode, as well as how to get the same effect using MIPS instructions. x86 Integer Operations The 8086 provides support for both 8-bit (byte) and 16-bit (word) data types. The 80386 adds 32-bit addresses and data (double words) in the x86. (AMD64 adds 64-bit addresses and data, called quad words; we’ll stick to the 80386 in this section.) The data type distinctions apply to register opera­tions as well as memory accesses.
clipped_hennesy_Page_166_Chunk5523
Source/destination operand type Second source operand Register Register Register Immediate Register Memory Memory Register Memory Immediate FIGURE 2.37 Instruction types for the arithmetic, logical, and data transfer instructions. The x86 allows the combinations shown. The only restriction is the absence of a memory-­memory mode. Immediates may be 8, 16, or 32 bits in length; a register is any one of the 14 major registers in Figure 2.36 (not EIP or EFLAGS). GPR 0 GPR 1 GPR 2 GPR 3 GPR 4 GPR 5 GPR 6 GPR 7 Code segment pointer Stack segment pointer (top of stack) Data segment pointer 0 Data segment pointer 1 Data segment pointer 2 Data segment pointer 3 Instruction pointer (PC) Condition codes Use 0 31 Name EAX ECX EDX EBX ESP EBP ESI EDI CS SS DS ES FS GS EIP EFLAGS FIGURE 2.36 The 80386 register set. Starting with the 80386, the top eight registers were extended to 32 bits and could also be used as general-purpose registers. 2.17 Real Stuff: x86 Instructions 169
clipped_hennesy_Page_167_Chunk5524
170 Chapter 2 Instructions: Language of the Computer Mode Description Register restrictions MIPS equivalent Register indirect Address is in a register. Not ESP or EBP lw $s0,0($s1) Based mode with 8- or 32-bit displacement Address is contents of base register plus displacement. Not ESP lw $s0,100($s1) # <= 16­bit # displacement Base plus scaled index The address is Base + (2Scale x Index) where Scale has the value 0, 1, 2, or 3. Base: any GPR Index: not ESP mul $t0,$s2,4 add $t0,$t0,$s1 lw $s0,0($t0) Base plus scaled index with 8- or 32-bit displacement The address is Base + (2Scale x Index) + displacement where Scale has the value 0, 1, 2, or 3. Base: any GPR Index: not ESP mul $t0,$s2,4 add $t0,$t0,$s1 lw $s0,100($t0) # ð16­bit # displacement FIGURE 2.38 x86 32-bit addressing modes with register restrictions and the equivalent MIPS code. The Base plus Scaled Index addressing mode, not found in ARM or MIPS, is included to avoid the multiplies by 4 (scale factor of 2) to turn an index in a register into a byte address (see Figures 2.25 and 2.27). A scale factor of 1 is used for 16-bit data, and a scale factor of 3 for 64-bit data. A scale factor of 0 means the address is not scaled. If the displacement is longer than 16 bits in the second or fourth modes, then the MIPS equivalent mode would need two more instructions: a lui to load the upper 16 bits of the displacement and an add to sum the upper address with the base register $s1. (Intel gives two dif­ferent names to what is called Based addressing mode—Based and Indexed—but they are essentially identical and we combine them here.) Almost every operation works on both 8-bit data and on one longer data size. That size is determined by the mode and is either 16 bits or 32 bits. Clearly, some programs want to operate on data of all three sizes, so the 80386 architects provided a convenient way to specify each version without expanding code size significantly. They decided that either 16-bit or 32-bit data dominates most programs, and so it made sense to be able to set a default large size. This default data size is set by a bit in the code segment register. To override the default data size, an 8-bit prefix is attached to the instruction to tell the machine to use the other large size for this instruction. The prefix solution was borrowed from the 8086, which allows multiple prefixes to modify instruction behavior. The three original prefixes override the default seg­ ment register, lock the bus to support synchronization (see Section 2.11), or repeat the following instruction until the register ECX counts down to 0. This last prefix was intended to be paired with a byte move instruction to move a variable number of bytes. The 80386 also added a prefix to override the default address size. The x86 integer operations can be divided into four major classes: 1. Data movement instructions, including move, push, and pop 2. Arithmetic and logic instructions, including test, integer, and decimal arith- metic operations 3. Control flow, including conditional branches, unconditional jumps, calls, and returns 4. String instructions, including string move and string compare
clipped_hennesy_Page_168_Chunk5525
The first two categories are unremarkable, except that the arithmetic and logic instruction operations allow the destination to be either a register or a memory location. Figure 2.39 shows some typical x86 instructions and their functions. Instruction Function je name if equal(condition code) {EIP=name}; EIP–128 <= name < EIP+128 jmp name EIP=name call name SP=SP–4; M[SP]=EIP+5; EIP=name; movw EBX,[EDI+45] EBX=M[EDI+45] push ESI SP=SP–4; M[SP]=ESI pop EDI EDI=M[SP]; SP=SP+4 add EAX,#6765 EAX= EAX+6765 test EDX,#42 Set condition code (flags) with EDX and 42 movsl M[EDI]=M[ESI]; EDI=EDI+4; ESI=ESI+4 FIGURE 2.39 Some typical x86 instructions and their functions. A list of frequent operations appears in Figure 2.40. The CALL saves the EIP of the next instruction on the stack. (EIP is the Intel PC.) Conditional branches on the x86 are based on condition codes or flags, like ARM. Condition codes are set as a side effect of an operation; most are used to compare the value of a result to 0. Branches then test the condition codes. PC- relative branch addresses must be specified in the number of bytes, since unlike ARM and MIPS, 80386 instructions are not all 4 bytes in length. String instructions are part of the 8080 ancestry of the x86 and are not com­ monly executed in most programs. They are often slower than equivalent software routines (see the fallacy on page 174). Figure 2.40 lists some of the integer x86 instructions. Many of the instructions are available in both byte and word formats. x86 Instruction Encoding Saving the worst for last, the encoding of instructions in the 80386 is complex, with many different instruction formats. Instructions for the 80386 may vary from 1 byte, when there are no operands, up to 15 bytes. Figure 2.41 shows the instruction for­mat for several of the example instructions in Figure 2.39. The opcode byte usually contains a bit saying whether the operand is 8 bits or 32 bits. For some instructions, the opcode may include the addressing mode and the register; this is true in many instructions that have the form “register = register op immediate.” Other instructions use a “postbyte” or extra opcode byte, labeled “mod, reg, r/m,” which contains the addressing mode informa­tion. This postbyte is used for many of the instructions that address memory. The base plus scaled index mode uses a second postbyte, labeled “sc, index, base.” 2.17 Real Stuff: x86 Instructions 171
clipped_hennesy_Page_169_Chunk5526
172 Chapter 2 Instructions: Language of the Computer Instruction Meaning Control Conditional and unconditional branches jnz, jz Jump if condition to EIP + 8-bit offset; JNE (for JNZ), JE (for JZ) are alternative names jmp Unconditional jump—8-bit or 16-bit offset call Subroutine call—16-bit offset; return address pushed onto stack ret Pops return address from stack and jumps to it loop Loop branch—decrement ECX; jump to EIP + 8-bit displacement if ECX ≠ 0 Data transfer Move data between registers or between register and memory move Move between two registers or between register and memory push, pop Push source operand on stack; pop operand from stack top to a register les Load ES and one of the GPRs from memory Arithmetic, logical Arithmetic and logical operations using the data registers and memory add, sub Add source to destination; subtract source from destination; register-memory format cmp Compare source and destination; register-memory format shl, shr, rcr Shift left; shift logical right; rotate right with carry condition code as fill cbw Convert byte in eight rightmost bits of EAX to 16-bit word in right of EAX test Logical AND of source and destination sets condition codes inc, dec Increment destination, decrement destination or, xor Logical OR; exclusive OR; register-memory format String Move between string operands; length given by a repeat prefix movs Copies from string source to destination by incrementing ESI and EDI; may be repeated lods Loads a byte, word, or doubleword of a string into the EAX register FIGURE 2.40 Some typical operations on the x86. Many operations use register-memory for­mat, where either the source or the destination may be memory and the other may be a register or immedi­ate operand. Figure 2.42 shows the encoding of the two postbyte address specifiers for both 16-bit and 32-bit mode. Unfortunately, to understand fully which registers and which addressing modes are available, you need to see the encoding of all address­ ing modes and sometimes even the encoding of the instructions. x86 Conclusion Intel had a 16-bit microprocessor two years before its competitors’ more elegant architectures, such as the Motorola 68000, and this head start led to the selection of the 8086 as the CPU for the IBM PC. Intel engineers generally acknowledge that the x86 is more difficult to build than computers like ARM and MIPS, but the large
clipped_hennesy_Page_170_Chunk5527
FIGURE 2.41 Typical x86 instruction formats. Figure 2.42 shows the encoding of the postbyte. Many instructions contain the 1-bit field w, which says whether the operation is a byte or a double word. The d field in MOV is used in instructions that may move to or from memory and shows the direction of the move. The ADD instruction requires 32 bits for the immediate field, because in 32-bit mode, the immediates are either 8 bits or 32 bits. The immediate field in the TEST is 32 bits long because there is no 8-bit immediate for test in 32-bit mode. Overall, instructions may vary from 1 to 17 bytes in length. The long length comes from extra 1-byte prefixes, having both a 4-byte immediate and a 4-byte displacement address, using an opcode of 2 bytes, and using the scaled index mode specifier, which adds another byte. a. JE EIP + displacement b. CALL c. MOV EBX, [EDI + 45] d. PUSH ESI e. ADD EAX, #6765 f. TEST EDX, #42 Immediate Postbyte TEST ADD PUSH MOV CALL JE w w Immediate Reg Reg w d Displacement r/m Postbyte Offset Displacement Condi- tion 4 4 8 8 32 6 8 1 1 8 5 3 4 32 3 1 7 32 1 8 market means AMD and Intel can afford more resources to help overcome the added complexity. What the x86 lacks in style, it makes up for in quantity, making it beauti­ful from the right perspective. Its saving grace is that the most frequently used x86 architectural compo- nents are not too difficult to implement, as AMD and Intel have demonstrated by rapidly improving performance of integer programs since 1978. To get that performance, compilers must avoid the portions of the architecture that are hard to implement fast. 2.17 Real Stuff: x86 Instructions 173
clipped_hennesy_Page_171_Chunk5528
174 Chapter 2 Instructions: Language of the Computer 2.18 Fallacies and Pitfalls Fallacy: More powerful instructions mean higher performance. Part of the power of the Intel x86 is the prefixes that can modify the execution of the following instruction. One prefix can repeat the following instruction until a counter counts down to 0. Thus, to move data in memory, it would seem that the natural instruction sequence is to use move with the repeat prefix to perform 32-bit memory-to-memory moves. An alternative method, which uses the standard instructions found in all com­ puters, is to load the data into the registers and then store the registers back to memory. This second version of this program, with the code replicated to reduce loop overhead, copies at about 1.5 times faster. A third version, which uses the larger floating-point registers instead of the integer registers of the x86, copies at about 2.0 times faster than the complex move instruction. Fallacy: Write in assembly language to obtain the highest performance. At one time compilers for programming languages produced naïve instruction sequences; the increasing sophistication of compilers means the gap between compiled code and code produced by hand is closing fast. In fact, to compete with current compilers, the assembly language programmer needs to under­stand the concepts in Chapters 4 and 5 thoroughly (processor pipelining and memory hierarchy). reg w = 0 w = 1 r/m mod = 0 mod = 1 mod = 2 mod = 3 16b 32b 16b 32b 16b 32b 16b 32b 0 AL AX EAX 0 addr=BX+SI =EAX same same same same same 1 CL CX ECX 1 addr=BX+DI =ECX addr as addr as addr as addr as as 2 DL DX EDX 2 addr=BP+SI =EDX mod=0 mod=0 mod=0 mod=0 reg 3 BL BX EBX 3 addr=BP+SI =EBX + disp8 + disp8 + disp16 + disp32 field 4 AH SP ESP 4 addr=SI =(sib) SI+disp8 (sib)+disp8 SI+disp8 (sib)+disp32 “ 5 CH BP EBP 5 addr=DI =disp32 DI+disp8 EBP+disp8 DI+disp16 EBP+disp32 “ 6 DH SI ESI 6 addr=disp16 =ESI BP+disp8 ESI+disp8 BP+disp16 ESI+disp32 “ 7 BH DI EDI 7 addr=BX =EDI BX+disp8 EDI+disp8 BX+disp16 EDI+disp32 “ FIGURE 2.42 The encoding of the first address specifier of the x86: mod, reg, r/m. The first four columns show the encoding of the 3-bit reg field, which depends on the w bit from the opcode and whether the machine is in 16-bit mode (8086) or 32-bit mode (80386). The remaining columns explain the mod and r/m fields. The meaning of the 3-bit r/m field depends on the value in the 2-bit mod field and the address size. Basically, the registers used in the address calculation are listed in the sixth and seventh columns, under mod = 0, with mod = 1 adding an 8-bit displacement and mod = 2 adding a 16-bit or 32-bit displacement, depending on the address mode. The exceptions are 1) r/m = 6 when mod = 1 or mod = 2 in 16-bit mode selects BP plus the displacement; 2) r/m = 5 when mod = 1 or mod = 2 in 32-bit mode selects EBP plus displacement; and 3) r/m = 4 in 32-bit mode when mod does not equal 3, where (sib) means use the scaled index mode shown in Figure 2.38. When mod = 3, the r/m field indicates a reg­ister, using the same encoding as the reg field combined with the w bit.
clipped_hennesy_Page_172_Chunk5529
This battle between compilers and assembly language coders is one situa­tion in which humans are losing ground. For example, C offers the program­mer a chance to give a hint to the compiler about which variables to keep in registers versus spilled to memory. When compilers were poor at register allocation, such hints were vital to performance. In fact, some old C text­books spent a fair amount of time giving examples that effectively use regis­ter hints. Today’s C compilers generally ignore such hints, because the compiler does a better job at allocation than the programmer does. Even if writing by hand resulted in faster code, the dangers of writing in assembly language are the longer time spent coding and debugging, the loss in portability, and the difficulty of maintaining such code. One of the few widely accepted axioms of software engineering is that coding takes longer if you write more lines, and it clearly takes many more lines to write a program in assembly language than in C or Java. Moreover, once it is coded, the next danger is that it will become a popular program. Such programs always live longer than expected, meaning that someone will have to update the code over several years and make it work with new releases of operating systems and new models of machines. Writing in higher-level language instead of assembly language not only allows future compilers to tailor the code to future machines, it also makes the software easier to maintain and allows the program to run on more brands of computers. Fallacy: The importance of commercial binary compatibility means successful instruction sets don’t change. While backwards binary compatibility is sacrosanct, Figure 2.43 shows that the x86 architecture has grown dramatically. The average is more than one instruc­tion per month over its 30-year lifetime! Pitfall: Forgetting that sequential word addresses in machines with byte addressing do not differ by one. Many an assembly language programmer has toiled over errors made by assuming that the address of the next word can be found by incrementing the address in a register by one instead of by the word size in bytes. Forewarned is forearmed! Pitfall: Using a pointer to an automatic variable outside its defining procedure. A common mistake in dealing with pointers is to pass a result from a ­procedure that includes a pointer to an array that is local to that procedure. Following the stack discipline in Figure 2.12, the memory that contains the local array will be reused as soon as the procedure returns. Pointers to automatic variables can lead to chaos. 2.18 Fallacies and Pitfalls 175
clipped_hennesy_Page_173_Chunk5530
176 Chapter 2 Instructions: Language of the Computer 2.19 Concluding Remarks The two principles of the stored-program computer are the use of instructions that are indistinguishable from numbers and the use of alterable memory for programs. These principles allow a single machine to aid environmental scientists, financial advisers, and novelists in their specialties. The selection of a set of instructions that the machine can understand demands a delicate balance among the number of instructions needed to execute a program, the number of clock cycles needed by an instruction, and the speed of the clock. As illustrated in this chapter, four design principles guide the authors of instruction sets in making that delicate balance: 1. Simplicity favors regularity. Regularity motivates many features of the MIPS instruction set: keeping all instructions a single size, always requiring three register operands in arithmetic instructions, and keeping the register fields in the same place in each instruction format. 2. Smaller is faster. The desire for speed is the reason that MIPS has 32 registers rather than many more. Less is more. Robert Browning, Andrea del Sarto, 1855 0 100 200 300 400 500 600 700 800 900 1000 1978 1980 1982 1984 1986 1988 1990 1992 1994 1996 1998 2000 2002 2004 2006 2008 Year Number of Instructions FIGURE 2.43 Growth of x86 instruction set over time. While there is clear technical value to some of these extensions, this rapid change also increases the difficulty for other companies to try to build compatible processors.
clipped_hennesy_Page_174_Chunk5531
3. Make the common case fast. Examples of making the common MIPS case fast include PC-relative addressing for conditional branches and immediate addressing for larger constant operands. 4. Good design demands good compromises. One MIPS example was the com­ promise between providing for larger addresses and constants in instruc­ tions and keeping all instructions the same length. Above this machine level is assembly language, a language that humans can read. The assembler translates it into the binary numbers that machines can understand, and it even “extends” the instruction set by creating symbolic instruc­tions that aren’t in the hardware. For instance, constants or addresses that are too big are broken into properly sized pieces, common variations of instructions are given their own name, and so on. Figure 2.44 lists the MIPS instructions we have covered so far, both real and pseudoinstructions. Each category of MIPS instructions is associated with constructs that appear in programming languages: ■ ■The arithmetic instructions correspond to the operations found in assign­ ment statements. ■ ■Data transfer instructions are most likely to occur when dealing with data structures like arrays or structures. ■ ■The conditional branches are used in if statements and in loops. ■ ■The unconditional jumps are used in procedure calls and returns and for case/switch statements. These instructions are not born equal; the popularity of the few dominates the many. For example, Figure 2.45 shows the popularity of each class of instructions for SPEC CPU2006. The varying popularity of instructions plays an important role in the chapters about datapath, control, and pipelining. After we explain computer arithmetic in Chapter 3, we reveal the rest of the MIPS instruction set architecture. 2.19 Concluding Remarks 177
clipped_hennesy_Page_175_Chunk5532
178 Chapter 2 Instructions: Language of the Computer MIPS instructions Name Format Pseudo MIPS Name Format add add R move move R subtract sub R multiply mult R add immediate addi I multiply immediate multi I load word lw I load immediate li I store word sw I branch less than blt I load half lh I branch less than or equal ble I load half unsigned lhu I store half sh I branch greater than bgt I load byte lb I branch greater than or equal bge I load byte unsigned lbu I store byte sb I load linked ll I store conditional sc I load upper immediate lui I and and R or or R nor nor R and immediate andi I or immediate ori I shift left logical sll R shift right logical srl R branch on equal beq I branch on not equal bne I set less than slt R set less than immediate slti I set less than immediate unsigned sltiu I jump j J jump register jr R jump and link jal J FIGURE 2.44 The MIPS instruction set covered so far, with the real MIPS instructions on the left and the pseudoinstructions on the right. Appendix B (Section B.10) describes the full MIPS architecture. Figure 2.1 shows more details of the MIPS architecture revealed in this chapter. The information given here is also found in Columns 1 and 2 of the MIPS Reference Data Card at the front of the book.
clipped_hennesy_Page_176_Chunk5533
Instruction class MIPS examples HLL correspondence Frequency Integer Ft. pt. Arithmetic add, sub, addi Operations in assignment statements 16% 48% Data transfer lw, sw, lb, lbu, lh, lhu, sb, lui References to data structures, such as arrays 35% 36% Logical and, or, nor, andi, ori, sll, srl 0perations in assignment statements 12% 4% Conditional branch beq, bne, slt, slti, sltiu If statements and loops 34% 8% Jump j, jr, jal Procedure calls, returns, and case/switch statements 2% 0% FIGURE 2.45 MIPS instruction classes, examples, correspondence to high-level program language constructs, and percent­age of MIPS instructions executed by category for the average SPEC CPU2006 benchmarks. Figure 3.26 in Chapter 3 shows average percent­age of the individual MIPS instructions executed. \ Historical Perspective and Further Reading This section surveys the history of instruction set architectures (ISAs) over time, and we give a short history of programming languages and compilers. ISAs include accumulator architectures, general-purpose register architectures, stack architectures, and a brief history of ARM and the x86. We also review the contro­versial subjects of high-level-language computer architectures and reduced instruction set computer architectures. The history of programming languages includes Fortran, Lisp, Algol, C, Cobol, Pascal, Simula, Smalltalk, C++, and Java, and the history of compilers includes the key milestones and the pioneers who achieved them. The rest of this section is on the CD. 2.21 Exercises Contributed by John Oliver of Cal Poly, San Luis Obispo, with contributions from Nicole Kaiyan (University of Adelaide) and Milos Prvulovic (Georgia Tech) Appendix B describes the MIPS simulator, which is helpful for these exercises. Although the simulator accepts pseudoinstructions, try not to use pseudo­ instructions for any exercises that ask you to produce MIPS code. Your goal should be to learn the real MIPS instruction set, and if you are asked to count instructions, your count should reflect the actual instructions that will be executed and not the pseudoinstructions. There are some cases where pseudoinstructions must be used (for example, the la instruction when an actual value is not known at assembly time). In many cases, 2.20 2.21 Exercises 179
clipped_hennesy_Page_177_Chunk5534
180 Chapter 2 Instructions: Language of the Computer they are quite convenient and result in more readable code (for example, the li and move instructions). If you choose to use pseudoinstructions for these reasons, please add a sentence or two to your solution stating which pseudoinstructions you have used and why. Exercise 2.1 The following problems explore translating from C to MIPS. Assume that the vari- ables f, g, h, and i are given and could be considered 32-bit integers as declared in a C program. a. f = g – h; b. f = g + (h - 5); 2.1.1 [5] <2.2> For the C statements above, what is the corresponding MIPS assembly code? Use a minimal number of MIPS assembly instructions. 2.1.2 [5] <2.2> For the C statements above, how many MIPS assembly instruc- tions are needed to perform the C statement? 2.1.3 [5] <2.2> If the variables f, g, h, and i have values 1, 2, 3, and 4, respec- tively, what is the end value of f? The following problems deal with translating from MIPS to C. Assume that the variables g, h, i, and j are given and could be considered 32-bit integers as declared in a C program. a. addi f, f, 4 b. add f, g, h add f, i, f 2.1.4 [5] <2.2> For the MIPS assembly instructions above, what is a correspond- ing C statement? 2.1.5 [5] <2.2> If the variables f, g, h, and i have values 1, 2, 3, and 4, respec- tively, what is the end value of f? Exercise 2.2 The following problems deal with translating from C to MIPS. Assume that the variables g, h, i, and j are given and could be considered 32-bit integers as declared in a C program.
clipped_hennesy_Page_178_Chunk5535
a. f = g – f; b. f = i + (h – 2); 2.2.1 [5] <2.2> For the C statements above, what is the corresponding MIPS assembly code? Use a minimal number of MIPS assembly instructions. 2.2.2 [5] <2.2> For the C statements above, how many MIPS assembly instruc- tions are needed to perform the C statement? 2.2.3 [5] <2.2> If the variables f, g, h, and i have values 1, 2, 3, and 4, respec- tively, what is the end value of f? The following problems deal with translating from MIPS to C. For the following exercise, assume that the variables g, h, i, and j are given and could be considered 32-bit integers as declared in a C program. a. addi f, f, 4 b. add f, g, h sub f, i, f 2.2.4 [5] <2.2> For the MIPS assembly instructions above, what is a correspond- ing C statement? 2.2.5 [5] <2.2> If the variables f, g, h, and i have values 1, 2, 3, and 4, respec- tively, what is the end value of f? Exercise 2.3 The following problems explore translating from C to MIPS. Assume that the vari- ables f and g are given and could be considered 32-bit integers as declared in a C program. a. f = –g – f; b. f = g + (–f – 5); 2.3.1 [5] <2.2> For the C statements above, what is the corresponding MIPS assembly code? Use a minimal number of MIPS assembly instructions. 2.3.2 [5] <2.2> For the C statements above, how many MIPS assembly instruc- tions are needed to perform the C statement? 2.3.3 [5] <2.2> If the variables f, g, h, i, and j have values 1, 2, 3, 4, and 5, respec- tively, what is the end value of f? 2.21 Exercises 181
clipped_hennesy_Page_179_Chunk5536
182 Chapter 2 Instructions: Language of the Computer The following problems deal with translating from MIPS to C. Assume that the variables g, h, i, and j are given and could be considered 32-bit integers as declared in a C program. a. addi f, f, –4 b. add i, g, h add f, i, f 2.3.4 [5] <2.2> For the MIPS statements above, what is a corresponding C statement? 2.3.5 [5] <2.2> If the variables f, g, h, and i have values 1, 2, 3, and 4, respec- tively, what is the end value of f? Exercise 2.4 The following problems deal with translating from C to MIPS. Assume that the variables f, g, h, i, and j are assigned to registers $s0, $s1, $s2, $s3, and$s4, respectively. Assume that the base address of the arrays A and B are in registers $s6 and $s7, respectively. a. f = –g – A[4]; b. B[8] = A[i–j]; 2.4.1 [10] <2.2, 2.3> For the C statements above, what is the corresponding MIPS assembly code? 2.4.2 [5] <2.2, 2.3> For the C statements above, how many MIPS assembly instructions are needed to perform the C statement? 2.4.3 [5] <2.2, 2.3> For the C statements above, how many different registers are needed to carry out the C statement? The following problems deal with translating from MIPS to C. Assume that the variables f, g, h, i, and j are assigned to registers $s0, $s1, $s2, $s3, and $s4, respectively. Assume that the base address of the arrays A and B are in registers $s6 and $s7, respectively. a. sll $s2, $s4, 1 add $s0, $s2, $s3 add $s0, $s0, $s1 b. sll $t0, $s0, 2 # $t0 = f * 4 add $t0, $s6, $t0 # $t0 = &A[f] sll $t1, $s1, 2 # $t1 = g * 4 add $t1, $s7, $t1 # $t1 = &B[g] lw $s0, 0($t0) # f = A[f] addi $t2, $t0, 4 lw $t0, 0($t2) add $t0, $t0, $s0 sw $t0, 0($t1)
clipped_hennesy_Page_180_Chunk5537
2.4.4 [10] <2.2, 2.3> For the MIPS assembly instructions above, what is the cor- responding C statement? 2.4.5 [5] <2.2, 2.3> For the MIPS assembly instructions above, rewrite the assem- bly code to minimize the number if MIPS instructions (if possible) needed to carry out the same function. 2.4.6 [5] <2.2, 2.3> How many registers are needed to carry out the MIPS assem- bly as written above? If you could rewrite the code above, what is the minimal number of registers needed? Exercise 2.5 In the following problems, we will be investigating memory operations in the con- text of an MIPS processor. The table below shows the values of an array stored in memory. Assume the base address of the array is stored in register $s6 and offset it with respect to the base address of the array. a. Address 20 24 28 32 34 Data 4 5 3 2 1 b. Address 24 38 32 36 40 Data 2 4 3 6 1 2.5.1 [10] <2.2, 2.3> For the memory locations in the table above, write C code to sort the data from lowest to highest, placing the lowest value in the smallest memory location shown in the figure. Assume that the data shown represents the C variable called Array, which is an array of type int, and that the first number in the array shown is the first element in the array. Assume that this particular machine is a byte-addressable machine and a word consists of four bytes. 2.5.2 [10] <2.2, 2.3> For the memory locations in the table above, write MIPS code to sort the data from lowest to highest, placing the lowest value in the smallest memory location. Use a minimum number of MIPS instructions. Assume the base address of Array is stored in register $s6. 2.5.3 [5] <2.2, 2.3> To sort the array above, how many instructions are required for the MIPS code? If you are not allowed to use the immediate field in lw and sw instructions, how many MIPS instructions do you need? 2.21 Exercises 183
clipped_hennesy_Page_181_Chunk5538
184 Chapter 2 Instructions: Language of the Computer The following problems explore the translation of hexadecimal numbers to other number formats. a. 0xabcdef12 b. 0x10203040 2.5.4 [5] <2.3> Translate the hexadecimal numbers above into decimal. 2.5.5 [5] <2.3> Show how the data in the table would be arranged in memory of a little-endian and a big-endian machine. Assume the data is stored starting at address 0. Exercise 2.6 The following problems deal with translating from C to MIPS. Assume that the vari- ables f, g, h, i, and j are assigned to registers $s0, $s1, $s2, $s3, and $s4, respec- tively. Assume that the base address of the arrays A and B are in registers $s6 and $s7, respectively. Assume that the elements of the arrays A and B are 4-byte words: a. f = f + A[2]; b. B[8] = A[i] + A[j]; 2.6.1 [10] <2.2, 2.3> For the C statements above, what is the corresponding MIPS assembly code? 2.6.2 [5] <2.2, 2.3> For the C statements above, how many MIPS assembly instructions are needed to perform the C statement? 2.6.3 [5] <2.2, 2.3> For the C statements above, how many registers are needed to carry out the C statement using MIPS assembly code? The following problems deal with translating from MIPS to C. Assume that the variables f, g, h, i, and j are assigned to registers $s0, $s1, $s2, $s3, and $s4, respectively. Assume that the base address of the arrays A and B are in registers $s6 and $s7, respectively. a. sub $s0, $s0, $s1 sub $s0, $s0, $s3 add $s0, $s0, $s1 b. addi $t0, $s6, 4 add $t1, $s6, $0 sw $t1, 0($t0) lw $t0, 0($t0) add $s0, $t1, $t0
clipped_hennesy_Page_182_Chunk5539
2.6.4 [5] <2.2, 2.3> For the MIPS assembly instructions above, what is the corresponding C statement? 2.6.5 [5] <2.2, 2.3> For the MIPS assembly above, assume that the registers $s0, $s1, $s2, and $s3 contain the values 0x0000000a, 0x00000014, 0x0000001e, and 0x00000028, respectively. Also, assume that register $s6 contains the value 0x00000100, and that memory contains the following values: Address Value 0x00000100 0x00000064 0x00000104 0x000000c8 0x00000108 0x0000012c Find the value of $s0 at the end of the assembly code. 2.6.6 [10] <2.3, 2.5> For each MIPS instruction, show the value of the opcode (OP), source register (RS), and target register (RT) fields. For the I-type instruc- tions, show the value of the immediate field, and for the R-type instructions, show the value of the destination register (RD) field. Exercise 2.7 The following problems explore number conversions from signed and unsigned binary numbers to decimal numbers. a. 0010 0100 1001 0010 0100 1001 0010 0100two b. 0101 1111 1011 1110 0100 0000 0000 0000two 2.7.1 [5] <2.4> For the patterns above, what base 10 number does the binary number represent, assuming that it is a two’s complement integer? 2.7.2 [5] <2.4> For the patterns above, what base 10 number does the binary number represent, assuming that it is an unsigned integer? 2.7.3 [5] <2.4> For the patterns above, what hexadecimal number does it ­represent? The following problems explore number conversions from decimal to signed and unsigned binary numbers. a. –1ten b. 1024ten 2.21 Exercises 185
clipped_hennesy_Page_183_Chunk5540
186 Chapter 2 Instructions: Language of the Computer 2.7.4 [5] <2.4> For the base ten numbers above, convert to 2’s complement binary. 2.7.5 [5] <2.4> For the base ten numbers above, convert to 2’s complement ­hexadecimal. 2.7.6 [5] <2.4> For the base ten numbers above, convert the negated values from the table to 2’s complement hexadecimal. Exercise 2.8 The following problems deal with sign extension and overflow. Registers $s0 and $s1 hold the values as shown in the table below. You will be asked to perform an MIPS assembly language instruction on these registers and show the result. a. $s0 = 0x80000000sixteen, $s1 = 0xD0000000sixteen b. $s0 = 0x00000001sixteen, $s1 = 0xFFFFFFFFsixteen 2.8.1 [5] <2.4> For the contents of registers $s0 and $s1 as specified above, what is the value of $t0 for the following assembly code? add $t0, $s0, $s1 Is the result in $t0 the desired result, or has there been overflow? 2.8.2 [5] <2.4> For the contents of registers $s0 and $s1 as specified above, what is the value of $t0 for the following assembly code? sub $t0, $s0, $s1 Is the result in $t0 the desired result, or has there been overflow? 2.8.3 [5] <2.4> For the contents of registers $s0 and $s1 as specified above, what is the value of $t0 for the following assembly code? add $t0, $s0, $s1 add $t0, $t0, $s0 Is the result in $t0 the desired result, or has there been overflow? In the following problems, you will perform various MIPS operations on a pair of registers, $s0 and $s1. Given the values of $s0 and $s1 in each of the questions below, state if there will be overflow.
clipped_hennesy_Page_184_Chunk5541
a. add $s0, $s0, $s1 add $s0, $s0, $s1 b. add $s0, $s0, $s1 add $s0, $s0, $s1 add $s0, $s0, $s1 2.8.4 [5] <2.4> Assume that register $s0 = 0x70000000 and $s1 = 0x10000000. For the table above, will there be overflow? 2.8.5 [5] <2.4> Assume that register $s0 = 0x40000000 and $s1 = 0x20000000. For the table above, will there be overflow? 2.8.6 [5] <2.4> Assume that register $s0 = 0x8FFFFFFF and $s1 = 0xD0000000. For the table above, will there be overflow? Exercise 2.9 The table below contains various values for register $s1. You will be asked to evalu- ate if there would be overflow for a given operation. a. –1ten b. 1024ten 2.9.1 [5] <2.4> Assume that register $s0 = 0x70000000 and $s1 has the value as given in the table. If the instruction: add $s0, $s0, $s1 is executed, will there be overflow? 2.9.2 [5] <2.4> Assume that register $s0 = 0x80000000 and $s1 has the value as given in the table. If the instruction: sub $s0, $s0, $s1 is executed, will there be overflow? 2.9.3 [5] <2.4> Assume that register $s0 = 0x7FFFFFFF and $s1 has the value as given in the table. If the instruction: sub $s0, $s0, $s1 is executed, will there be overflow? The table below contains various values for register $s1. You will be asked to evalu- ate if there would be overflow for a given operation. a. 0010 0100 1001 0010 0100 1001 0010 0100two b. 0101 1111 1011 1110 0100 0000 0000 0000two 2.9.4 [5] <2.4> Assume that register $s0 = 0x70000000 and $s1 has the value as given in the table. If the instruction: add $s0, $s0, $s1 is executed, will there be overflow? 2.21 Exercises 187
clipped_hennesy_Page_185_Chunk5542
188 Chapter 2 Instructions: Language of the Computer 2.9.5 [5] <2.4> Assume that register $s0 = 0x70000000 and $s1 has the value as given in the table. If the instruction: add $s0, $s0, $s1 is executed, what is the result in hex? 2.9.6 [5] <2.4> Assume that register $s0 = 0x70000000 and $s1 has the value as given in the table. If the instruction: add $s0, $s0, $s1 is executed, what is the result in base ten? Exercise 2.10 In the following problems, the data table contains bits that represent the opcode of an instruction. You will be asked to interpret the bits as MIPS instructions into assembly code and determine what format of MIPS instruction the bits represent. a. 0000 0010 0001 0000 1000 0000 0010 0000two b. 0000 0001 0100 1011 0100 1000 0010 0010two 2.10.1 [5] <2.5> For the binary entries above, what instruction do they ­ represent? 2.10.2 [5] <2.5> What type (I-type, R-type, J-type) instruction do the binary entries above represent? 2.10.3 [5] <2.4, 2.5> If the binary entries above were data bits, what number would they represent in hexadecimal? In the following problems, the data table contains MIPS instructions. You will be asked to translate the entries into the bits of the opcode and determine the MIPS instruction format. a. addi $t0, $t0, 0 b. sw $t1, 32($t2) 2.10.4 [5] <2.4, 2.5> For the instructions above, show the binary then hexadeci- mal representation of these instructions. 2.10.5 [5] <2.5> What type (I-type, R-type, J-type) instruction do the instruc- tions above represent? 2.10.6 [5] <2.5> What is the binary then hexadecimal representation of the opcode, Rs, and Rt fields in this instruction? For R-type instructions, what is the hexadecimal representation of the Rd and funct fields? For I-type instructions, what is the hexadecimal representation of the immediate field?
clipped_hennesy_Page_186_Chunk5543
Exercise 2.11 In the following problems, the data table contains bits that represent the opcode of an instruction. You will be asked to translate the entries into assembly code and determine what format of MIPS instruction the bits represent. a. 0x01084020 b. 0x02538822 2.11.1 [5] <2.4, 2.5> What binary number does the above hexadecimal number represent? 2.11.2 [5] <2.4, 2.5> What decimal number does the above hexadecimal number represent? 2.11.3 [5] <2.5> What instruction does the above hexadecimal number represent? In the following problems, the data table contains the values of various fields of MIPS instructions. You will be asked to determine what the instruction is, and find the MIPS format for the instruction. a. op=0, rs=3, rt=2, rd=3, shamt=0, funct=34 b. op=0x23, rs=1, rt=2, const=0x4 2.11.4 [5] <2.5> What type (I-type, R-type) instruction do the instructions above represent? 2.11.5 [5] <2.5> What is the MIPS assembly instruction described above? 2.11.6 [5] <2.4, 2.5> What is the binary representation of the instructions above? Exercise 2.12 In the following problems, the data table contains various modifications that could be made to the MIPS instruction set architecture. You will investigate the impact of these changes on the instruction format of the MIPS architecture. a. 128 registers b. Four times as many different instructions 2.12.1 [5] <2.5> If the instruction set of the MIPS processor is modified, the instruction format must also be changed. For each of the suggested changes above, show the size of the bit fields of an R-type format instruction. What is the total number of bits needed for each instruction? 2.21 Exercises 189
clipped_hennesy_Page_187_Chunk5544
190 Chapter 2 Instructions: Language of the Computer 2.12.2 [5] <2.5> If the instruction set of the MIPS processor is modified, the instruction format must also be changed. For each of the suggested changes above, show the size of the bit fields of an I-type format instruction. What is the total number of bits needed for each instruction? 2.12.3 [5] <2.5, 2.10> Why could the suggested change in the table above decrease the size of an MIPS assembly program? Why could the suggested change in the table above increase the size of an MIPS assembly program? In the following problems, the data table contains hexadecimal values. You will be asked to determine what MIPS instruction the value represents, and find the MIPS instruction format. a. 0x01090012 b. 0xAD090012 2.12.4 [5] <2.5> For the entries above, what is the value of the number in ­decimal? 2.12.5 [5] <2.5> For the hexadecimal entries above, what instruction do they represent? 2.12.6 [5] <2.4, 2.5> What type (I-type, R-type, J-type) instruction do the binary entries above represent? What is the value of the op field and the rt field? Exercise 2.13 In the following problems, the data table contains the values for registers $t0 and $t1. You will be asked to perform several MIPS logical operations on these registers. a. $t0 = 0xAAAAAAAA, $t1 = 0x12345678 b. $t0 = 0xF00DD00D, $t1 = 0x11111111 2.13.1 [5] <2.6> For the lines above, what is the value of $t2 for the following sequence of instructions? sll $t2, $t0, 44 or $t2, $t2, $t1 2.13.2 [5] <2.6> For the values in the table above, what is the value of $t2 for the following sequence of instructions? sll $t2, $t0, 4 andi $t2, $t2, –1
clipped_hennesy_Page_188_Chunk5545
2.13.3 [5] <2.6> For the lines above, what is the value of $t2 for the following sequence of instructions? srl $t2, $t0, 3 andi $t2, $t2, 0xFFEF In the following exercise, the data table contains various MIPS logical operations. You will be asked to find the result of these operations given values for registers $t0 and $t1. a. sll $t2, $t0, 1 andi $t2, $t2, –1 b. andi $t2, $t1, 0x00F0 srl $t2, 2 2.13.4 [5] <2.6> Assume that $t0 = 0x0000A5A5 and $t1 = 00005A5A. What is the value of $t2 after the two instructions in the table? 2.13.5 [5] <2.6> Assume that $t0 = 0xA5A50000 and $t1 = A5A50000. What is the value of $t2 after the two instructions in the table? 2.13.6 [5] <2.6> Assume that $t0 = 0xA5A5FFFF and $t1 = A5A5FFFF. What is the value of $t2 after the two instructions in the table? Exercise 2.14 The following figure shows the placement of a bit field in register $t0. Field 31 – i bits i – j bits j bits In the following problems, you will be asked to write MIPS instructions to extract the bits “Field” from register $t0 and place them into register $t1 at the location indicated in the following table. a. Field 0 0 0 … 0 0 0 b. 1 1 1 … 1 1 1 Field 1 1 1 … 1 1 1 31 i j 0 31 0 31 14 + i – j bits 14 0 2.21 Exercises 191 31 – (i – j)
clipped_hennesy_Page_189_Chunk5546
192 Chapter 2 Instructions: Language of the Computer 2.14.1 [20] <2.6> Find the shortest sequence of MIPS instructions that extracts a field from $t0 for the constant values i = 22 and j = 5 and places the field into $t1 in the format shown in the data table. 2.14.2 [5] <2.6> Find the shortest sequence of MIPS instructions that extracts a field from $t0 for the constant values i = 4 and j = 0 and places the field into $t1 in the format shown in the data table. 2.14.3 [5] <2.6> Find the shortest sequence of MIPS instructions that extracts a field from $t0 for the constant values i = 31 and j = 28 and places the field into $t1 in the format shown in the data table. In the following problems, you will be asked to write MIPS instructions to extract the bits “Field” from register $t0 shown in the figure and place them into register $t1 at the location indicated in the following table. The bits shown as “XXX” are to remain unchanged. a. Field X X X … X X X b. X X X … X X X Field X X X … X X X 2.14.4 [20] <2.6> Find the shortest sequence of MIPS instructions that extracts a field from $t0 for the constant values i = 17 and j = 11 and places the field into $t1 in the format shown in the data table. 2.14.5 [5] <2.6> Find the shortest sequence of MIPS instructions that extracts a field from $t0 for the constant values i = 5 and j = 0 and places the field into $t1 in the format shown in the data table. 2.14.6 [5] <2.6> Find the shortest sequence of MIPS instructions that extracts a field from $t0 for the constant values i = 31 and j = 29 and places the field into $t1 in the format shown in the data table. Exercise 2.15 For these problems, the table holds some logical operations that are not included in the MIPS instruction set. How can these instructions be implemented? a. not $t1, $t2 // bit-wise invert b. orn $t1, $t2, $t3 // bit-wise OR of $t2, !$t3 31 31 14 + i – j bits 14 0 31 – (i – j)
clipped_hennesy_Page_190_Chunk5547
2.15.1 [5] <2.6> The logical instructions above are not included in the MIPS instruction set, but are described above. If the value of $t2 = 0x00FFA5A5 and the value of $t3 = 0xFFFF003C, what is the result in $t1? 2.15.2 [10] <2.6> The logical instructions above are not included in the MIPS instruction set, but can be synthesized using one or more MIPS assembly instruc- tions. Provide a minimal set of MIPS instructions that may be used in place of the instructions in the table above. 2.15.3 [5] <2.6> For your sequence of instructions in 2.15.2, show the bit-level representation of each instruction. Various C-level logical statements are shown in the table below. In this exercise, you will be asked to evaluate the statements and implement these C statements using MIPS assembly instructions. a. A = B | !A; b. A = C[0] << 4; 2.15.4 [5] <2.6> The table above shows different C statements that use logical operators. If the memory location at C[0] contains the integer values 0x00001234, and the initial integer values of A and B are 0x00000000 and 0x00002222, what is the result value of A? 2.15.5 [5] <2.6> For the C statements in the table above, write a minimal sequence of MIPS assembly instructions that does the identical operation. Assume $t1 = A, $t2 = B, and $s1 is the base address of C. 2.15.6 [5] <2.6> For your sequence of instructions in 2.15.5, show the bit-level representation of each instruction. Exercise 2.16 For these problems, the table holds various binary values for register $t0. Given the value of $t0, you will be asked to evaluate the outcome of different branches. a. 0010 0100 1001 0010 0100 1001 0010 0100two b. 0101 1111 1011 1110 0100 0000 0000 0000two 2.16.1 [5] <2.7> Suppose that register $t0 contains a value from above and $t1 has the value 0011 1111 1111 1000 0000 0000 0000 0000two 2.21 Exercises 193
clipped_hennesy_Page_191_Chunk5548
194 Chapter 2 Instructions: Language of the Computer Note the result of executing these instructions on particular registers. What is the value of $t2 after the following instructions? slt $t2, $t0, $t1 beq $t2, $0, ELSE j DONE ELSE: addi $t2, $0, 2 DONE: 2.16.2 [5] <2.7> Suppose that register $t0 contains a value from the table above and is compared against the value X, as used in the MIPS instruction below. Note the format of the slti instruction. For what values of X, if any, will $t2 be equal to 1? slti $t2, $t0, X 2.16.3 [5] <2.7> Suppose the program counter (PC) is set to 0x0000 0020. Is it possible to use the jump MIPS assembly instruction to get set the PC to the address as shown in the data table above? Is it possible to use the branch-on-equal MIPS assembly instruction to get set the PC to the address as shown in the data table above? For these problems, the table holds various binary values for register $t0. Given the value of $t0, you will be asked to evaluate the outcome of different branches. a. 0x00101000 b. 0x80001000 2.16.4 [5] <2.7> Suppose that register $t0 contains a value from above. What is the value of $t2 after the following instructions? slt $t2, $0, $t0 bne $t2, $0, ELSE j DONE ELSE: addi $t2, $t2, 2 DONE: 2.16.5 [5] <2.6, 2.7> Suppose that register $t0 contains a value from above. What is the value of $t2 after the following instructions? sll $t0, $t0, 2 slt $t2, $t0, $0 2.16.6 [5] <2.7> Suppose the program counter (PC) is set to 0x2000 0000. Is it possible to use the jump (j) MIPS assembly instruction to get set the PC to the
clipped_hennesy_Page_192_Chunk5549
address as shown in the data table above? Is it possible to use the branch-on-equal (beq) MIPS assembly instruction to set the PC to the address as shown in the data table above? Note the format of the J-type instruction. Exercise 2.17 For these problems, there are several instructions that are not included in the MIPS instruction set are shown. a. subi $t2, $t3, 5 # R[rt] = R[rs] – SignExtImm b. rpt $t2, loop # if(R[rs]>0) R[rs]=R[rs]-1, PC=PC+4+BranchAddr 2.17.1 [5] <2.7> The table above contains some instructions not included in the MIPS instruction set and the description of each instruction. Why are these instructions not included in the MIPS instruction set? 2.17.2 [5] <2.7> The table above contains some instructions not included in the MIPS instruction set and the description of each instruction. If these instructions were to be implemented in the MIPS instruction set, what is the most appropriate instruction format? 2.17.3 [5] <2.7> For each instruction in the table above, find the shortest sequence of MIPS instructions that performs the same operation. For these problems, the table holds MIPS assembly code fragments. You will be asked to evaluate each of the code fragments, familiarizing you with the different MIPS branch instructions. a. LOOP: addi $s2, $s2, 2 subi $t1, $t1, 1 bne $t1, $0, LOOP DONE: b. LOOP: slt $t2, $0, $t1 beq $t2, $0, DONE subi $t1, $t1, 1 addi $s2, $s2, 2 j LOOP DONE: 2.17.4 [5] <2.7> For the loops written in MIPS assembly above, assume that the register $t1 is initialized to the value 10. What is the value in register $s2 assuming the $s2 is initially zero? 2.17.5 [5] <2.7> For each of the loops above, write the equivalent C code rou- tine. Assume that the registers $s1, $s2, $t1, and $t2 are integers A, B, i, and temp, respectively. 2.21 Exercises 195
clipped_hennesy_Page_193_Chunk5550
196 Chapter 2 Instructions: Language of the Computer 2.17.6 [5] <2.7> For the loops written in MIPS assembly above, assume that the register $t1 is initialized to the value N. How many MIPS instructions are executed? Exercise 2.18 For these problems, the table holds some C code. You will be asked to evaluate these C code statements in MIPS assembly code. a. for(i=0; i<a; i++) a += b; b. for(i=0; i<a; i++) for(j=0; j<b; j++) D[4*j] = i + j; 2.18.1 [5] <2.7> For the table above, draw a control-flow graph of the C code. 2.18.2 [5] <2.7> For the table above, translate the C code to MIPS assembly code. Use a minimum number of instructions. Assume that the values of a, b, i, and j are in registers $s0, $s1, $t0, and $t1, respectively. Also, assume that register $s2 holds the base address of the array D. 2.18.3 [5] <2.7> How many MIPS instructions does it take to implement the C code? If the variables a and b are initialized to 10 and 1 and all elements of D are initially 0, what is the total number of MIPS instructions that is executed to complete the loop? For these problems, the table holds MIPS assembly code fragments. You will be asked to evaluate each of the code fragments, familiarizing you with the different MIPS branch instructions. a. addi $t1, $0, 50 LOOP: lw $s1, 0($s0) add $s2, $s2, $s1 lw $s1, 4($s0) add $s2, $s2, $s1 addi $s0, $s0, 8 subi $t1, $t1, 1 bne $t1, $0, LOOP b. addi $t1, $0, $0 LOOP: lw $s1, 0($s0) add $s2, $s2, $s1 addi $s0, $s0, 4 addi $t1, $t1, 1 slti $t2, $t1, 100 bne $t2, $s0, LOOP 2.18.4 [5] <2.7> What is the total number of MIPS instructions executed?
clipped_hennesy_Page_194_Chunk5551
2.18.5 [5] <2.7> Translate the loops above into C. Assume that the C-level inte- ger i is held in register $t1, $s2 holds the C-level integer called result, and $s0 holds the base address of the integer MemArray. 2.18.6 [5] <2.7> Rewrite the loop to reduce the number of MIPS instructions executed. Exercise 2.19 For the following problems, the table holds C code functions. Assume that the first function listed in the table is called first. You will be asked to translate these C code routines into MIPS assembly. a. int fib(int n){ if (n==0) return 0; else if (n == 1) return 1; else fib(n-1) + fib(n–2); b. int positive(int a, int b) { if (addit(a, b) > 0) return 1; else return 0; } int addit(int a, int b) { return a+b; } 2.19.1 [15] <2.8> Implement the C code in the table in MIPS assembly. What is the total number of MIPS instructions needed to execute the function? 2.19.2 [5] <2.8> Functions can often be implemented by compilers “in-line.” An in-line function is when the body of the function is copied into the program space, allowing the overhead of the function call to be eliminated. Implement an “in-line” version of the the C code in the table in MIPS assembly. What is the reduction in the total number of MIPS assembly instructions needed to complete the function? Assume that the C variable n is initialized to 5. 2.19.3 [5] <2.8> For each function call, show the contents of the stack after the function call is made. Assume the stack pointer is originally at address 0x7ffffffc, and follow the register conventions as specified in Figure 2.11. The following three problems in this Exercise refer to a function f that calls another function func. The code for C function func is already compiled in another ­module 2.21 Exercises 197
clipped_hennesy_Page_195_Chunk5552
198 Chapter 2 Instructions: Language of the Computer using the MIPS calling convention from Figure 2.14. The function declaration for func is “int func(int a, int b);”. The code for function f is as follows: a. int f(int a, int b, int c, int d){ return func(func(a,b),c+d); } b. int f(int a, int b, int c, int d){ if(a+b>c+d) return func(a+b,c+d); return func(c+d,a+b); } 2.19.4 [10] <2.8> Translate function f into MIPS assembly language, also using the MIPS calling convention from Figure 2.14. If you need to use registers $t0 through $t7, use the lower-numbered registers first. 2.19.5 [5] <2.8> Can we use the tail-call optimization in this function? If no, explain why not. If yes, what is the difference in the number of executed instruc- tions in f with and without the optimization? 2.19.6 [5] <2.8> Right before your function f from Problem 2.19.4 returns, what do we know about contents of registers $t5, $s3, $ra, and $sp? Keep in mind that we know what the entire function f looks like, but for function func we only know its declaration. Exercise 2.20 This exercise deals with recursive procedure calls. For the following problems, the table has an assembly code fragment that computes the factorial of a number. However, the entries in the table have errors, and you will be asked to fix these errors. For number n, factorial of n = 1 x 2 x 3 x .. .. x n. a. FACT: sw $ra, 4($sp) sw $a0, 0($sp) addi $sp, $sp, -8 slti $t0, $a0, 1 beq $t0, $0, L1 addi $v0, $0, 1 addi $sp, $sp, 8 jr $ra L1: addi $a0, $a0, -1 jal FACT addi $sp, $sp, 8 lw $a0, 0($sp) lw $ra, 4($sp) mul $v0, $a0, $v0 jr $ra
clipped_hennesy_Page_196_Chunk5553
b. FACT: addi $sp, $sp, 8 sw $ra, 4($sp) sw $a0, 0($sp) add $s0, $0, $a0 slti $t0, $a0, 2 beq $t0, $0, L1 mul $v0, $s0, $v0 addi $sp, $sp, -8 jr $ra L1: addi $a0, $a0, -1 jal FACT addi $v0, $0, 1 lw $a0, 0($sp) lw $ra, 4($sp) addi $sp, $sp, -8 jr $ra 2.20.1 [5] <2.8> The MIPS assembly program above computes the factorial of a given input. The integer input is passed through register $a0, and the result is returned in register $v0. In the assembly code, there are a few errors. Correct the MIPS errors. 2.20.2 [10] <2.8> For the recursive factorial MIPS program above, assume that the input is 4. Rewrite the factorial program to operate in a non-recursive man- ner. Restrict your register usage to registers $s0-$s7. What is the total number of instructions used to execute your solution from 2.20.2 versus the recursive version of the factorial program? 2.20.3 [5] <2.8> Show the contents of the stack after each function call, assum- ing that the input is 4. For the following problems, the table has an assembly code fragment that computes a Fibonacci number. However, the entries in the table have errors, and you will be asked to fix these errors. For number n, the Fibonacci of n is calculated as follows: n fibonacci of n 1 1 2 1 3 2 4 3 5 5 6 8 7 13 8 21 2.21 Exercises 199
clipped_hennesy_Page_197_Chunk5554
200 Chapter 2 Instructions: Language of the Computer a. FIB: addi $sp, $sp, –12 sw $ra, 0($sp) sw $s1, 4($sp) sw $a0, 8($sp) slti $t0, $a0, 1 beq $t0, $0, L1 addi $v0, $a0, $0 j EXIT L1: addi $a0, $a0, –1 jal FIB addi $s1, $v0, $0 addi $a0, $a0, –1 jal FIB add $v0, $v0, $s1 EXIT: lw $ra, 0($sp) lw $a0, 8($sp) lw $s1, 4($sp) addi $sp, $sp, 12 jr $ra b. FIB: addi $sp, $sp, -12 sw $ra, 8($sp) sw $s1, 4($sp) sw $a0, 0($sp) slti $t0, $a0, 3 beq $t0, $0, L1 addi $v0, $0, 1 j EXIT L1: addi $a0, $a0, -1 jal FIB addi $a0, $a0, -2 jal FIB add $v0, $v0, $s1 EXIT: lw $a0, 0($sp) lw $s1, 4($sp) lw $ra, 8($sp) addi $sp, $sp, 12 jr $ra 2.20.4 [5] <2.8> The MIPS assembly program above computes the Fibonacci of a given input. The integer input is passed through register $a0, and the result is returned in register $v0. In the assembly code, there are a few errors. Correct the MIPS errors. 2.20.5 [10] <2.8> For the recursive Fibonacci MIPS program above, assume that the input is 4. Rewrite the Fibonacci program to operate in a non-recursive man- ner. Restrict your register usage to registers $s0–$s7. What is the total number of
clipped_hennesy_Page_198_Chunk5555
instructions used to execute your solution from 2.20.2 versus the recursive version of the factorial program? 2.20.6 [5] <2.8> Show the contents of the stack after each function call, assum- ing that the input is 4. Exercise 2.21 Assume that the stack and the static data segments are empty and that the stack and global pointers start at address 0x7fff fffc and 0x1000 8000, respectively. Assume the calling conventions as specified in Figure 2.11 and that function inputs are passed using registers $a0–$a3 and returned in register $r0. Assume that leaf functions may only use saved registers. a. int my_global = 100; main() { int x = 10; int y = 20; int z; z = my_function(x, y) } int my_function(int x, int y) { return x – y + my_global; } b. int my_global = 100; main() { int z; my_global += 1; z = leaf_function(my_global); } int leaf_function(int x) { return x + 1; } 2.21.1 [5] <2.8> Write MIPS assembly code for the code in the table above. 2.21.2 [5] <2.8> Show the contents of the stack and the static data segments after each function call. 2.21.3 [5] <2.8> If the leaf function could use temporary registers ($t0, $t1, etc.), write the MIPS code for the code in the table above. 2.21 Exercises 201
clipped_hennesy_Page_199_Chunk5556
202 Chapter 2 Instructions: Language of the Computer The following three problems in this Exercise refer to this function, written in MIPS assembly following the calling conventions from Figure 2.14: a. f: add $v0,$a1,$a0 bnez $a2,L sub $v0,$a0,$a1 L: jr $v0 b. f: add $a2,$a3,$a2 slt $a2,$a2,$a0 move $v0,$a1 beqz $a2, L jr $ra L: move $a0,$a1 jal g ; Tail call 2.21.4 [10] <2.8> This code contains a mistake that violates the MIPS calling convention. What is this mistake and how should it be fixed? 2.21.5 [10] <2.8> What is the C equivalent of this code? Assume that the func- tion’s arguments are named a, b, c, etc. in the C version of the function. 2.21.6 [10] <2.8> At the point where this function is called register $a0, $a1, $a2, and $a3 have values 1, 100, 1000, and 30, respectively. What is the value returned by this function? If another function g is called from f, assume that the value returned from g is always 500. Exercise 2.22 This exercise explores ASCII and Unicode conversion. The following table shows strings of characters. a. hello world b. 0123456789 2.22.1 [5] <2.9> Translate the strings into hexadecimal ASCII byte values. 2.22.2 [5] <2.9> Translate the strings into 16-bit Unicode (using hex notation and the Basic Latin character set). The following table shows hexadecimal ASCII character values. a. 41 44 44 b. 4D 49 50 53
clipped_hennesy_Page_200_Chunk5557
2.22.3 [5] <2.5, 2.9> Translate the hexadecimal ASCII values to text. Exercise 2.23 In this exercise, you will be asked to write an MIPS assembly program that converts strings into the number format as specified in the table. a. positive and negative integer decimal strings b. positive hexadecimal integers 2.23.1 [10] <2.9> Write a program in MIPS assembly language to convert an ASCII number string with the conditions listed in the table above, to an integer. Your program should expect register $a0 to hold the address of a null-terminated string containing some combination of the digits 0 through 9. Your program should compute the integer value equivalent to this string of digits, then place the number in register $v0. If a non-digit character appears anywhere in the string, your program should stop with the value –1 in register $v0. For example, if register $a0 points to a sequence of three bytes 50ten, 52ten, 0ten (the null-terminated string “24”), then when the program stops, register $v0 should contain the value 24ten. Exercise 2.24 Assume that the register $t1 contains the address 0x1000 0000 and the register $t2 contains the address 0x1000 0010. Note the MIPS architecture utilizes big- endian addressing. a. lbu $t0, 0($t1) sw $t0, 0($t2) b. lb $t0, 0($t1) sh $t0, 0($t2) 2.24.1 [5] <2.9> Assume that the data (in hexadecimal) at address 0x1000 0000 is: 1000 0000 12 34 56 78 What value is stored at the address pointed to by register $t2? Assume that the memory location pointed to $t2 is initialized to 0xFFFF FFFF. 2.24.2 [5] <2.9> Assume that the data (in hexadecimal) at address 0x1000 0000 is: 1000 0000 80 80 80 80 2.21 Exercises 203
clipped_hennesy_Page_201_Chunk5558
204 Chapter 2 Instructions: Language of the Computer What value is stored at the address pointed to by register $t2? Assume that the memory location pointed to $t2 is initialized to 0x0000 0000. 2.24.3 [5] <2.9> Assume that the data (in hexadecimal) at address 0x1000 0000 is: 1000 0000 11 00 00 FF What value is stored at the address pointed to by register $t2? Assume that the memory location pointed to $t2 is initialized to 0x5555 5555. Exercise 2.25 In this exercise, you will explore 32-bit constants in MIPS. For the following prob- lems, you will be using the binary data in the table below. a. 0010 0000 0000 0001 0100 1001 0010 0100two b. 0000 1111 1011 1110 0100 0000 0000 0000two 2.25.1 [10] <2.10> Write the MIPS assembly code that creates the 32-bit con- stants listed above and stores that value to register $t1. 2.25.2 [5] <2.6, 2.10> If the current value of the PC is 0x00000000, can you use a single jump instruction to get to the PC address as shown in the table above? 2.25.3 [5] <2.6, 2.10> If the current value of the PC is 0x00000600, can you use a single branch instruction to get to the PC address as shown in the table above? 2.25.4 [5] <2.6, 2.10> If the current value of the PC is 0x1FFFf000, can you use a single branch instruction to get to the PC address as shown in the table above? 2.25.5 [10] <2.10> If the immediate field of an MIPS instruction was only 8 bits wide, write the MIPS code that creates the 32-bit constants listed above and stores that value to register $t1. Do not use the lui instruction. For the following problems, you will be using the MIPS assembly code as listed in the table. a. lui $t0, 0x1234 addi $t0, $t0, 0x5678 b. lui $t0, 0x1234 andi $t0, $t0, 0x5678
clipped_hennesy_Page_202_Chunk5559
2.25.6 [5] <2.6, 2.10> What is the value of register $t0 after the sequence of code in the table above? 2.25.7 [5] <2.6, 2.10> Write C code that is equivalent to the assembly code in the table. Assume that the largest constant that you can load into a 32-bit integer is 16 bits. Exercise 2.26 For this exercise, you will explore the range of branch and jump instructions in MIPS. For the following problems, use the hexadecimal data in the table below. a. 0x00020000 b. 0xFFFFFF00 2.26.1 [10] <2.6, 2.10> If the PC is at address 0x00000000, how many branch (no jump instructions) do you need to get to the address in the table above? 2.26.2 [10] <2.6, 2.10> If the PC is at address 0x00000000, how many jump instructions (no jump register instructions or branch instructions) are required to get to the target address in the table above? 2.26.3 [10] <2.6, 2.10> In order to reduce the size of MIPS programs, MIPS designers have decided to cut the immediate field of I-type instructions from 16 bits to 8 bits. If the PC is at address 0x0000000, how many branch instructions are needed to set the PC to the address in the table above? For the following problems, you will be using making modifications to the MIPS instruction set architecture. a. 128 registers b. Four times as many different operations 2.26.4 [10] <2.6, 2.10> If the instruction set of the MIPS processor is modified, the instruction format must also be changed. For each of the suggested changes above, what is the impact on the range of addresses for a beq instruction? Assume that all instructions remain 32 bits long and any changes made to the instruction format of i-type instructions only increase/decrease the immediate field of the beq instruction. 2.26.5 [10] <2.6, 2.10> If the instruction set of the MIPS processor is modi- fied, the instruction format must also be changed. For each of the ­suggested 2.21 Exercises 205
clipped_hennesy_Page_203_Chunk5560
206 Chapter 2 Instructions: Language of the Computer changes above, what is the impact on the range of addresses for a jump instruc- tion? Assume that instructions remain 32 bits long and any changes made to the instruction format of J-type instructions only impact the address field of the jump instruction. 2.26.6 [10] <2.6, 2.10> If the instruction set of the MIPS processor is modified, the instruction format must also be changed. For each of the suggested changes above, what is the impact on the range of addresses for a jump register instruction, assuming that each instruction must be 32 bits. Exercise 2.27 In the following problems, you will be exploring different addressing modes in the MIPS instruction set architecture. These different addressing modes are listed in the table below. a. Base or Displacement Addressing b. Pseudodirect Addressing 2.27.1 [5] <2.10> In the table above are different addressing modes of the MIPS instruction set. Give an example MIPS instructios that shows the MIPS addressing mode. 2.27.2 [5] <2.10> For the instructions in 2.27.1, what is the instruction format type used for the given instruction? 2.27.3 [5] <2.10> List the benefits and drawbacks of a particular MIPS address- ing mode. Write MIPS code that shows these benefits and drawbacks. In the following problems, you will be using the MIPS assembly code as listed below to explore the trade-offs of the immediate field in the MIPS I-type instructions. a. 0x00400000 beq $s0, $0, FAR ... 0x00403100 FAR: addi $s0, $s0, 1 b. 0x00000100 j AWAY ... 0x04000010 AWAY: addi $s0, $s0, 1 2.27.4 [15] <2.10> For the MIPS statements above, show the bit-level instruc- tion representation of each of the instructions in hexadecimal.
clipped_hennesy_Page_204_Chunk5561
2.27.5 [10] <2.10> By reducing the size of the immediate fields of the I-type and J-type instructions, we can save on the number of bits needed to represent these types of instructions. If the immediate field of I-type instructions were 8 bits and the immediate field of J-type instructions were 18 bits, rewrite the MIPS code above to reflect this change. Avoid using the lui instruction. 2.27.6 [5] <2.10> How many extra instructions are needed to do execute your code in 2.27.5 MIPS statements in the table versus the code shown in the table above? Exercise 2.28 The following table contains MIPS assembly code for a lock. Refer to the definition of the ll and sc pairs of MIPS instructions. a. try: MOV R3,R4 LL R2,0(R2) ADDI R2,R2, 1 SC R3,0(R1) BEQZ R3,try MOV R4,R2 2.28.1 [5] <2.11> For each test and fail of the store conditional, how many instructions need to be executed? 2.28.2 [5] <2.11> For the load locked/store conditional code above, explain why this code may fail. 2.28.3 [15] <2.11> Rewrite the code above so that the code may operate cor- rectly. Be sure to avoid any race conditions. Each entry in the following table has code and also shows the contents of various registers. The notation “($s1)” shows the contents of a memory location pointed to by register $s1. The assembly code in each table is executed in the cycle shown on parallel processors with a shared memory space. a. Processor 1 Processor 2 Cycle Processor 1 Mem Processor 2 $t1 $t0 ($s1) $t1 $t0 0 1 2 99 30 40 ll $t1, 0($s1) 1 ll $t1, 0($s1) 2 sc $t0, 0($s1) 3 sc $t0, 0($s1) 4 2.21 Exercises 207
clipped_hennesy_Page_205_Chunk5562
208 Chapter 2 Instructions: Language of the Computer b. Processor 1 Processor 2 Cycle Processor 1 Mem Processor 2 $t1 $t0 ($s1) $t1 $t0 0 1 2 99 30 40 ll $t1,0($s1) 1 ll $t1,0($s1) 2 addi $t1,$t1,1 3 sc $t1,0($s1) 4 sc $t0,0($s1) 5 2.28.4 [5] <2.11> Fill out the table with the value of the registers for each given cycle. Exercise 2.29 The first three problems in this Exercise refer to a critical section of the form lock(lk); operation unlock(lk); where the “operation” updates the shared variable shvar using the local (non- shared) variable x as follows: Operation a. shvar=max(shvar,x); b. if(shvar>0) shvar=max(shvar,x); 2.29.1 [10] <2.11> Write the MIPS assembly code for this critical section, assum- ing that the address of the lk variable is in $a0, the address of the shvar variable is in $a1, and the value of variable x is in $a2. Your critical section should not con- tain any function calls, i.e., you should include the MIPS instructions for lock(), unlock(), max(), and min() operations. Use ll/sc instructions to implement the lock() operation, and the unlock() operation is simply an ordinary store instruction. 2.29.2 [10] <2.11> Repeat problem 2.29.1, but this time use ll/sc to per- form an atomic update of the shvar variable directly, without using lock() and unlock(). Note that in this problem there is no variable lk. 2.29.3 [10] <2.11> Compare the best-case performance of your code from 2.29.1 and 2.29.2, assuming that each instruction takes one cycle to execute. Note: best-case
clipped_hennesy_Page_206_Chunk5563
means that ll/sc always succeeds, the lock is always free when we want to lock(), and if there is a branch we take the path that completes the operation with fewer executed instructions. 2.29.4 [10] <2.11> Using your code from 2.29.2 as an example, explain what happens when two processors begin to execute this critical section at the same time, assuming that each processor executes exactly one instruction per cycle. 2.29.5 [10] <2.11> Explain why in your code from 2.29.2 register $a1 contains the address of variable shvar and not the value of that variable, and why register $a2 contains the value of variable x and not its address. 2.29.6 [10] <2.11> If we want to atomically perform the same operation on two shared variables (e.g., shvar1 and shvar2) in the same critical section, we can do this easily using the approach from 2.29.1 (simply put both updates between the lock operation and the corresponding unlock operation). Explain why we cannot do this using the approach from 2.29.2. i.e., why we cannot use ll/sc to access both shared variables in a way that guarantees that both updates are executed together as a single atomic operation. Exercise 2.30 Assembler instructions are not a part of the MIPS instruction set, but often appear in MIPS programs. The table below contains some MIPS assembly instructions that get translated to actual MIPS instructions. a. clear $t0 b. beq $t1, large, LOOP 2.30.1 [5] <2.12> For each assembly instruction in the table above, produce a minimal sequence of actual MIPS instructions to accomplish the same thing. You may need to use temporary registers in some cases. In the table large refers to a number that requires 32 bits to represent and small to a number that can fit into 16 bits. The table below contains some MIPS assembly instructions that get translated to actual MIPS instructions. a. bltu $s0, $t1, Loop b. ulw $v0, v 2.21 Exercises 209
clipped_hennesy_Page_207_Chunk5564
210 Chapter 2 Instructions: Language of the Computer 2.30.2 [5] <2.12> Does the instruction in the table above need to be edited dur- ing the link phase? Why? Exercise 2.31 The table below contains the link-level details of two different procedures. In this exercise, you will be taking the place of the linker. a. Procedure A Procedure B Text Segment Address Instruction Text Segment Address Instruction 0 lbu $a0, 0($gp) 0 sw $a1, 0($gp) 4 jal 0 4 jal 0 Data Segment 0 (X) Data Segment 0 (Y) … … … … Relocation Info Address Instruction Type Dependency Relocation Info Address Instruction Type Dependency 0 lbu X 0 sw Y 4 jal B 4 jal A Symbol Table Address Symbol Symbol Table Address Symbol — X — Y — B — A b. Procedure A Procedure B Text Segment Address Instruction Text Segment Address Instruction 0 lui $at, 0 0 sw $a0, 0($gp) 4 ori $a0, $at, 0 4 jmp 0 … … … … 0x84 jr $ra 0x180 jal 0 … … … … Data Segment 0 (X) Data Segment 0 (Y) … … … … Relocation Info Address Instruction Type Dependency Relocation Info Address Instruction Type Dependency 0 lui X 0 sw Y 4 ori X 4 jmp FOO 0x180 jal A Symbol Table Address Symbol Symbol Table Address Symbol — X — Y 0x180 FOO — A
clipped_hennesy_Page_208_Chunk5565
2.31.1 [5] <2.12> Link the object files above to form the executable file header. Assume that Procedure A has a text size of 0x140 and data size of 0x40 and Pro- cedure B has a text size of 0x300 and data size of 0x50. Also assume the memory allocation strategy as shown in Figure 2.13. 2.31.2 [5] <2.12> What limitations, if any, are there on the size of an executable? 2.31.3 [5] <2.12> Given your understanding of the limitations of branch and jump instructions, why might an assembler have problems directly implementing branch and jump instructions an object file? Exercise 2.32 The first three problems in this exercise assume that the function swap, instead of the code in Figure 2.24, is defined in C as follows: a. void swap(int *p, int *q){ int temp; temp=*p; *p=*q; *q=temp; } b. void swap(int *p, int *q){ *p=*p+*q; *q=*p-*q; *p=*p-*q; } 2.32.1 [10] <2.13> Translate this function into MIPS assembler code. 2.32.2 [5] <2.13> What needs to change in the sort function? 2.32.3 [5] <2.13> If we were sorting 8-bit bytes, not 32-bit words, how would your MIPS code for swap in 2.32.1 change? For the remaining three problems in this Exercise, we assume that the sort func- tion from Figure 2.27 is changed in the following way: a. Use the swap function from the beginning of this exercise. b. Sort an array of n bytes instead of n words. 2.32.4 [5] <2.13> Does this change affect the code for saving and restoring reg- isters in Figure 2.27? 2.32.5 [10] <2.13> When sorting a 10-element array that was already sorted, how many more (or fewer) instructions are executed as a result of this change? 2.21 Exercises 211
clipped_hennesy_Page_209_Chunk5566
212 Chapter 2 Instructions: Language of the Computer 2.32.6 [10] <2.13> When sorting a 10-element array that was sorted in descend- ing order (opposite of the order that sort() creates), how many more (or fewer) instructions are executed as a result of this change? Exercise 2.33 The problems in this Exercise refer to the following function, given as array code: a. void copy(int a[], int b[], int n){ int i; for(i=0;i!=n;i++) a[i]=b[i]; } b. void shift(int a[], int n){ int i; for(i=0;i!=n-1;i++) a[i]=a[i+1]; } 2.33.1 [10] <2.14> Translate this function into MIPS assembly. 2.33.2 [10] <2.14> Convert this function into pointer-based code (in C). 2.33.3 [10] <2.14> Translate your pointer-based C code from 2.33.2 into MIPS assembly. 2.33.4 [5] <2.14> Compare the worst-case number of executed instructions per non-last loop iteration in your array-based code from 2.33.1 and your pointer-based code from 2.33.3. Note: the worst case occurs when branch con- ditions are such that the longest path through the code is taken, i.e., if there is an if statement, the result of the condition check is such that the path with more instructions is taken. However, if the result of the condition check would cause the loop to exit, then we assume that the path that keeps us in the loop is taken. 2.33.5 [5] <2.14> Compare the number of temporary registers (t-registers) needed for your array-based code from 2.33.1 and for your pointer-based code from 2.33.3. 2.33.6 [5] <2.14> What would change in your answer from 2.33.4 if registers $t0–$t7 and $a0–$a3 in the MIPS calling convention were all callee-saved, just like $s0–$s7?
clipped_hennesy_Page_210_Chunk5567
Exercise 2.34 The table below contains ARM assembly code. In the following problems, you will translate ARM assembly code to MIPS. a. ADD r0, r1, r2 ;r0 = r1 + r2 ADC r0, r1, r2 ;r0 = r1 + r2 + Carrybit b. CMP r0, #4 ;if (r0 != 4) { ADDNE r1, r1, r0 ;r1 += r0 } 2.34.1 [5] <2.16> For the table above, translate this ARM assembly code to MIPS assembly code. Assume that ARM registers r0, r1, and r2 hold the same values as MIPS registers $s0, $s1, and $s2, respectively. Use MIPS temporary registers ($t0, etc.) where necessary. 2.34.2 [5] <2.16> For the ARM assembly instructions in the table above, show the bit fields that represent the ARM instructions. The table below contains MIPS assembly code. In the following problems, you will translate MIPS assembly code to ARM. a. nor $t0, #s0, 0 and $s1, $s1, $t0 b. sll $s1, $s2, 16 srl $s2, $s2, 16 or $s1, $s1, $s2 2.34.3 [5] <2.16> For the table above, find the ARM assembly code that corre- sponds to the sequence of MIPS assembly code. 2.34.4 [5] <2.16> Show the bit fields that represent the ARM assembly code. Exercise 2.35 The ARM processor has a few different addressing modes that are not supported in MIPS. The following problems explore these new addressing modes. a. LDR r0, [r1, #4] ; r0 = memory[r1+4], r1 += 4 b. LDMIA r0!, {r1-r3} ; r1 = memory[r0], r2 = memory[r0+4] ; r3 = memory[r0+8], r0 += 3*4 2.35.1 [5] <2.16> Identify the type of addressing mode of the ARM assembly instructions in the table above. 2.21 Exercises 213
clipped_hennesy_Page_211_Chunk5568
214 Chapter 2 Instructions: Language of the Computer 2.35.2 [5] <2.16> For the ARM assembly instructions above, write a sequence of MIPS assembly instructions to accomplish the same data transfer. In the following problems, you will compare code written using the ARM and MIPS instruction sets. The following table shows code written in the ARM instruc- tion set. a. MOV r0, #10 ;init loop counter to 10 LOOP: ADD r0, r1 ;add r1 to r0 SUBS r0, 1 ;decrement counter BNE LOOP ;if Z=0 repeat loop b. ADD r0, r1 ;r0 = r0 + r1 ADC r2, r3 ;r2 = r2 + r3 + carry 2.35.3 [10] <2.16> For the ARM assembly code above, write an equivalent MIPS assembly code routine. 2.35.4 [5] <2.16> What is the total number of ARM assembly instructions required to execute the code? What is the total number of MIPS assembly instruc- tions required to execute the code? 2.35.5 [5] <2.16> Assuming that the average CPI of the MIPS assembly routine is the same as the average CPI of the ARM assembly routine, and the MIPS proces- sor has an operation frequency that is 1.5 times that of the ARM processor, how much faster is the ARM processor than the MIPS processor? Exercise 2.36 The ARM processor has an interesting way of supporting immediate constants. This exercise investigates those differences. The following table contains ARM instructions. a. ADD, r3, r2, r1, LSR #4 ;r3 = r2 + (r1 >> 4) b. ADD, r3, r2, r2 ;r3 = r2 + r1 2.36.1 [5] <2.16> Write the equivalent MIPS code for the ARM assembly code above. 2.36.2 [5] <2.16> If the register R1 had the constant value of 8, rewrite your MIPS code to minimize the number of MIPS assembly instructions needed. 2.36.3 [5] <2.16> If the register R1 had the constant value of 0x06000000, rewrite your MIPS code to minimize the number of MIPS assembly instructions needed.
clipped_hennesy_Page_212_Chunk5569
The following table contains MIPS instructions. a. addi r3, r2, 0x2 b. addi r3, r2, –1 2.36.4 [5] <2.16> For the MIPS assembly code above, write the equivalent ARM assembly code. Exercise 2.37 This exercise explores the differences between the MIP and x86 instruction sets. The following table contains x86 assembly code. a. START: mov eax, 3 push eax mov eax, 4 mov ecx, 4 add eax, ecx pop ecx add eax, ecx b. START: mov ecx, 100 mov eax, 0 LOOP: add eax, ecx dec ecx cmp ecx, 0 jne LOOP DONE: 2.37.1 [10] <2.17> Write pseudo code for the given routine. 2.37.2 [10] <2.17> For the code in the table above, what is the equivalent MIPS for the given routine? The following table contains x86 assembly instructions. a. push eax b. test eax, 0x00200010 2.37.3 [5] <2.17> For each assembly instruction, show the size of each of the bit fields that represent the instruction. Treat the label MY_FUNCTION as a 32-bit constant. 2.37.4 [10] <2.17> Write equivalent MIPS assembly statements. 2.21 Exercises 215
clipped_hennesy_Page_213_Chunk5570
216 Chapter 2 Instructions: Language of the Computer Exercise 2.38 The x86 instruction set includes the REP prefix that causes the instruction to be repeated a given number of times or until a condition is satisfied. Note that x86 instructions refer to 8 bits as a byte, 16 bits as a word, and 32 bits as a double word. The first three problems in this Exercise refer to the following x86 instruction: Instruction Interpretation a. REP MOVSW Repeat until ECX is zero: Mem16[EDI]=Mem16[ESI], EDI=EDI+2, ESI=ESI+2, ECX=ECX-1 b. REPNE SCASB Repeat until ECX is zero: If Mem8[EDI] == AL then go to next instruction, otherwise EDI=EDI+1, ECX=ECI+1. Note: AL is the least- significant byte of the EAX register. 2.38.1 [5] <2.17> What would be a typical use for this instruction? 2.38.2 [5] <2.17> Write MIPS code that performs the same operation, assuming that $a0 corresponds to ECX, $a1 to EDI, $a2 to ESI, and $a3 to EAX. 2.38.3 [5] <2.17> If the x86 instruction takes one cycle to read memory, one cycle to write memory, and one cycle for each register update, and if MIPS takes one cycle per instruction, what is the speedup of using this x86 instruction instead of the equivalent MIPS code when ECX is very large? Assume that the clock cycle time for x86 and MIPS is the same. The remaining three problems in this exercise refer to the following function, given in both C and x86 assembly. For each x86 instruction, we also show its length in the x86 variable-length instruction format and the interpretation (what the instruc- tion does). Note that the x86 architecture has very few registers compared to MIPS, and as a result the x86 calling convention is to push all arguments onto the stack. The return value of an x86 function is passed back to the caller in the EAX register. C Code x86 Code a. int f(int a, int b, int c, int d){ if(a>b) return c; return d; } f: push %ebp ; 1B, push %ebp to stack mov %esp,%ebp ; 2B, move %esp to %ebp mov 12(%ebp),%eax ; 3B, load 2nd arg into %eax cmp %eax,8(%ebp) ; 3B, compare %eax w/ 1st arg mov 16(%ebp),%edx ; 3B, load 3rd arg into %edx jle S ; 2B, jump if cmp result is <= pop %ebp ; 1B, restore %ebp mov %edx,%eax ; 2B, move %edx into %eax ret ; 1B, return S: mov 20(%ebp),%edx ; 3B, load 4th arg into %edx pop %ebp ; 1B, restore %ebp mov %edx,%eax ; 2B, move %edx into %eax ret ; 1B, return
clipped_hennesy_Page_214_Chunk5571
b. void f(int a[], int n){ int i; for(i=0;i!=n;i++) a[i]=0; } f: push %ebp ; 1B, push %ebp to stack mov %esp,%ebp ; 2B, move %esp to %ebp mov 12(%ebp),%edx ; 3B, move 2nd arg into %edx mov 8(%ebp),%ecx ; 3B, move 1st arg into %ecx test %edx,%edx ; 2B, set flags based on %edx jz D ; 2B, jump if %edx was 0 xor %eax,%eax ; 2B, zero into %eax L: movl 0,(%ecx,%eax,4) ; 7B, Mem[%ecx+4*%eax]=0 add 1,%eax ; 3B, add 1 to %eax cmp %edx,%eax ; 2B, compare %edx and %eax jne L ; 2B, jump if cmp was != D: pop %ebp ; 1B, restore %ebp ret ; 1B, return 2.21 Exercises 217 2.38.4 [5] <2.17> Translate this function into MIPS assembly. Compare the size (how many bytes of instruction memory are needed) for this x86 code and for your MIPS code. 2.38.5 [5] <2.17> If the processor can execute two instructions per cycle, it must at least be able to read two consecutive instructions in each cycle. Explain how it would be done in MIPS and how it would be done in x86. 2.38.6 [5] <2.17> If each MIPS instruction takes one cycle, and if each x86 instruction takes one cycle plus a cycle for each memory read or write it has to perform, what is the speedup of using x86 instead of MIPS? Assume that the clock cycle time is the same in both x86 and MIPS, and that the execution takes the short- est possible path through the function (i.e., every loop is exited immediately and every if statement takes the direction that leads toward the return from the func- tion). Note that the x86 ret instruction reads the return address from the stack. Exercise 2.39 The CPI of the different instruction types is given in the following table. Arithmetic Load/Store Branch a. 1 10 3 b. 4 40 3 2.39.1 [5] <2.18> Assume the following instruction breakdown given for execut- ing a given program: Instructions (in millions) Arithmetic 500 Load/Store 300 Branch 100 What is the execution time for the processor if the operation frequency is 5 GHz?
clipped_hennesy_Page_215_Chunk5572
218 Chapter 2 Instructions: Language of the Computer 2.39.2 [5] <2.18> Suppose that new, more powerful arithmetic instructions are added to the instruction set. On average, through the use of these more power- ful arithmetic instructions, we can reduce the number of arithmetic instructions needed to execute a program by 25%, and the cost of increasing the clock cycle time by only 10%. Is this a good design choice? Why? 2.39.3 [5] <2.18> Suppose that we find a way to double the performance of arithmetic instructions. What is the overall speedup of our machine? What if we find a way to improve the performance of arithmetic instructions by 10 times? The following table shows the proportions of instruction execution for the differ- ent instruction types. Arithmetic Load/Store Branch a. 70% 10% 20% b. 50% 40% 10% 2.39.4 [5] <2.18> Given the instruction mix above and the assumption that an arithmetic instruction requires 2 cycles, a load/store instruction takes 6 cycles, and a branch instruction takes 3 cycles, find the average CPI. 2.39.5 [5] <2.18> For a 25% improvement in performance, how many cycles, on average, may an arithmetic instruction take if load/store and branch instructions are not improved at all? 2.39.6 [5] <2.18> For a 50% improvement in performance, how many cycles, on average, may an arithmetic instruction take if load/store and branch instructions are not improved at all? Exercise 2.40 The first three problems in this Exercise refer to the following function, given in MIPS assembly. Unfortunately, the programmer of this function has fallen prey to the pitfall of assuming that MIPS is a word-addressed machine, but in fact MIPS is byte-addressed. a. ; int f(int *a, int n, int x); f: move $v0,$0 ; ret=0 move $t0,$a0 ; ptr=a add $t1,$a1,$a0 ; &(a[n]) L: lw $t2,0($t0) ; read *p bne $t2,$a2,S ; if(*p==x) addi $v0,$v0,1 ; ret++; S: addi $t0,$t0,1 ; p=p+1 bne $t0,$t1,L ; repeat if p!=&(a[n]) jr $ra ; return ret
clipped_hennesy_Page_216_Chunk5573
b. ; void f(int a[], int n); f: move $t0,$0 ; i=0; addi $t1,$a1,-1 ; n-1 L: add $t2,$t0,$a0 ; address of a[i] lw $t3,1($t2) ; read a[i+1] sw $t3,0($t2) ; a[i]=a[i+1] addi $t0,$t0,1 ; i=i+1 bne $t0,$t1,L ; repeat if i!=n-1 jr $ra ; return Note that in MIPS assembly the “;” character denotes that the remainder of the line is a comment. 2.40.1 [5] <2.18> The MIPS architecture requires word-sized accesses (lw and sw) to be word-aligned, i.e., the lowermost 2 bits of the address must both be zero. If an address is not word-aligned, the processor raises a “bus error” exception. Explain how this alignment requirement affects the execution of this function. 2.40.2 [5] <2.18> If “a” was a pointer to the beginning of an array of 1-byte elements, and if we replaced lw and sw with lb (load byte) and sb (store byte), respectively, would this function be correct? Note: lb reads a byte from memory, sign-extends it, and places it into the destination register, while sb stores the least- significant byte of the register into memory. 2.40.3 [5] <2.18> Change this code to make it correct for 32-bit integers. The remaining three problems in this exercise refer to a program that allocates memory for an array, fills the array with some numbers, calls the sort function from Figure 2.27, and then prints out the array. The main function of the program is as follows (given as both C and MIPS code): Main Code in C MIPS Version of the Main Code main(){ int *v; int n=5; v=my_alloc(5); my_init(v,n); sort(v,n); . . . main: li $s0,5 move $a0,$s0 jal my_alloc move $s1,$v0 move $a0,$s1 move $a1,$s0 jal my_init move $a0,$s1 move $a1,$s0 jal sort The my_alloc function is defined as follows (given as both C and MIPS code). Note that the programmer of this function has fallen prey to the pitfall of 2.21 Exercises 219
clipped_hennesy_Page_217_Chunk5574
220 Chapter 2 Instructions: Language of the Computer using a pointer to an automatic variable arr outside the function in which it is defined. my_alloc in C MIPS Code for my_alloc int *my_alloc(int n){ int arr[n]; return arr; } my_alloc: addu $sp,$sp,-4 ; Push sw $fp,0($sp) ; $fp to stack move $fp,$sp ; Save $sp in $fp sll $t0,$a0,2 ; We need 4*n bytes sub $sp,$sp,$t0 ; Make room for arr move $v0,$sp ; Return address of arr move $sp,$fp ; Restore $sp from $fp lw $fp,0(sp) ; Pop $fp addiu $sp,$sp,4 ; from stack jr ra The my_init function is defined as follows (MIPS code): a. my_init: move $t0,$0 ; i=0 move $t1,$a0 L: addi $t2,$t0,10 sw $t2,0($t1) ; v[i]=i+10 addiu $t1,$t1,4 addiu $t0,$t0,1 ; i=i+1 bne $t0,$a1,L ; until i==n jr $ra b. my_init: move $t0,$0 ; i=0 move $t1,$a0 L: sll $t2,$t0,1 addi $t2,$t2,100 sw $t2,0($t1) ; a[i]=100+2*i; addiu $t1,$t1,4 addiu $t0,$t0,1 ; i=i+1 bne $t0,$a1,L ; until i==n jr $ra 2.40.4 [5] <2.18> What are the contents (values of all five elements) of array v right before the “jal sort” instruction in the main code is executed? 2.40.5 [15] <2.18, 2.13> What are the contents of array v right before the sort function enters its outer loop for the first time? Assume that registers $sp, $s0, $s1, $s2, and $s3 have values of 0x1000, 20, 40, 7, and 1, respectively, at the begin- ning of the main code (right before “li $s0, 5” is executed). 2.40.6 [10] <2.18, 2.13> What are the contents of the 5-element array pointed by v right after “jal sort” returns to the main code?
clipped_hennesy_Page_218_Chunk5575
§2.2, page 80: MIPS, C, Java §2.3, page 87: 2) Very slow §2.4, page 93: 3) –8ten §2.5, page 101: 4) sub $s2, $s0, $s1 §2.6, page 105: Both. AND with a mask pattern of 1s will leaves 0s everywhere but the desired field. Shifting left by the right amount removes the bits from the left of the field. Shifting right by the appropriate amount puts the field into the right­most bits of the word, with 0s in the rest of the word. Note that AND leaves the field where it was originally, and the shift pair moves the field into the rightmost part of the word. §2.7, page 111: I. All are true. II. 1). §2.8, page 122: Both are true. §2.9, page 127: I. 2) II. 3) §2.10, page 136: I. 4) +-128K. II. 6) a block of 256M. III. 4) sll §2.11, page 139: Both are true. §2.12, page 148: 4) Machine independence. Answers to Check Yourself 2.21 Exercises 221
clipped_hennesy_Page_219_Chunk5576
3 Numerical precision is the very soul of science. Sir D’arcy Wentworth Thompson On Growth and Form, 1917 Arithmetic for Computers 3.1 Introduction 224 3.2 Addition and Subtraction 224 3.3 Multiplication 230 3.4 Division 236 3.5 Floating Point 242 3.6 Parallelism and Computer Arithmetic: Associativity 270 3.7 Real Stuff: Floating Point in the x86 272 3.8 Fallacies and Pitfalls 275 Computer Organization and Design. DOI: 10.1016/B978-0-12-374750-1.00003-7 © 2012 Elsevier, Inc. All rights reserved.
clipped_hennesy_Page_220_Chunk5577
3.9 Concluding Remarks 280 3.10 Historical Perspective and Further Reading 283 3.11 Exercises 283 The Five Classic Components of a Computer
clipped_hennesy_Page_221_Chunk5578
224 Chapter 3 Arithmetic for Computers 3.1 Introduction Computer words are composed of bits; thus, words can be represented as binary numbers. Chapter 2 shows that integers can be represented either in decimal or binary form, but what about the other numbers that commonly occur? For example: ■ ■What about fractions and other real numbers? ■ ■What happens if an operation creates a number bigger than can be represented? ■ ■And underlying these questions is a mystery: How does hardware really multiply or divide numbers? The goal of this chapter is to unravel these mysteries including representation of real numbers, arithmetic algorithms, hardware that follows these algorithms, and the implications of all this for instruction sets. These insights may explain quirks that you have already encountered with computers. 3.2 Addition and Subtraction Addition is just what you would expect in computers. Digits are added bit by bit from right to left, with carries passed to the next digit to the left, just as you would do by hand. Subtraction uses addition: the appropriate operand is simply negated before being added. Binary Addition and Subtraction Let’s try adding 6ten to 7ten in binary and then subtracting 6ten from 7ten in binary. 0000 0000 0000 0000 0000 0000 0000 0111two = 7ten + 0000 0000 0000 0000 0000 0000 0000 0110two = 6ten = 0000 0000 0000 0000 0000 0000 0000 1101two = 13ten The 4 bits to the right have all the action; Figure 3.1 shows the sums and carries. The carries are shown in parentheses, with the arrows showing how they are passed. Subtraction: Addition’s Tricky Pal No. 10, Top Ten Courses for Athletes at a Football Factory, David Letterman et al., Book of Top Ten Lists, 1990 EXAMPLE
clipped_hennesy_Page_222_Chunk5579
3.2 Addition and Subtraction 225 Subtracting 6ten from 7ten can be done directly: 0000 0000 0000 0000 0000 0000 0000 0111two = 7ten – 0000 0000 0000 0000 0000 0000 0000 0110two = 6ten = 0000 0000 0000 0000 0000 0000 0000 0001two = 1ten or via addition using the two’s complement representation of -6: 0000 0000 0000 0000 0000 0000 0000 0111two = 7ten + 1111 1111 1111 1111 1111 1111 1111 1010two = –6ten = 0000 0000 0000 0000 0000 0000 0000 0001two = 1ten ANSWER Recall that overflow occurs when the result from an operation cannot be represented with the available hardware, in this case a 32-bit word. When can overflow occur in addition? When adding operands with different signs, overflow cannot occur. The reason is the sum must be no larger than one of the operands. For example, -10 + 4 = -6. Since the operands fit in 32 bits and the sum is no larger than an operand, the sum must fit in 32 bits as well. Therefore, no overflow can occur when adding positive and negative operands. There are similar restrictions to the occurrence of overflow during subtract, but it’s just the opposite principle: when the signs of the operands are the same, overflow cannot occur. To see this, remember that x - y = x + (-y) because we subtract by negating the second operand and then add. Therefore, when we subtract operands of the same sign we end up by adding operands of different signs. From the prior paragraph, we know that overflow cannot occur in this case either. Knowing when overflow cannot occur in addition and subtraction is all well and good, but how do we detect it when it does occur? Clearly, adding or subtracting two 32-bit numbers can yield a result that needs 33 bits to be fully expressed. FIGURE 3.1 Binary addition, showing carries from right to left. The rightmost bit adds 1 to 0, resulting in the sum of this bit being 1 and the carry out from this bit being 0. Hence, the operation for the second digit to the right is 0 + 1 + 1. This generates a 0 for this sum bit and a carry out of 1. The third digit is the sum of 1 + 1 + 1, resulting in a carry out of 1 and a sum bit of 1. The fourth bit is 1 + 0 + 0, yielding a 1 sum and no carry. (0) 0 0 0 (0) (0) 0 0 0 (0) (1) 0 0 1 (1) (1) 1 1 1 (1) (0) 1 1 0 (0) (Carries) 1 0 1 (0) . . . . . . . . .
clipped_hennesy_Page_223_Chunk5580
226 Chapter 3 Arithmetic for Computers The lack of a 33rd bit means that when overflow occurs, the sign bit is set with the value of the result instead of the proper sign of the result. Since we need just one extra bit, only the sign bit can be wrong. Hence, overflow occurs when adding two positive numbers and the sum is negative, or vice versa. This means a carry out occurred into the sign bit. Overflow occurs in subtraction when we subtract a negative number from a positive number and get a negative result, or when we subtract a positive number from a negative number and get a positive result. This means a borrow occurred from the sign bit. Figure 3.2 shows the combination of operations, operands, and results that indicate an overflow. We have just seen how to detect overflow for two’s complement numbers in a computer. What about overflow with unsigned integers? Unsigned integers are commonly used for memory addresses where overflows are ignored. The computer designer must therefore provide a way to ignore overflow in some cases and to recognize it in others. The MIPS solution is to have two kinds of arithmetic instructions to recognize the two choices: ■ ■Add (add), add immediate (addi), and subtract (sub) cause exceptions on overflow. ■ ■Add unsigned (addu), add immediate unsigned (addiu), and subtract unsigned (subu) do not cause exceptions on overflow. Because C ignores overflows, the MIPS C compilers will always generate the unsigned versions of the arithmetic instructions addu, addiu, and subu, no matter what the type of the variables. The MIPS Fortran compilers, however, pick the appropriate arithmetic instructions, depending on the type of the operands. Operation Operand A Operand B Result indicating overflow A + B ≥ 0 ≥ 0 < 0 A + B < 0 < 0 ≥ 0 A – B ≥ 0 < 0 < 0 A – B < 0 ≥ 0 ≥ 0 FIGURE 3.2 Overflow conditions for addition and subtraction. Appendix C describes the hardware that performs addition and subtraction, which is called an Arithmetic Logic Unit or ALU. Arithmetic Logic Unit (ALU) Hardware that performs addition, subtraction, and usually logical operations such as AND and OR.
clipped_hennesy_Page_224_Chunk5581
3.2 Addition and Subtraction 227 The computer designer must decide how to handle arithmetic overflows. Although some languages like C and Java ignore integer overflow, languages like Ada and Fortran require that the program be notified. The programmer or the programming environment must then decide what to do when overflow occurs. MIPS detects overflow with an exception, also called an interrupt on many computers. An exception or interrupt is essentially an unscheduled procedure call. The address of the instruction that overflowed is saved in a register, and the computer jumps to a predefined address to invoke the appropriate routine for that exception. The interrupted address is saved so that in some situations the program can continue after corrective code is executed. (Section 4.9 covers exceptions in more detail; Chapters 5 and 6 describe other situations where exceptions and interrupts occur.) MIPS includes a register called the exception program counter (EPC) to contain the address of the instruction that caused the exception. The instruction move from system control (mfc0) is used to copy EPC into a general-purpose register so that MIPS software has the option of returning to the offending instruction via a jump register instruction. Arithmetic for Multimedia Since every desktop microprocessor by definition has its own graphical displays, as transistor budgets increased it was inevitable that support would be added for graphics operations. Many graphics systems originally used 8 bits to represent each of the three primary colors plus 8 bits for a location of a pixel. The addition of speakers and microphones for teleconferencing and video games suggested support of sound as well. Audio samples need more than 8 bits of precision, but 16 bits are sufficient. Every microprocessor has special support so that bytes and halfwords take up less space when stored in memory (see Section 2.9), but due to the infrequency of arithmetic operations on these data sizes in typical integer programs, there is little support beyond data transfers. Architects recognized that many graphics and audio applications would perform the same operation on vectors of this data. By partitioning the carry chains within a 64-bit adder, a processor could perform simultaneous operations on short vectors of eight 8-bit operands, four 16-bit operands, or two 32-bit operands. The cost of such partitioned adders was small. These extensions have been called vector or SIMD, for single instruction, multiple data (see Section 2.17 and Chapter 7). One feature not generally found in general-purpose microprocessors is saturating operations. Saturation means that when a calculation overflows, the result is set Hardware/ Software Interface exception Also called interrupt. An unscheduled event that disrupts program execution; used to detect overflow. interrupt An exception that comes from outside of the processor. (Some architectures use the term interrupt for all exceptions.)
clipped_hennesy_Page_225_Chunk5582
228 Chapter 3 Arithmetic for Computers to the largest positive number or most negative number, rather than a modulo calculation as in two’s complement arithmetic. Saturation is likely what you want for media operations. For example, the volume knob on a radio set would be frustrating if, as you turned, it would get continuously louder for a while and then immediately very soft. A knob with saturation would stop at the highest volume no matter how far you turned it. Figure 3.3 shows arithmetic and logical operations found in many multimedia extensions to modern instruction sets. Instruction category Operands Unsigned add/subtract Eight 8-bit or Four 16-bit Saturating add/subtract Eight 8-bit or Four 16-bit Max/min/minimum Eight 8-bit or Four 16-bit Average Eight 8-bit or Four 16-bit Shift right/left Eight 8-bit or Four 16-bit FIGURE 3.3 Summary of multimedia support for desktop computers. Elaboration: MIPS can trap on overflow, but unlike many other computers, there is no conditional branch to test overflow. A sequence of MIPS instructions can discover overflow. For signed addition, the sequence is the following (see the Elaboration on page 104 in Chapter 2 for a description of the xor instruction): addu $t0, $t1, $t2 # $t0 = sum, but don’t trap xor $t3, $t1, $t2 # Check if signs differ slt $t3, $t3, $zero # $t3 = 1 if signs differ bne $t3, $zero, No_overflow # $t1, $t2 signs ≠, # so no overflow xor $t3, $t0, $t1 # signs =; sign of sum match too? # $t3 negative if sum sign different slt $t3, $t3, $zero # $t3 = 1 if sum sign different bne $t3, $zero, Overflow # All 3 signs ≠; go to overflow For unsigned addition ($t0 = $t1 + $t2), the test is addu $t0, $t1, $t2 # $t0 = sum nor $t3, $t1, $zero # $t3 = NOT $t1 # (2’s comp – 1: 232 – $t1 – 1) sltu $t3, $t3, $t2 # (232 – $t1 – 1) < $t2 # ⇒ 232 – 1 < $t1 + $t2 bne $t3,$zero,Overflow # if(232–1<$t1+$t2) goto overflow
clipped_hennesy_Page_226_Chunk5583
3.2 Addition and Subtraction 229 Summary A major point of this section is that, independent of the representation, the finite word size of computers means that arithmetic operations can create results that are too large to fit in this fixed word size. It’s easy to detect overflow in unsigned numbers, although these are almost always ignored because programs don’t want to detect overflow for address arithmetic, the most common use of natural numbers. Two’s complement presents a greater challenge, yet some software systems require detection of overflow, so today all computers have a way to detect it. The rising popularity of multimedia applications led to arithmetic instructions that support narrower operations that can easily operate in parallel. Some programming languages allow two’s complement integer arithmetic on variables declared byte and half. What MIPS instructions would be used? 1. Load with lbu, lhu; arithmetic with add, sub, mult, div; then store using sb, sh. 2. Load with lb, lh; arithmetic with add, sub, mult, div; then store using sb, sh. 3. Load with lb, lh; arithmetic with add, sub, mult, div, using AND to mask result to 8 or 16 bits after each operation; then store using sb, sh. Elaboration: In the preceding text, we said that you copy EPC into a register via mfc0 and then return to the interrupted code via jump register. This leads to an interesting question: since you must first transfer EPC to a register to use with jump register, how can jump register return to the interrupted code and restore the original values of all registers? Either you restore the old registers first, thereby destroying your return address from EPC, which you placed in a register for use in jump register, or you restore all registers but the one with the return address so that you can jump—meaning an exception would result in changing that one register at any time during program execution! Neither option is satisfactory. To rescue the hardware from this dilemma, MIPS programmers agreed to reserve registers $k0 and $k1 for the operating system; these registers are not restored on exceptions. Just as the MIPS compilers avoid using register $at so that the assembler can use it as a temporary register (see Hardware/Software Interface in Section 2.10), compilers also abstain from using registers $k0 and $k1 to make them available for the operating system. Exception routines place the return address in one of these registers and then use jump register to restore the instruction address. Elaboration: The speed of addition is increased by determining the carry in to the high-order bits sooner. There are a variety of schemes to anticipate the carry so that the worst-case scenario is a function of the log 2 of the number of bits in the adder. These anticipatory signals are faster because they go through fewer gates in sequence, but it takes many more gates to anticipate the proper carry. The most popular is carry lookahead, which Section C.6 in Appendix C on the CD describes. Check Yourself
clipped_hennesy_Page_227_Chunk5584
230 Chapter 3 Arithmetic for Computers 3.3 Multiplication Now that we have completed the explanation of addition and subtraction, we are ready to build the more vexing operation of multiplication. First, let’s review the multiplication of decimal numbers in longhand to remind ourselves of the steps of multiplication and the names of the operands. For reasons that will become clear shortly, we limit this decimal example to using only the digits 0 and 1. Multiplying 1000ten by 1001ten: Multiplication is vexation, Division is as bad; The rule of three doth puzzle me, And practice drives me mad. Anonymous, Elizabethan manuscript, 1570 Multiplicand 1000ten Multiplier x 1001ten 1000 0000 0000 1000 Product 1001000ten The first operand is called the multiplicand and the second the multiplier. The final result is called the product. As you may recall, the algorithm learned in grammar school is to take the digits of the multiplier one at a time from right to left, multiplying the multiplicand by the single digit of the multiplier, and shifting the intermediate product one digit to the left of the earlier intermediate products. The first observation is that the number of digits in the product is considerably larger than the number in either the multiplicand or the multiplier. In fact, if we ignore the sign bits, the length of the multiplication of an n-bit multiplicand and an m-bit multiplier is a product that is n + m bits long. That is, n + m bits are required to represent all possible products. Hence, like add, multiply must cope with overflow because we frequently want a 32-bit product as the result of multiplying two 32-bit numbers. In this example, we restricted the decimal digits to 0 and 1. With only two choices, each step of the multiplication is simple: 1. Just place a copy of the multiplicand (1 × multiplicand) in the proper place if the multiplier digit is a 1, or 2. Place 0 (0 × multiplicand) in the proper place if the digit is 0. Although the decimal example above happens to use only 0 and 1, multiplication of binary numbers must always use 0 and 1, and thus always offers only these two choices.
clipped_hennesy_Page_228_Chunk5585
Now that we have reviewed the basics of multiplication, the traditional next step is to provide the highly optimized multiply hardware. We break with tradition in the belief that you will gain a better understanding by seeing the evolution of the multiply hardware and algorithm through multiple generations. For now, let’s assume that we are multiplying only positive numbers. Sequential Version of the Multiplication Algorithm and Hardware This design mimics the algorithm we learned in grammar school; Figure 3.4 shows the hardware. We have drawn the hardware so that data flows from top to bottom to resemble more closely the paper-and-pencil method. Let’s assume that the multiplier is in the 32-bit Multiplier register and that the 64-bit Product register is initialized to 0. From the paper-and-pencil example above, it’s clear that we will need to move the multiplicand left one digit each step, as it may be added to the intermediate products. Over 32 steps, a 32-bit multipli- cand would move 32 bits to the left. Hence, we need a 64-bit Multiplicand register, initialized with the 32-bit multiplicand in the right half and zero in the left half. This register is then shifted left 1 bit each step to align the multiplicand with the sum being accumulated in the 64-bit Product register. Figure 3.5 shows the three basic steps needed for each bit. The least significant bit of the multiplier (Multiplier0) determines whether the multiplicand is added to FIGURE 3.4 First version of the multiplication hardware. The Multiplicand register, ALU, and Product register are all 64 bits wide, with only the Multiplier register containing 32 bits. ( Appendix C describes ALUs.) The 32-bit multiplicand starts in the right half of the Multiplicand register and is shifted left 1 bit on each step. The multiplier is shifted in the opposite direction at each step. The algorithm starts with the product initialized to 0. Control decides when to shift the Multiplicand and Multiplier registers and when to write new values into the Product register. Multiplicand Shift left 64 bits 64-bit ALU Product Write 64 bits Control test Multiplier Shift right 32 bits 3.3 Multiplication 231
clipped_hennesy_Page_229_Chunk5586
232 Chapter 3 Arithmetic for Computers the Product register. The left shift in step 2 has the effect of moving the intermediate operands to the left, just as when multiplying with paper and pencil. The shift right in step 3 gives us the next bit of the multiplier to examine in the following iteration. These three steps are repeated 32 times to obtain the product. If each step took a clock cycle, this algorithm would require almost 100 clock cycles to multiply FIGURE 3.5 The first multiplication algorithm, using the hardware shown in Figure 3.4. If the least significant bit of the multiplier is 1, add the multiplicand to the product. If not, go to the next step. Shift the multiplicand left and the multiplier right in the next two steps. These three steps are repeated 32 times. 32nd repetition? 1a. Add multiplicand to product and place the result in Product register Multiplier0 = 0 1. Test Multiplier0 Start Multiplier0 = 1 2. Shift the Multiplicand register left 1 bit 3. Shift the Multiplier register right 1 bit No: < 32 repetitions Yes: 32 repetitions Done
clipped_hennesy_Page_230_Chunk5587
two 32-bit numbers. The relative importance of arithmetic operations like multiply varies with the program, but addition and subtraction may be anywhere from 5 to 100 times more popular than multiply. Accordingly, in many applications, multiply can take multiple clock cycles without significantly affecting performance. Yet Amdahl’s law (see Section 1.8) reminds us that even a moderate frequency for a slow operation can limit performance. This algorithm and hardware are easily refined to take 1 clock cycle per step. The speed-up comes from performing the operations in parallel: the multiplier and multiplicand are shifted while the multiplicand is added to the product if the multiplier bit is a 1. The hardware just has to ensure that it tests the right bit of the multiplier and gets the preshifted version of the multiplicand. The hardware is usually further optimized to halve the width of the adder and registers by noticing where there are unused portions of registers and adders. Figure 3.6 shows the revised hardware. Replacing arithmetic by shifts can also occur when multiplying by constants. Some compilers replace multiplies by short constants with a series of shifts and adds. Because one bit to the left represents a number twice as large in base 2, shifting the bits left has the same effect as multiplying by a power of 2. As mentioned in Chapter 2, almost every compiler will perform the strength reduction optimization of substituting a left shift for a multiply by a power of 2. Hardware/ Software Interface FIGURE 3.6 Refined version of the multiplication hardware. Compare with the first version in Figure 3.4. The Multiplicand register, ALU, and Multiplier register are all 32 bits wide, with only the Product register left at 64 bits. Now the product is shifted right. The separate Multiplier register also disappeared. The multiplier is placed instead in the right half of the Product register. These changes are highlighted in color. (The Product register should really be 65 bits to hold the carry out of the adder, but it’s shown here as 64 bits to highlight the evolution from Figure 3.4.) Multiplicand 32 bits 32-bit ALU Product Write 64 bits Control test Shift right 3.3 Multiplication 233
clipped_hennesy_Page_231_Chunk5588
234 Chapter 3 Arithmetic for Computers A Multiply Algorithm Using 4-bit numbers to save space, multiply 2ten × 3ten, or 0010two × 0011two. Figure 3.7 shows the value of each register for each of the steps labeled according to Figure 3.5, with the final value of 0000 0110two or 6ten. Color is used to indicate the register values that change on that step, and the bit circled is the one examined to determine the operation of the next step. Signed Multiplication So far, we have dealt with positive numbers. The easiest way to understand how to deal with signed numbers is to first convert the multiplier and multiplicand to positive numbers and then remember the original signs. The algorithms should then be run for 31 iterations, leaving the signs out of the calculation. As we learned in grammar school, we need negate the product only if the original signs disagree. It turns out that the last algorithm will work for signed numbers, provided that we remember that we are dealing with numbers that have infinite digits, and we are only representing them with 32 bits. Hence, the shifting steps would need to extend the sign of the product for signed numbers. When the algorithm completes, the lower word would have the 32-bit product. EXAMPLE ANSWER Iteration Step Multiplier Multiplicand Product 0 Initial values 0011 0000 0010 0000 0000 1 1a: 1 ⇒ Prod = Prod + Mcand 0011 0000 0010 0000 0010 2: Shift left Multiplicand 0011 0000 0100 0000 0010 3: Shift right Multiplier 0001 0000 0100 0000 0010 2 1a: 1 ⇒ Prod = Prod + Mcand 0001 0000 0100 0000 0110 2: Shift left Multiplicand 0001 0000 1000 0000 0110 3: Shift right Multiplier 0000 0000 1000 0000 0110 3 1: 0 ⇒ No operation 0000 0000 1000 0000 0110 2: Shift left Multiplicand 0000 0001 0000 0000 0110 3: Shift right Multiplier 0000 0001 0000 0000 0110 4 1: 0 ⇒ No operation 0000 0001 0000 0000 0110 2: Shift left Multiplicand 0000 0010 0000 0000 0110 3: Shift right Multiplier 0000 0010 0000 0000 0110 FIGURE 3.7 Multiply example using algorithm in Figure 3.5. The bit examined to determine the next step is circled in color.
clipped_hennesy_Page_232_Chunk5589
Faster Multiplication Moore’s law has provided so much more in resources that hardware designers can now build much faster multiplication hardware. Whether the multiplicand is to be added or not is known at the beginning of the multiplication by looking at each of the 32 multiplier bits. Faster multiplications are possible by essentially providing one 32-bit adder for each bit of the multiplier: one input is the multiplicand ANDed with a multiplier bit, and the other is the output of a prior adder. A straightforward approach would be to connect the outputs of adders on the right to the inputs of adders on the left, making a stack of adders 32 high. An alternative way to organize these 32 additions is in a parallel tree, as Figure 3.8 shows. Instead of waiting for 32 add times, we wait just the log2 (32) or five 32-bit add times. Figure 3.8 shows how this is a faster way to connect them. In fact, multiply can go even faster than five add times because of the use of carry save adders (see Section C.6 in Appendix C) and because it is easy to pipeline such a design to be able to support many multiplies simultaneously (see Chapter 4). Multiply in MIPS MIPS provides a separate pair of 32-bit registers to contain the 64-bit product, called Hi and Lo. To produce a properly signed or unsigned product, MIPS has two instructions: multiply (mult) and multiply unsigned (multu). To fetch the integer 32-bit product, the programmer uses move from lo (mflo). The MIPS assembler generates a pseudoinstruction for multiply that specifies three general- purpose registers, generating mflo and mfhi instructions to place the product into registers. Summary Multiplication hardware is simply shifts and add, derived from the paper-and- pencil method learned in grammar school. Compilers even use shift instructions for multiplications by powers of 2. Both MIPS multiply instructions ignore overflow, so it is up to the software to check to see if the product is too big to fit in 32 bits. There is no overflow if Hi is 0 for multu or the replicated sign of Lo for mult. The instruction move from hi (mfhi) can be used to transfer Hi to a general-purpose register to test for overflow. Hardware/ Software Interface 3.3 Multiplication 235
clipped_hennesy_Page_233_Chunk5590
236 Chapter 3 Arithmetic for Computers 3.4 Division The reciprocal operation of multiply is divide, an operation that is even less frequent and even more quirky. It even offers the opportunity to perform a mathematically invalid operation: dividing by 0. Let’s start with an example of long division using decimal numbers to recall the names of the operands and the grammar school division algorithm. For reasons similar to those in the previous section, we limit the decimal digits to just 0 or 1. The example is dividing 1,001,010ten by 1000ten: 1001ten Quotient Divisor 1000ten 1001010ten Dividend -1000 10 101 1010 -1000 10ten Remainder Divide et impera. Latin for “Divide and rule,” ancient political maxim cited by Machiavelli, 1532 FIGURE 3.8 Fast multiplication hardware. Rather than use a single 32-bit adder 31 times, this hardware “unrolls the loop” to use 31 adders and then organizes them to minimize delay. Product1 Product0 Product63 Product62 Product47..16 1 bit 1 bit 1 bit 1 bit . . . . . . . . . . . . . . . . . . 32 bits 32 bits 32 bits 32 bits 32 bits 32 bits 32 bits Mplier31 • Mcand Mplier30 • Mcand Mplier29 • Mcand Mplier28 • Mcand Mplier3 • Mcand Mplier2 • Mcand Mplier1 • Mcand Mplier0 • Mcand
clipped_hennesy_Page_234_Chunk5591
Divide’s two operands, called the dividend and divisor, and the result, called the quotient, are accompanied by a second result, called the remainder. Here is another way to express the relationship between the components: Dividend = Quotient × Divisor + Remainder where the remainder is smaller than the divisor. Infrequently, programs use the divide instruction just to get the remainder, ignoring the quotient. The basic grammar school division algorithm tries to see how big a number can be subtracted, creating a digit of the quotient on each attempt. Our carefully selected decimal example uses only the numbers 0 and 1, so it’s easy to figure out how many times the divisor goes into the portion of the dividend: it’s either 0 times or 1 time. Binary numbers contain only 0 or 1, so binary division is restricted to these two choices, thereby simplifying binary division. Let’s assume that both the dividend and the divisor are positive and hence the quotient and the remainder are nonnegative. The division operands and both results are 32-bit values, and we will ignore the sign for now. A Division Algorithm and Hardware Figure 3.9 shows hardware to mimic our grammar school algorithm. We start with the 32-bit Quotient register set to 0. Each iteration of the algorithm needs to move the divisor to the right one digit, so we start with the divisor placed in the left half of the 64-bit Divisor register and shift it right 1 bit each step to align it with the dividend. The Remainder register is initialized with the dividend. dividend A number being divided. divisor A number that the dividend is divided by. quotient The primary result of a division; a number that when multiplied by the divisor and added to the remainder produces the dividend. remainder The secondary result of a division; a number that when added to the product of the quotient and the divisor produces the dividend. FIGURE 3.9 First version of the division hardware. The Divisor register, ALU, and Remainder register are all 64 bits wide, with only the Quotient register being 32 bits. The 32-bit divisor starts in the left half of the Divisor register and is shifted right 1 bit each iteration. The remainder is initialized with the dividend. Control decides when to shift the Divisor and Quotient registers and when to write the new value into the Remainder register. Divisor Shift right 64 bits 64-bit ALU Remainder Write 64 bits Control test Quotient Shift left 32 bits 3.4 Division 237
clipped_hennesy_Page_235_Chunk5592
238 Chapter 3 Arithmetic for Computers 33rd repetition? . Shift the Quotient register to the left, setting the new rightmost bit to 1 Remainder < 0 Remainder ≥ 0 Test Remainder Start 3. Shift the Divisor register right 1 bit No: < 33 repetitions Yes: 33 repetitions Done 1. Subtract the Divisor register from the Remainder register and place the result in the Remainder register 2b. Restore the original value by adding the Divisor register to the Remainder register and placing the sum in the Remainder register. Also shift the Quotient register to the left, setting the new least significant bit to 0 2a FIGURE 3.10 A division algorithm, using the hardware in Figure 3.9. If the remainder is positive, the divisor did go into the dividend, so step 2a generates a 1 in the quotient. A negative remainder after step 1 means that the divisor did not go into the dividend, so step 2b generates a 0 in the quotient and adds the divisor to the remainder, thereby reversing the subtraction of step 1. The final shift, in step 3, aligns the divisor properly, relative to the dividend for the next iteration. These steps are repeated 33 times.
clipped_hennesy_Page_236_Chunk5593
Figure 3.10 shows three steps of the first division algorithm. Unlike a human, the computer isn’t smart enough to know in advance whether the divisor is smaller than the dividend. It must first subtract the divisor in step 1; remember that this is how we performed the comparison in the set on less than instruction. If the result is positive, the divisor was smaller or equal to the dividend, so we generate a 1 in the quotient (step 2a). If the result is negative, the next step is to restore the original value by adding the divisor back to the remainder and generate a 0 in the quotient (step 2b). The divisor is shifted right and then we iterate again. The remainder and quotient will be found in their namesake registers after the iterations are complete. A Divide Algorithm Using a 4-bit version of the algorithm to save pages, let’s try dividing 7ten by 2ten, or 0000 0111two by 0010two. Figure 3.11 shows the value of each register for each of the steps, with the quotient being 3ten and the remainder 1ten. Notice that the test in step 2 of whether the remainder is positive or negative simply tests whether the sign bit of the Remainder register is a 0 or 1. The surprising requirement of this algorithm is that it takes n + 1 steps to get the proper quotient and remainder. This algorithm and hardware can be refined to be faster and cheaper. The speed- up comes from shifting the operands and the quotient simultaneously with the subtraction. This refinement halves the width of the adder and registers by ­noticing where there are unused portions of registers and adders. Figure 3.12 shows the revised hardware. Signed Division So far, we have ignored signed numbers in division. The simplest solution is to remember the signs of the divisor and dividend and then negate the quotient if the signs disagree. Elaboration: The one complication of signed division is that we must also set the sign of the remainder. Remember that the following equation must always hold: Dividend = Quotient × Divisor + Remainder To understand how to set the sign of the remainder, let’s look at the example of dividing all the combinations of ±7ten by ±2ten. The first case is easy: +7 ÷ +2: Quotient = +3, Remainder = +1 EXAMPLE ANSWER 3.4 Division 239
clipped_hennesy_Page_237_Chunk5594
240 Chapter 3 Arithmetic for Computers Checking the results: 7 = 3 × 2 + (+1) = 6 + 1 If we change the sign of the dividend, the quotient must change as well: –7 ÷ +2: Quotient = –3 Iteration Step Quotient Divisor Remainder 0 Initial values 0000 0010 0000 0000 0111 1 1: Rem = Rem – Div 0000 0010 0000 1110 0111 2b: Rem < 0 ⇒ +Div, sll Q, Q0 = 0 0000 0010 0000 0000 0111 3: Shift Div right 0000 0001 0000 0000 0111 2 1: Rem = Rem – Div 0000 0001 0000 1111 0111 2b: Rem < 0 ⇒ +Div, sll Q, Q0 = 0 0000 0001 0000 0000 0111 3: Shift Div right 0000 0000 1000 0000 0111 3 1: Rem = Rem – Div 0000 0000 1000 1111 1111 2b: Rem < 0 ⇒ +Div, sll Q, Q0 = 0 0000 0000 1000 0000 0111 3: Shift Div right 0000 0000 0100 0000 0111 4 1: Rem = Rem – Div 0000 0000 0100 0000 0011 2a: Rem ≥ 0 ⇒ sll Q, Q0 = 1 0001 0000 0100 0000 0011 3: Shift Div right 0001 0000 0010 0000 0011 5 1: Rem = Rem – Div 0001 0000 0010 0000 0001 2a: Rem ≥ 0 ⇒ sll Q, Q0 = 1 0011 0000 0010 0000 0001 3: Shift Div right 0011 0000 0001 0000 0001 FIGURE 3.11 Division example using the algorithm in Figure 3.10. The bit examined to determine the next step is circled in color. FIGURE 3.12 An improved version of the division hardware. The Divisor register, ALU, and Quotient register are all 32 bits wide, with only the Remainder register left at 64 bits. Compared to Figure 3.9, the ALU and Divisor registers are halved and the remainder is shifted left. This version also combines the Quotient register with the right half of the Remainder register. (As in Figure 3.6, the Remainder register should really be 65 bits to make sure the carry out of the adder is not lost.) Divisor 32 bits 32-bit ALU Remainder Write 64 bits Control test Shift left Shift right
clipped_hennesy_Page_238_Chunk5595
Rewriting our basic formula to calculate the remainder: Remainder = (Dividend – Quotient × Divisor) = –7 – (–3 × +2) = –7–(–6) = –1 So, –7 ÷ +2: Quotient = –3, Remainder = –1 Checking the results again: –7 = –3 × 2 + (–1) = – 6 – 1 The reason the answer isn’t a quotient of –4 and a remainder of +1, which would also fit this formula, is that the absolute value of the quotient would then change depending on the sign of the dividend and the divisor! Clearly, if –(x ÷ y) ≠ (–x) ÷ y programming would be an even greater challenge. This anomalous behavior is avoided by following the rule that the dividend and remainder must have the same signs, no matter what the signs of the divisor and quotient. We calculate the other combinations by following the same rule: +7 ÷ –2: Quotient = –3, Remainder = +1 –7 ÷ –2: Quotient = +3, Remainder = –1 Thus the correctly signed division algorithm negates the quotient if the signs of the operands are opposite and makes the sign of the nonzero remainder match the dividend. Faster Division We used many adders to speed up multiply, but we cannot do the same trick for divide. The reason is that we need to know the sign of the difference before we can perform the next step of the algorithm, whereas with multiply we could calculate the 32 partial products immediately. There are techniques to produce more than one bit of the quotient per step. The SRT division technique tries to guess several quotient bits per step, using a table lookup based on the upper bits of the dividend and remainder. It relies on subsequent steps to correct wrong guesses. A typical value today is 4 bits. The key is guessing the value to subtract. With binary division, there is only a single choice. These algorithms use 6 bits from the remainder and 4 bits from the divisor to index a table that determines the guess for each step. The accuracy of this fast method depends on having proper values in the lookup table. The fallacy on page 276 in Section 3.8 shows what can happen if the table is incorrect. Divide in MIPS You may have already observed that the same sequential hardware can be used for both multiply and divide in Figures 3.6 and 3.12. The only requirement is a 64-bit register that can shift left or right and a 32-bit ALU that adds or subtracts. Hence, MIPS uses the 32-bit Hi and 32-bit Lo registers for both multiply and divide. 3.4 Division 241
clipped_hennesy_Page_239_Chunk5596
242 Chapter 3 Arithmetic for Computers As we might expect from the algorithm above, Hi contains the remainder, and Lo contains the quotient after the divide instruction completes. To handle both signed integers and unsigned integers, MIPS has two instruc- tions: divide (div) and divide unsigned (divu). The MIPS assembler allows divide instructions to specify three registers, generating the mflo or mfhi instructions to place the desired result into a general-purpose register. Summary The common hardware support for multiply and divide allows MIPS to provide a single pair of 32-bit registers that are used both for multiply and divide. Figure 3.13 summarizes the additions to the MIPS architecture for the last two sections. MIPS divide instructions ignore overflow, so software must determine whether the quotient is too large. In addition to overflow, division can also result in an improper calculation: division by 0. Some computers distinguish these two anomalous events. MIPS software must check the divisor to discover division by 0 as well as overflow. Elaboration: An even faster algorithm does not immediately add the divisor back if the remainder is negative. It simply adds the dividend to the shifted remainder in the following step, since (r + d) × 2 – d = r × 2 + d × 2 – d = r × 2 + d. This nonrestoring division algorithm, which takes 1 clock cycle per step, is explored further in the exercises; the algorithm here is called restoring division. A third algorithm that doesn’t save the result of the subtract if its negative is called a nonperforming division algorithm. It averages one-third fewer arithmetic operations. 3.5 Floating Point Going beyond signed and unsigned integers, programming languages support numbers with fractions, which are called reals in mathematics. Here are some examples of reals: 3.14159265 . . .ten (pi) 2.71828 . . .ten (e) 0.000000001ten or 1.0ten × 10-9 (seconds in a nanosecond) 3,155,760,000ten or 3.15576ten × 109 (seconds in a typical century) Hardware/ Software Interface Speed gets you nowhere if you’re headed the wrong way. American proverb
clipped_hennesy_Page_240_Chunk5597
MIPS assembly language Category Instruction Example Meaning Comments Arithmetic add add $s1,$s2,$s3 $s1 = $s2 + $s3 Three operands; overflow detected subtract sub $s1,$s2,$s3 $s1 = $s2 – $s3 Three operands; overflow detected add immediate addi $s1,$s2,100 $s1 = $s2 + 100 + constant; overflow detected add unsigned addu $s1,$s2,$s3 $s1 = $s2 + $s3 Three operands; overflow undetected subtract unsigned subu $s1,$s2,$s3 $s1 = $s2 – $s3 Three operands; overflow undetected add immediate unsigned addiu $s1,$s2,100 $s1 = $s2 + 100 + constant; overflow undetected move from coprocessor register mfc0 $s1,$epc $s1 = $epc Copy Exception PC + special regs multiply mult $s2,$s3 Hi, Lo = $s2 × $s3 64-bit signed product in Hi, Lo multiply unsigned multu $s2,$s3 Hi, Lo = $s2 × $s3 64-bit unsigned product in Hi, Lo divide div $s2,$s3 Lo = $s2 / $s3, Hi = $s2 mod $s3 Lo = quotient, Hi = remainder divide unsigned divu $s2,$s3 Lo = $s2 / $s3, Hi = $s2 mod $s3 Unsigned quotient and remainder move from Hi mfhi $s1 $s1 = Hi Used to get copy of Hi move from Lo mflo $s1 $s1 = Lo Used to get copy of Lo Data transfer load word lw $s1,20($s2) $s1 = Memory[$s2 + 20] Word from memory to register store word sw $s1,20($s2) Memory[$s2 + 20] = $s1 Word from register to memory load half unsigned lhu $s1,20($s2) $s1 = Memory[$s2 + 20] Halfword memory to register store half sh $s1,20($s2) Memory[$s2 + 20] = $s1 Halfword register to memory load byte unsigned lbu $s1,20($s2) $s1 = Memory[$s2 + 20] Byte from memory to register store byte sb $s1,20($s2) Memory[$s2 + 20] = $s1 Byte from register to memory load linked word ll $s1,20($s2) $s1 = Memory[$s2 + 20] Load word as 1st half of atomic swap store conditional word sc $s1,20($s2) Memory[$s2+20]=$s1;$s1=0 or 1 Store word as 2nd half atomic swap load upper immediate lui $s1,100 $s1 = 100 * 216 Loads constant in upper 16 bits Logical AND AND $s1,$s2,$s3 $s1 = $s2 & $s3 Three reg. operands; bit-by-bit AND OR OR $s1,$s2,$s3 $s1 = $s2 | $s3 Three reg. operands; bit-by-bit OR NOR NOR $s1,$s2,$s3 $s1 = ~ ($s2 |$s3) Three reg. operands; bit-by-bit NOR AND immediate ANDi $s1,$s2,100 $s1 = $s2 & 100 Bit-by-bit AND with constant OR immediate ORi $s1,$s2,100 $s1 = $s2 | 100 Bit-by-bit OR with constant shift left logical sll $s1,$s2,10 $s1 = $s2 << 10 Shift left by constant shift right logical srl $s1,$s2,10 $s1 = $s2 >> 10 Shift right by constant Condi- tional branch branch on equal beq $s1,$s2,25 if ($s1 == $s2) go to PC + 4 + 100 Equal test; PC-relative branch branch on not equal bne $s1,$s2,25 if ($s1 != $s2) go to PC + 4 + 100 Not equal test; PC-relative set on less than slt $s1,$s2,$s3 if ($s2 < $s3) $s1 = 1; else $s1 = 0 Compare less than; two’s complement set less than immediate slti $s1,$s2,100 if ($s2 < 100) $s1 = 1; else $s1=0 Compare < constant; two’s complement set less than unsigned sltu $s1,$s2,$s3 if ($s2 < $s3) $s1 = 1; else $s1=0 Compare less than; natural numbers set less than immediate unsigned sltiu $s1,$s2,100 if ($s2 < 100) $s1 = 1; else $s1 = 0 Compare < constant; natural numbers Uncondi- tional jump jump j 2500 go to 10000 Jump to target address jump register jr $ra go to $ra For switch, procedure return jump and link jal 2500 $ra = PC + 4; go to 10000 For procedure call FIGURE 3.13 MIPS core architecture. The memory and registers of the MIPS architecture are not included for space reasons, but this section added the Hi and Lo registers to support multiply and divide. MIPS machine language is listed in the MIPS Reference Data Card at the front of this book. 3.5 Floating Point 243
clipped_hennesy_Page_241_Chunk5598
244 Chapter 3 Arithmetic for Computers Notice that in the last case, the number didn’t represent a small fraction, but it was bigger than we could represent with a 32-bit signed integer. The alternative notation for the last two numbers is called scientific notation, which has a single digit to the left of the decimal point. A number in scientific notation that has no leading 0s is called a normalized number, which is the usual way to write it. For example, 1.0ten × 10-9 is in normalized scientific notation, but 0.1ten × 10-8 and 10.0ten × 10 -10 are not. Just as we can show decimal numbers in scientific notation, we can also show binary numbers in scientific notation: 1.0two × 2-1 To keep a binary number in normalized form, we need a base that we can increase or decrease by exactly the number of bits the number must be shifted to have one nonzero digit to the left of the decimal point. Only a base of 2 fulfills our need. Since the base is not 10, we also need a new name for decimal point; binary point will do fine. Computer arithmetic that supports such numbers is called floating point because it represents numbers in which the binary point is not fixed, as it is for integers. The programming language C uses the name float for such numbers. Just as in scientific notation, numbers are represented as a single nonzero digit to the left of the binary point. In binary, the form is 1.xxxxxxxxxtwo × 2yyyy (Although the computer represents the exponent in base 2 as well as the rest of the number, to simplify the notation we show the exponent in decimal.) A standard scientific notation for reals in normalized form offers three advantages. It simplifies exchange of data that includes floating-point numbers; it simplifies the floating-point arithmetic algorithms to know that numbers will always be in this form; and it increases the accuracy of the numbers that can be stored in a word, since the unnecessary leading 0s are replaced by real digits to the right of the binary point. Floating-Point Representation A designer of a floating-point representation must find a compromise between the size of the fraction and the size of the exponent, because a fixed word size means you must take a bit from one to add a bit to the other. This tradeoff is between precision and range: increasing the size of the fraction enhances the precision of the fraction, while increasing the size of the exponent increases the range of numbers that can be represented. As our design guideline from Chapter 2 reminds us, good design demands good compromise. Floating-point numbers are usually a multiple of the size of a word. The representation of a MIPS floating-point number is shown below, where s is the sign of the floating-point number (1 meaning negative), exponent is the value of the 8-bit exponent field (including the sign of the exponent), and fraction is the scientific notation A notation that renders numbers with a single digit to the left of the decimal point. normalized A number in floating-point notation that has no leading 0s. floating point Computer arithmetic that represents numbers in which the binary point is not fixed. fraction The value, generally between 0 and 1, placed in the fraction field. exponent In the numerical representation system of floating-point arithmetic, the value that is placed in the exponent field.
clipped_hennesy_Page_242_Chunk5599
23-bit number. This representation is called sign and magnitude, since the sign is a separate bit from the rest of the 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 s exponent fraction 1 bit 8 bits 23 bits In general, floating-point numbers are of the form (-1)S × F × 2E F involves the value in the fraction field and E involves the value in the exponent field; the exact relationship to these fields will be spelled out soon. (We will shortly see that MIPS does something slightly more sophisticated.) These chosen sizes of exponent and fraction give MIPS computer arithmetic an extraordinary range. Fractions almost as small as 2.0ten × 10-38 and numbers almost as large as 2.0ten × 1038 can be represented in a computer. Alas, extraordinary differs from infinite, so it is still possible for numbers to be too large. Thus, overflow interrupts can occur in floating-point arithmetic as well as in integer arithmetic. Notice that overflow here means that the exponent is too large to be represented in the exponent field. Floating point offers a new kind of exceptional event as well. Just as programmers will want to know when they have calculated a number that is too large to be represented, they will want to know if the nonzero fraction they are calculating has become so small that it cannot be represented; either event could result in a program giving incorrect answers. To distinguish it from overflow, we call this event underflow. This situation occurs when the negative exponent is too large to fit in the exponent field. One way to reduce chances of underflow or overflow is to offer another format that has a larger exponent. In C this number is called double, and operations on doubles are called double precision floating-point arithmetic; single precision floating point is the name of the earlier format. The representation of a double precision floating-point number takes two MIPS words, as shown below, where s is still the sign of the number, exponent is the value of the 11-bit exponent field, and fraction is the 52-bit number in the fraction field. 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 s exponent fraction 1 bit 11 bits 20 bits fraction (continued) 32 bits MIPS double precision allows numbers almost as small as 2.0ten × 10-308 and almost as large as 2.0ten × 10308. Although double precision does increase the overflow (floating- point) A situation in which a positive exponent becomes too large to fit in the exponent field. underflow (floating- point) A situation in which a negative exponent becomes too large to fit in the exponent field. double precision A floating-point value represented in two 32-bit words. single precision A floating-point value represented in a single ­ 32-bit word. 3.5 Floating Point 245
clipped_hennesy_Page_243_Chunk5600