text
stringlengths
1
7.76k
source
stringlengths
17
81
46 Chapter 1 Computer Abstractions and Technology each wafer, creating the transistors, conductors, and insulators discussed ear­lier. Today’s integrated circuits contain only one layer of transistors but may have from two to eight levels of metal conductor, separated by layers of insulators. A single microscopic flaw in the wafer itself or in one of the dozens of pattern­ ing steps can result in that area of the wafer failing. These defects, as they are called, make it virtually impossible to manufacture a perfect wafer. To cope with imperfection, several strategies have been used, but the simplest is to place many independent components on a single wafer. The patterned wafer is then chopped up, or diced, into these components, called dies and more informally known as chips. Figure 1.19 is a photograph of a wafer containing microprocessors before they have been diced; earlier, Figure 1.9 on page 20 shows an individual micro­ processor die and its major components. Dicing enables you to discard only those dies that were unlucky enough to con­ tain the flaws, rather than the whole wafer. This concept is quantified by the yield of a process, which is defined as the percentage of good dies from the total num­ber of dies on the wafer. The cost of an integrated circuit rises quickly as the die size increases, due both to the lower yield and the smaller number of dies that fit on a wafer. To reduce the cost, a large die is often “shrunk” by using the next generation process, which incorporates smaller sizes for both transistors and wires. This improves the yield and the die count per wafer. Once you’ve found good dies, they are connected to the input/output pins of a package, using a process called bonding. These packaged parts are tested a final time, since mistakes can occur in packaging, and then they are shipped to cus­tomers. As mentioned above, an increasingly important design constraint is power. Power is a challenge for two reasons. First, power must be brought in and distrib­ uted around the chip; modern microprocessors use hundreds of pins just for power and ground! Similarly, multiple levels of interconnect are used solely for power and ground distribution to portions of the chip. Second, power is dissi­pated as heat and must be removed. An AMD Opteron X4 model 2356 2.0 GHz burns 120 watts in 2008, which must be removed from a chip whose surface area is just over 1 cm2! Elaboration: The cost of an integrated circuit can be expressed in three simple equations: Cost per die = ​ Cost per wafer ____________________ Dies per wafer × yield ​ Dies per wafer ≈ ​ Wafer area __________ Die area ​ Yield = ​ 1 __________________________________ (1 + (Defects per area × Die area/2))2 ​ defect A microscopic flaw in a wafer or in patterning steps that can result in the failure of the die containing that defect. die The individual rectangular sections that are cut from a wafer, more informally known as chips. yield The percentage of good dies from the total number of dies on the wafer.
clipped_hennesy_Page_44_Chunk5401
The first equation is straightforward to derive. The second is an approximation, since it does not subtract the area near the border of the round wafer that cannot accommodate the rectangu­lar dies (see Figure 1.19). The final equation is based on empirical observations of yields at inte­grated circuit factories, with the exponent related to the number of critical processing steps. Hence, depending on the defect rate and the size of the die and wafer, costs are generally not linear in die area. FIGURE 1.19 A 12-inch (300mm) wafer of AMD Opteron X2 chips, the predecessor of Opteron X4 chips (Courtesy AMD). The number of dies per wafer at 100% yield is 117. The several dozen partially rounded chips at the boundaries of the wafer are useless; they are included because it’s easier to create the masks used to pattern the silicon. This die uses a 90-nanometer technology, which means that the smallest transistors are approximately 90 nm in size, although they are typically somewhat smaller than the actual feature size, which refers to the size of the transistors as “drawn” versus the final manufactured size. 1.7 Real Stuff: Manufacturing and Benchmarking the AMD Opteron X4 47
clipped_hennesy_Page_45_Chunk5402
48 Chapter 1 Computer Abstractions and Technology SPEC CPU Benchmark A computer user who runs the same programs day in and day out would be the perfect candidate to evaluate a new computer. The set of programs run would form a workload. To evaluate two computer systems, a user would simply com­pare the execution time of the workload on the two computers. Most users, how­ever, are not in this situation. Instead, they must rely on other methods that measure the performance of a candidate computer, hoping that the methods will reflect how well the computer will perform with the user’s workload. This alterna­tive is usually followed by evaluating the computer using a set of benchmarks—programs specifically chosen to measure performance. The benchmarks form a workload that the user hopes will predict the performance of the actual workload. SPEC (System Performance Evaluation Cooperative) is an effort funded and supported by a number of computer vendors to create standard sets of bench­marks for modern computer systems. In 1989, SPEC originally created a bench­mark set focusing on processor performance (now called SPEC89), which has evolved through five generations. The latest is SPEC CPU2006, which consists of a set of 12 integer benchmarks (CINT2006) and 17 floating-point benchmarks (CFP2006). The integer benchmarks vary from part of a C compiler to a chess program to a quantum computer simulation. The floating-point benchmarks include structured grid codes for finite element modeling, particle method codes for molecular dynamics, and sparse linear algebra codes for fluid dynam­ics. Figure 1.20 describes the SPEC integer benchmarks and their execution time on the Opteron X4 and shows the factors that explain execution time: instruction count, CPI, and clock cycle time. Note that CPI varies by a factor of 13. To simplify the marketing of computers, SPEC decided to report a single number to summarize all 12 integer benchmarks. The execution time measure­ ments are first normalized by dividing the execution time on a reference processor by the execution time on the measured computer; this normalization yields a measure, called the SPECratio, which has the advantage that bigger numeric results indicate faster performance (i.e., the SPECratio is the inverse of execution time). A CINT2006 or CFP2006 summary measurement is obtained by taking the geometric mean of the SPECratios. Elaboration: When comparing two computers using SPECratios, use the geometric mean so that it gives the same relative answer no matter what computer is used to normalize the results. If we averaged the normalized execution time values with an arithmetic mean, the results would vary depending on the computer we choose as the reference. workload A set of programs run on a computer that is either the actual collection of applica­tions run by a user or con­structed from real programs to approximate such a mix. A typi­cal workload specifies both the programs and the relative fre­quencies. benchmark A program selected for use in comparing computer performance.
clipped_hennesy_Page_46_Chunk5403
The formula for the geometric mean is n​  ​ i = 1 ​ n ​ Execution time ratio​ ​ i where Execution time ratioi is the execution time, normalized to the reference computer, for the ith program of a total of n in the workload, and ​ i = 1​ n ​ ai means the product a1 × a2 × … × an​ SPEC Power Benchmark Today, SPEC offers a dozen different benchmark sets designed to test a wide variety of computing environments using real applications and strictly specified execution rules and reporting requirements. The most recent is SPECpower. It reports power consumption of servers at different workload levels, divided into 10% increments, over a period of time. Figure 1.21 shows the results for a server using Barcelona. SPECpower started with the SPEC benchmark for Java business applications (SPECJBB2005), which exercises the processors, caches, and main memory as well as the Java virtual machine, compiler, garbage collector, and pieces of the ­operat­ing 1.7 Real Stuff: Manufacturing and Benchmarking the AMD Opteron X4 49 FIGURE 1.20 SPECINTC2006 benchmarks running on AMD Opteron X4 model 2356 (Barcelona). As the equation on page 35 explains, execution time is the prod­uct of the three factors in this table: instruction count in billions, clocks per instruction (CPI), and clock cycle time in nanoseconds. SPECratio is sim­ply the reference time, which is supplied by SPEC, divided by the measured execution time. The single number quoted as SPECINTC2006 is the geometric mean of the SPECratios. Figure 5.40 on page 542 shows that mcf, libquantum, omnetpp, and xalancbmk have relatively high CPIs because they have high cache miss rates. Description Name Instruction Count × 109 CPI Clock cycle time (seconds × 10-9) Execution Time (seconds) Reference Time (seconds) SPECratio Interpreted string processing perl 2,118 0.75 0.4 637 9,770 15.3 Block-sorting compression bzip2 2,389 0.85 0.4 817 9,650 11.8 GNU C compiler gcc 1,050 1.72 0.4 724 8,050 11.1 Combinatorial optimization mcf 336 10.00 0.4 1,345 9,120 6.8 Go game (AI) go 1,658 1.09 0.4 721 10,490 14.6 Search gene sequence hmmer 2,783 0.80 0.4 890 9,330 10.5 Chess game (AI) sjeng 2,176 0.96 0.4 837 12,100 14.5 Quantum computer simulation libquantum 1,623 1.61 0.4 1,047 20,720 19.8 Video compression h264avc 3,102 0.80 0.4 993 22,130 22.3 Discrete event simulation library omnetpp 587 2.94 0.4 690 6,250 9.1 Games/path finding astar 1,082 1.79 0.4 773 7,020 9.1 XML parsing xalancbmk 1,058 2.70 0.4 1,143 6,900 6.0 Geometric Mean 11.7
clipped_hennesy_Page_47_Chunk5404
50 Chapter 1 Computer Abstractions and Technology system. Performance is measured in throughput, and the units are business operations per second. Once again, to simplify the marketing of computers, SPEC boils these numbers down to a single number, called “overall ssj_ops per Watt.” The formula for this single summarizing metric is overall ssj_ops per Watt = ​ ​∑ i = 0 ​ 10 ​ ssj_opsi​ ​ / ​ ​∑ i = 0 ​ 10 ​ poweri​ ​ where ssj_opsi is performance at each 10% increment and poweri is power con­ sumed at each performance level. A key factor in determining the cost of an integrated circuit is volume. Which of the following are reasons why a chip made in high volume should cost less? 1. With high volumes, the manufacturing process can be tuned to a particular design, increasing the yield. 2. It is less work to design a high-volume part than a low-volume part. 3. The masks used to make the chip are expensive, so the cost per chip is lower for higher volumes. 4. Engineering development costs are high and largely independent of vol­ume; thus, the development cost per die is lower with high-volume parts. 5. High-volume parts usually have smaller die sizes than low-volume parts and therefore have higher yield per wafer. Check Yourself Target Load % Performance (ssj_ops) Average Power (Watts) 100% 231,867 295 90% 211,282 286 80% 185,803 275 70% 163,427 265 60% 140,160 256 50% 118,324 246 40% 92,035 233 30% 70,500 222 20% 47,126 206 10% 23,066 180 0% 0 141 Overall Sum 1,283,590 2,605 Σ ssj_ops / Σ power = 493 FIGURE 1.21 SPECpower_ssj2008 running on dual socket 2.3 GHz AMD Opteron X4 2356 (Barcelona) with 16 GB Of DDR2-667 DRAM and one 500 GB disk.
clipped_hennesy_Page_48_Chunk5405
1.8 Fallacies and Pitfalls The purpose of a section on fallacies and pitfalls, which will be found in every chapter, is to explain some commonly held misconceptions that you might encounter. We call such misbeliefs fallacies. When discussing a fallacy, we try to give a counterexample. We also discuss pitfalls, or easily made mistakes. Often pit­ falls are generalizations of principles that are true in a limited context. The pur­pose of these sections is to help you avoid making these mistakes in the computers you may design or use. Cost/performance fallacies and pitfalls have ensnared many a computer architect, including us. Accordingly, this section suffers no shortage of relevant examples. We start with a pitfall that traps many designers and reveals an important relationship in computer design. Pitfall: Expecting the improvement of one aspect of a computer to increase overall performance by an amount proportional to the size of the improvement. This pitfall has visited designers of both hardware and software. A simple design prob­ lem illustrates it well. Suppose a program runs in 100 seconds on a computer, with multiply operations responsible for 80 seconds of this time. How much do I have to improve the speed of multiplication if I want my program to run five times faster? The execution time of the program after making the improvement is given by the following simple equation known as Amdahl’s law: Execution time after improvement = ​ Execution time affected by improvement  Amount of improvement ​ + Execution time unaffected For this problem: Execution time after improvement = ​ 80 seconds  n ​ + (100 − 80 seconds) Since we want the performance to be five times faster, the new execution time should be 20 seconds, giving 20 seconds = ​ 80 seconds  n ​ + 20 seconds 0 = ​ 80 seconds  n ​ That is, there is no amount by which we can enhance-multiply to achieve a fivefold increase in performance, if multiply accounts for only 80% of the workload. Science must begin with myths, and the criticism of myths. Sir Karl Popper, The ­Philosophy of Science, 1957 Amdahl’s law A rule stating that the performance ­enhance­ ment possible with a given improvement is limited by the amount that the improved feature is used. It is a quantita­ tive version of the law of diminishing returns. 1.8 Fallacies and Pitfalls 51
clipped_hennesy_Page_49_Chunk5406
52 Chapter 1 Computer Abstractions and Technology The performance enhancement possible with a given improvement is limited by the amount that the improved feature is used. This concept also yields what we call the law of diminishing returns in everyday life. We can use Amdahl’s law to estimate performance improvements when we know the time consumed for some function and its potential speedup. Amdahl’s law, together with the CPU performance equation, is a handy tool for evaluating potential enhancements. Amdahl’s law is explored in more detail in the exercises. A common theme in hardware design is a corollary of Amdahl’s law: Make the common case fast. This simple guideline reminds us that in many cases the fre­quency with which one event occurs may be much higher than the frequency of another. ­Amdahl’s law reminds us that the opportunity for improvement is affected by how much time the event consumes. Thus, making the common case fast will tend to enhance performance better than optimizing the rare case. Ironically, the com­mon case is often simpler than the rare case and hence is often easier to enhance. Amdahl’s law is also used to argue for practical limits to the number of parallel processors. We examine this argument in the Fallacies and Pitfalls section of Chapter 7. Fallacy: Computers at low utilization use little power. Power efficiency matters at low utilizations because server workloads vary. CPU utilization for servers at Google, for example, is between 10% and 50% most of the time and at 100% less than 1% of the time. Figure 1.22 shows power for serv­ers with the best SPECpower results at 100% load, 50% load, 10% load, and idle. Even servers that are only 10% utilized burn about two-thirds of their peak power. Since servers’ workloads vary but use a large fraction of peak power, Luiz Barroso and Urs Hölzle [2007] argue that we should redesign hardware to achieve “energy-proportional computing.” If future servers used, say, 10% of peak power at 10% workload, we could reduce the electricity bill of datacenters and become good corporate citizens in an era of increasing concern about CO2 emissions. FIGURE 1.22 SPECPower results for three servers with the best overall ssj_ops per watt in the fourth quarter of 2007. The overall ssj_ops per watt of the three servers are 698, 682, and 667, respectively. The memory of the top two servers is 16 GB and the bottom is 8 GB. Server Manufacturer Micro- processor Total Cores/ Sockets Clock Rate Peak Performance (ssj_ops) 100% Load Power 50% Load Power 50% Load/ 100% Power 10% Load Power 10% Load/ 100% Power Active Idle Power Active Idle/ 100% Power HP Xeon E5440 8/2 3.0 GHz 308,022 269 W 227 W 84% 174 W 65% 160 W 59% Dell Xeon E5440 8/2 2.8 GHz 305,413 276 W 230 W 83% 173 W 63% 157 W 57% Fujitsu Seimens Xeon X3220 4/1 2.4 GHz 143,742 132 W 110 W 83% 85 W 65% 80 W 60% Pitfall: Using a subset of the performance equation as a performance metric. We have already shown the fallacy of predicting performance based on simply one of clock rate, instruction count, or CPI. Another common mistake is to use only
clipped_hennesy_Page_50_Chunk5407
two of the three factors to compare performance. Although using two of the three factors may be valid in a limited context, the concept is also easily misused. Indeed, nearly all pro­posed alternatives to the use of time as the performance metric have led eventually to misleading claims, distorted results, or incorrect interpretations. One alternative to time is MIPS (million instructions per second). For a given program, MIPS is simply MIPS = ​ Instruction count  Execution time × 106 ​ Since MIPS is an instruction execution rate, MIPS specifies performance inversely to execution time; faster computers have a higher MIPS rating. The good news about MIPS is that it is easy to understand, and faster computers mean big­ger MIPS, which matches intuition. There are three problems with using MIPS as a measure for comparing com­ puters. First, MIPS specifies the instruction execution rate but does not take into account the capabilities of the instructions. We cannot compare computers with different instruction sets using MIPS, since the instruction counts will certainly differ. Second, MIPS varies between programs on the same computer; thus, a com­ puter cannot have a single MIPS rating. For example, by substituting for execu­tion time, we see the relationship between MIPS, clock rate, and CPI: MIPS = ​ Instruction count  ​ Instruction count × CPI  Clock rate ​ × 106 ​ = ​ Clock rate  CPI × 106 ​ Recall that CPI varied by 13× for SPEC CPU2006 on Opteron X4, so MIPS does as well. Finally, and most importantly, if a new program executes more instructions but each instruction is faster, MIPS can vary independently from performance! Consider the following performance measurements for a program: million instructions per sec­ond (MIPS) A measurement of program execution speed based on the number of millions of instructions. MIPS is computed as the instruction count divided by the product of the execution time and 106. Check Yourself Measurement Computer A Computer B Instruction count 10 billion 8 billion Clock rate 4 GHz 4 GHz CPI 1.0 1.1 a. Which computer has the higher MIPS rating? b. Which computer is faster? 1.8 Fallacies and Pitfalls 53
clipped_hennesy_Page_51_Chunk5408
54 Chapter 1 Computer Abstractions and Technology 1.9 Concluding Remarks Although it is difficult to predict exactly what level of cost/performance comput­ ers will have in the future, it’s a safe bet that they will be much better than they are today. To participate in these advances, computer designers and programmers must understand a wider variety of issues. Both hardware and software designers construct computer systems in hierar­ chical layers, with each lower layer hiding details from the level above. This princi­ ple of abstraction is fundamental to understanding today’s computer systems, but it does not mean that designers can limit themselves to knowing a single abstraction. Perhaps the most important example of abstraction is the interface between hardware and low-level software, called the instruction set architecture. Maintain­ ing the instruction set architecture as a constant enables many implementations of that architecture—presumably varying in cost and performance—to run identical software. On the downside, the architecture may preclude introducing innova­tions that require the interface to change. There is a reliable method of determining and reporting performance by using the execution time of real programs as the metric. This execution time is related to other important measurements we can make by the following equation: ​ Seconds  Program ​ = ​ Instructions  Program ​ × ​ Clock cycles  Instruction ​ × ​ Seconds  Clock cycle ​ We will use this equation and its constituent factors many times. Remember, though, that individually the factors do not determine performance: only the product, which equals execution time, is a reliable measure of performance. Execution time is the only valid and unimpeachable measure of perfor­ mance. Many other metrics have been proposed and found wanting. Sometimes these metrics are flawed from the start by not reflecting exe­ cution time; other times a metric that is valid in a limited context is extended and used beyond that context or without the additional clarifi­ cation needed to make it valid. The key hardware technology for modern processors is silicon. Equal in impor­ tance to an understanding of integrated circuit technology is an understanding of the expected rates of technological change. While silicon fuels the rapid advance of hardware, new ideas in the organization of computers have improved price/ performance. Two of the key ideas are exploiting parallelism in the program, The BIG Picture Where . . . the ENIAC is equipped with 18,000 ­vacuum tubes and weighs 30 tons, computers in the future may have 1,000 vacuum tubes and perhaps weigh just 1½ tons. Popular Mechanics, March 1949
clipped_hennesy_Page_52_Chunk5409
typically today via multiple processors, and exploiting locality of accesses to a memory hierarchy, typically via caches. Power has replaced die area as the most critical resource of microprocessor design. Conserving power while trying to increase performance has forced the hardware industry to switch to multicore microprocessors, thereby forcing the software industry to switch to programming parallel hardware. Computer designs have always been measured by cost and performance, as well as other important factors such as power, reliability, cost of ownership, and scal­ ability. Although this chapter has focused on cost, performance, and power, the best designs will strike the appropriate balance for a given market among all the factors. Road Map for This Book At the bottom of these abstractions are the five classic components of a computer: datapath, control, memory, input, and output (refer to Figure 1.4). These five components also serve as the framework for the rest of the chapters in this book: ■ ■Datapath: Chapters 3, 4, 7, and Appendix A ■ ■Control: Chapters 4, 7, and Appendix A ■ ■Memory: Chapter 5 ■ ■Input: Chapter 6 ■ ■Output: Chapter 6 As mentioned above, Chapter 4 describes how processors exploit implicit par­ allelism, Chapter 7 describes the explicitly parallel multicore microprocessors that are at the heart of the parallel revolution, and Appendix A describes the highly parallel graphics processor chip. Chapter 5 describes how a memory hierarchy exploits locality. Chapter 2 describes instruction sets—the interface between com­ pilers and the computer—and emphasizes the role of compilers and ­programming languages in using the features of the instruction set. Appendix B provides a reference for the instruction set of Chapter 2. Chapter 3 describes how computers handle arithmetic data. Appendix C, on the CD, introduces logic design. Historical Perspective and Further Reading For each chapter in the text, a section devoted to a historical perspective can be found on the CD that accompanies this book. We may trace the development of an idea through a series of computers or describe some important projects, and we provide references in case you are interested in probing further. An active field of science is like an immense anthill; the individual almost vanishes into the mass of minds tum­bling over each other, carry­ ing information from place to place, passing it around at the speed of light. Lewis Thomas, “Natural ­Science,” in The Lives of a Cell, 1974 1.10 1.10 Historical Perspective and Further Reading 55
clipped_hennesy_Page_53_Chunk5410
56 Chapter 1 Computer Abstractions and Technology The historical perspective for this chapter provides a background for some of the key ideas presented in this opening chapter. Its purpose is to give you the human story behind the technological advances and to place achievements in their historical context. By understanding the past, you may be better able to understand the forces that will shape computing in the future. Each historical per­ spectives section on the CD ends with suggestions for further reading, which are also collected separately on the CD under the section “Further Reading.” The rest of Section 1.10 is found on the CD. 1.11 Exercises Contributed by Javier Bruguera of Universidade de Santiago de Compostela Most of the exercises in this edition are designed so that they feature a qualitative description supported by a table that provides alternative quantitative parameters. These parameters are needed to solve the questions that comprise the exercise. Individual questions can be solved using any or all of the parameters—you decide how many of the parameters should be considered for any given exercise question. For example, it is possible to say “complete Question 4.1.1 using the parameters given in row A of the table.” Alternately, instructors can customize these exercises to create novel solutions by replacing the given parameters with your own unique values. The number of quantitative exercises varies from chapter to chapter and depends largely on the topics covered. More conventional exercises are provided where the quantitative approach does not fit. The relative time ratings of exercises are shown in square brackets after each exercise number. On average, an exercise rated [10] will take you twice as long as one rated [5]. Sections of the text that should be read before attempting an exercise will be given in angled brackets; for example, <1.3> means you should have read Section 1.3, Under the Covers, to help you solve this exercise. Exercise 1.1 Find the word or phrase from the list below that best matches the description in the following questions. Use the num­bers to the left of words in the answer. Each answer should be used only once.
clipped_hennesy_Page_54_Chunk5411
1. virtual worlds 14. operating system 2. desktop computers 15. compiler 3. servers 16. bit 4. low-end servers 17. instruction 5. supercomputers 18. assembly language 6. terabyte 19. machine language 7. petabyte 20. C 8. data centers 21. assembler 9. embedded computers 22. high-level language 10. multicore processors 23. system software 11. VHDL 24. application software 12. RAM 25. Cobol 13. CPU 26. Fortran 1.1.1 [2] <1.1> Computer used to run large problems and usually accessed via a network 1.1.2 [2] <1.1> 1015 or 250 bytes 1.1.3 [2] <1.1> A class of computers composed of hundred to thousand proces­ sors and terabytes of memory and having the highest performance and cost 1.1.4 [2] <1.1> Today’s science fiction application that probably will be available in the near future 1.1.5 [2] <1.1> A kind of memory called random access memory 1.1.6 [2] <1.1> Part of a computer called central processor unit 1.1.7 [2] <1.1> Thousands of processors forming a large cluster 1.1.8 [2] <1.1> Microprocessors containing several processors in the same chip 1.1.9 [2] <1.1> Desktop computer without a screen or keyboard usually accessed via a network 1.1.10 [2] <1.1> A computer used to running one predetermined application or collection of software 1.1.11 [2] <1.1> Special language used to describe hardware components 1.11 Exercises 57
clipped_hennesy_Page_55_Chunk5412
58 Chapter 1 Computer Abstractions and Technology 1.1.12 [2] <1.1> Personal computer delivering good performance to single users at low cost 1.1.13 [2] <1.2> Program that translates statements in high-level language to assembly language 1.1.14 [2] <1.2> Program that translates symbolic instructions to binary ­ins­tructions 1.1.15 [2] <1.2> High-level language for business data processing 1.1.16 [2] <1.2> Binary language that the processor can understand 1.1.17 [2] <1.2> Commands that the processors understand 1.1.18 [2] <1.2> High-level language for scientific computation 1.1.19 [2] <1.2> Symbolic representation of machine instructions 1.1.20 [2] <1.2> Interface between user’s program and hardware providing a variety of services and supervision functions 1.1.21 [2] <1.2> Software/programs developed by the users 1.1.22 [2] <1.2> Binary digit (value 0 or 1) 1.1.23 [2] <1.2> Software layer between the application software and the hard­ ware that includes the operating system and the compilers 1.1.24 [2] <1.2> High-level language used to write application and system software 1.1.25 [2] <1.2> Portable language composed of words and algebraic expres­ sions that must be translated into assembly language before run in a computer 1.1.26 [2] <1.2> 1012 or 240 bytes Exercise 1.2 Consider the different configurations shown in the table Configuration Resolution Main Memory Ethernet Network a. 1 640 × 480 2 Gbytes 100 Mbit 2 1280 × 1024 4 Gbytes 1 Gbit b. 1 1024 × 768 2 Gbytes 100 Mbit 2 2560 × 1600 4 Gbytes 1Gbit
clipped_hennesy_Page_56_Chunk5413
1.2.1 [10] <1.3> For a color display using 8 bits for each of the primary colors (red, green, blue) per pixel, what should be the minimum size in bytes of the frame buffer to store a frame? 1.2.2 [5] <1.3> How many frames could it store, assuming the memory contains no other information? 1.2.3 [5] <1.3> If a 256 Kbytes file is sent through the Ethernet connection, how long it would take? For problems below, use the information about access time for every type of mem­ ory in the following table. Cache DRAM Flash Memory Magnetic Disk a. 5 ns 50 ns 5 μs 5 ms b. 7 ns 70 ns 15 μs 20 ms 1.2.4 [5] <1.3> Find how long it takes to read a file from a DRAM if it takes 2 microseconds from the cache memory. 1.2.5 [5] <1.3> Find how long it takes to read a file from a disk if it takes 2 micro­ seconds from the cache memory. 1.2.6 [5] <1.3> Find how long it takes to read a file from a flash memory if it takes 2 microseconds from the cache memory. Exercise 1.3 Consider three different processors P1, P2, and P3 executing the same instruction set with the clock rates and CPIs given in the following table. Processor Clock Rate CPI a. P1 3 GHz 1.5 P2 2.5 GHz 1.0 P3 4 GHz 2.2 b. P1 2 GHz 1.2 P2 3 GHz 0.8 P3 4 GHz 2.0 1.3.1 [5] <1.4> Which processor has the highest performance expressed in instructions per second? 1.3.2 [10] <1.4> If the processors each execute a program in 10 seconds, find the number of cycles and the number of instructions. 1.11 Exercises 59
clipped_hennesy_Page_57_Chunk5414
60 Chapter 1 Computer Abstractions and Technology 1.3.3 [10] <1.4> We are trying to reduce the time by 30% but this leads to an increase of 20% in the CPI. What clock rate should we have to get this time reduction? For problems below, use the information in the following table. Processor Clock Rate No. Instructions Time a. P1 3 GHz 20.00E+09 7 s P2 2.5 GHz 30.00E+09 10 s P3 4 GHz 90.00E+09 9 s b. P1 2 GHz 20.00E+09 5 s P2 3 GHz 30.00E+09 8 s P3 4 GHz 25.00E+09 7 s 1.3.4 [10] <1.4> Find the IPC (instructions per cycle) for each processor. 1.3.5 [5] <1.4> Find the clock rate for P2 that reduces its execution time to that of P1. 1.3.6 [5] <1.4> Find the number of instructions for P2 that reduces its execution time to that of P3. Exercise 1.4 Consider two different implementations of the same instruction set architecture. There are four classes of instructions, A, B, C, and D. The clock rate and CPI of each implementation are given in the following table. Clock Rate CPI Class A CPI Class B CPI Class C CPI Class D a. P1 2.5 GHz 1 2 3 3 P2 3 GHz 2 2 2 2 b. P1 2.5 GHz 2 1.5 2 1 P2 3 GHz 1 2 1 1 1.4.1 [10] <1.4> Given a program with 106 instructions divided into classes as follows: 10% class A, 20% class B, 50% class C, and 20% class D, which implemen­ tation is faster? 1.4.2 [5] <1.4> What is the global CPI for each implementation? 1.4.3 [5] <1.4> Find the clock cycles required in both cases.
clipped_hennesy_Page_58_Chunk5415
The following table shows the number of instructions for a program. Arith Store Load Branch Total a. 650 100 600 50 1400 b. 750 250 500 500 2000 1.4.4 [5] <1.4> Assuming that arith instructions take 1 cycle, load and store 5 cycles, and branches 2 cycles, what is the execution time of the program in a 2 GHz processor? 1.4.5 [5] <1.4> Find the CPI for the program. 1.4.6 [10] <1.4> If the number of load instructions can be reduced by one half, what is the speedup and the CPI? Exercise 1.5 Consider two different implementations, P1 and P2, of the same instruction set. There are five classes of instructions (A, B, C, D, and E) in the instruction set. The clock rate and CPI of each class is given below. Clock Rate CPI Class A CPI Class B CPI Class C CPI Class D CPI Class E a. P1 2.0 GHz 1 2 3 4 3 P2 4.0 GHz 2 2 2 4 4 b. P1 2.0 GHz 1 1 2 3 2 P2 3.0 GHz 1 2 3 4 3 1.5.1 [5] <1.4> Assume that peak performance is defined as the fastest rate that a computer can execute any instruction sequence. What are the peak performances of P1 and P2 expressed in instructions per second? 1.5.2 [10] <1.4> If the number of instructions executed in a certain program is divided equally among the classes of instructions except for class A, which occurs twice as often as each of the others, which computer is faster? How much faster is it? 1.5.3 [10] <1.4> If the number of instructions executed in a certain program is divided equally among the classes of instructions except for class E, which oc­ curs twice as often as each of the others, which computer is faster? How much faster is it? The table below shows instruction-type breakdown for different programs. Using this data, you will be exploring the performance trade-offs for different changes made to an MIPS processor. 1.11 Exercises 61
clipped_hennesy_Page_59_Chunk5416
62 Chapter 1 Computer Abstractions and Technology No. Instructions Compute Load Store Branch Total a. Program1 600 600 200 50 1450 b. Program 2 900 500 100 200 1700 1.5.4 [5] <1.4> Assuming that computes take 1 cycle, loads and store instructions take 10 cycles, and branches take 3 cycles, find the execution time on a 3 GHz MIPS processor. 1.5.5 [5] <1.4> Assuming that computes take 1 cycle, loads and store instructions take 2 cycles, and branches take 3 cycles, find the execution time on a 3 GHz MIPS processor. 1.5.6 [5] <1.4> Assuming that computes take 1 cycle, loads and store instruc­ tions take 2 cycles, and branches take 3 cycles, what is the speedup if the number of compute instruction can be reduced by one-half? Exercise 1.6 Compilers can have a profound impact on the performance of an application on given a processor. This problem will explore the impact compilers have on execu­ tion time. Compiler A Compiler B No. Instructions Execution Time No. Instructions Execution Time a. 1.00E+09 1.8 s 1.20E+09 1.8 s b. 1.00E+09 1.1 s 1.20E+09 1.5 s 1.6.1 [5] <1.4> For the same program, two different compilers are used. The table above shows the execution time of the two different compiled programs. Find the average CPI for each program given that the processor has a clock cycle time of 1 ns. 1.6.2 [5] <1.4> Assume the average CPIs found in 1.6.1, but that the compiled programs run on two different processors. If the execution times on the two pro­ cessors are the same, how much faster is the clock of the processor running com­ piler A’s code versus the clock of the processor running compiler B’s code? 1.6.3 [5] <1.4> A new compiler is developed that uses only 600 million instruc­ tions and has an average CPI of 1.1. What is the speedup of using this new compiler versus using Compiler A or B on the original processor of 1.6.1? Consider two different implementations, P1 and P2, of the same instruction set. There are five classes of instructions (A, B, C, D, and E) in the instruction set. P1 has a clock rate of 4 GHz, and P2 has a clock rate of 6 GHz. The average number of cycles for each instruction class for P1 and P2 are listed in the following table.
clipped_hennesy_Page_60_Chunk5417
CPI Class A CPI Class B CPI Class C CPI Class D CPI Class E a. P1 1 2 3 4 5 P2 3 3 3 5 5 b. P1 1 2 3 4 5 P2 2 2 2 2 6 1.6.4 [5] <1.4> Assume that peak performance is defined as the fastest rate that a computer can execute any instruction sequence. What are the peak performances of P1 and P2 expressed in instructions per second? 1.6.5 [5] <1.4> If the number of instructions executed in a certain program is di­ vided equally among the five classes of instructions except for class A, which occurs twice as often as each of the others, how much faster is P2 than P1? 1.6.6 [5] <1.4> At what frequency does P1 have the same performance of P2 for the instruction mix given in 1.6.5? Exercise 1.7 The following table shows the increase in clock rate and power of eight generations of Intel processors over 28 years. Processor Clock Rate Power 80286 (1982) 12.5 MHz 3.3 W 80386 (1985) 16 MHz 4.1 W 80486 (1989) 25 MHz 4.9 W Pentium (1993) 66 MHz 10.1 W Pentium Pro (1997) 200 MHz 29.1 W Pentium 4 Willamette (2001) 2 GHz 75.3 W Pentium 4 Prescott (2004) 3.6 GHz 103 W Core 2 Ketsfield (2007) 2.667 GHz 95 W 1.7.1 [5] <1.5> What is the geometric mean of the ratios between consecutive generations for both clock rate and power? (The geometric mean is described in Section 1.7.) 1.7.2 [5] <1.5> What is the largest relative change in clock rate and power between generations? 1.7.3 [5] <1.5> How much larger is the clock rate and power of the last genera­ tion with respect to the first generation? 1.11 Exercises 63
clipped_hennesy_Page_61_Chunk5418
64 Chapter 1 Computer Abstractions and Technology Consider the following values for voltage in each generation. Processor Voltage 80286 (1982) 5 80386 (1985) 5 80486 (1989) 5 Pentium (1993) 5 Pentium Pro (1997) 3.3 Pentium 4 Willamette (2001) 1.75 Pentium 4 Prescott (2004) 1.25 Core 2 Ketsfield (2007) 1.1 1.7.4 [5] <1.5> Find the average capacitive loads, assuming a negligible static power consumption. 1.7.5 [5] <1.5> Find the largest relative change in voltage between generations. 1.7.6 [5] <1.5> Find the geometric mean of the voltage ratios in the generations since the Pentium. Exercise 1.8 Suppose we have developed new versions of a processor with the following char­ acteristics. Version Voltage Clock Rate a. Version 1 1.75 V 1.5 GHz Version 2 1.2 V 2 GHz b. Version 1 1.1 V 3 GHz Version 2 0.8 V 4 GHz 1.8.1 [5] <1.5> How much has the capacitive load varied between versions if the dynamic power has been reduced by 10%? 1.8.2 [5] <1.5> How much has the dynamic power been reduced if the capacitive load does not change? 1.8.3 [10] <1.5> Assuming that the capacitive load of version 2 is 80% the capacitive load of version 1, find the voltage for version 2 if the dynamic power of version 2 is reduced by 40% from version 1. Suppose that the industry trends show that a new process generation varies as follows.
clipped_hennesy_Page_62_Chunk5419
Capacitance Voltage Clock Rate Area a. 1 1/21/2 1.15 1/21/2 b. 1 1/21/4 1.2 1/21/4 1.8.4 [5] <1.5> Find the scaling factor for the dynamic power. 1.8.5 [5] <1.5> Find the scaling of the capacitance per unit area unit. 1.8.6 [5] <1.5> Assuming a Core 2 processor with a clock rate of 2.667 GHz, a power consumption of 95 W, and a voltage of 1.1 V, find the voltage and clock rate of this processor for the next process generation. Exercise 1.9 Although the dynamic power is the primary source of power dissipation in CMOS, leakage current produces a static power dissipation V × Ileak. The smaller the on- chip dimensions, the more significant is the static power. Assume the figures shown in the following table for static and dynamic power dissipation for several genera­ tions of processors. Technology Dynamic Power (W) Static Power (W) Voltage (V) a. 180 nm 50 10 1.2 b. 70 nm 90 60 0.9 1.9.1 [5] <1.5> Find the percentage of the total dissipated power comprised by static power. 1.9.2 [5] <1.5> If the total dissipated power is reduced by 10% while maintain­ ing the static to total power rate of problem 1.9.1, how much should the voltage be reduced to maintain the same leakage current? 1.9.3 [5] <1.5> Determine the ratio of static power to dynamic power for each technology. Consider now the dynamic power dissipation of different versions of a given pro­ cessor for three different voltages given in the following table. 1.2 V 1.0 V 0.8 V a. 75 W 60 W 35 W b. 62 W 50 W 30 W 1.11 Exercises 65
clipped_hennesy_Page_63_Chunk5420
66 Chapter 1 Computer Abstractions and Technology 1.9.4 [5] <1.5> Determine the static power at 0.8 V, assuming a static to dynamic power ratio of 0.6. 1.9.5 [5] <1.5> Determine the static and dynamic power dissipation assuming the rates obtained in problem 1.9.1. 1.9.6 [10] <1.5> Determine the geometric mean of the power variations between versions. Exercise 1.10 The table below shows the instruction type breakdown of a given application executed on 1, 2, 4, or 8 processors. Using this data, you will be exploring the speed­ up of applications on parallel processors. Processors No. Instructions per Processor CPI Arithmetic Load/Store Branch Arithmetic Load/Store Branch a. 1 2560 1280 256 1 4 2 2 1280 640 128 1 5 2 4 640 320 64 1 7 2 8 320 160 32 1 12 2 Processors No. Instructions per Processor CPI Arithmetic Load/Store Branch Arithmetic Load/Store Branch b. 1 2560 1280 256 1 4 2 2 1280 640 128 1 6 2 4 640 320 64 1 8 2 8 320 160 32 1 10 2 1.10.1 [5] <1.4, 1.6> The table above shows the number of instructions required per processor to complete a program on a multiprocessor with 1, 2, 4, or 8 proces­ sors. What is the total number of instructions executed per processor? What is the aggregate number of instructions executed across all processors? 1.10.2 [5] <1.4, 1.6> Given the CPI values on the right of the table above, find the total execution time for this program on 1, 2, 4, and 8 processors. Assume that each processor has a 2 GHz clock frequency. 1.10.3 [10] <1.4, 1.6> If the CPI of the arithmetic instructions was doubled, what would the impact be on the execution time of the program on 1, 2, 4, or 8 processors?
clipped_hennesy_Page_64_Chunk5421
The table below shows the number of instructions per processor core on a multi­core processor as well as the average CPI for executing the program on 1, 2, 4, or 8 cores. Using this data, you will be exploring the speedup of applications on ­multicore ­processors. Cores per Processor Instructions per Core Average CPI a. 1 1.00E+10 1.2 2 5.00E+09 1.4 4 2.50E+09 1.8 8 1.25E+09 2.6 Cores per Processor Instructions per Core Average CPI b. 1 1.00E+10 1.0 2 5.00E+09 1.2 4 2.50E+09 1.4 8 1.25E+09 1.7 1.10.4 [10] <1.4, 1.6> Assuming a 3 GHz clock frequency, what is the execution time of the program using 1, 2, 4, or 8 cores? 1.10.5 [10] <1.5, 1.6> Assume that the power consumption of a processor core can be described by the following equation: Power = ​ 5.0mA  MHz ​ Voltage2 where the operation voltage of the processor is described by the following equa­ tion: Voltage = ​ 1  5 ​ Frequency + 0.4 with the frequency measured in GHz. So, at 5 GHz, the voltage would be 1.4 V. Find the power consumption of the program executing on 1, 2, 4, and 8 cores assuming that each core is operating at a 3 GHz clock frequency. Likewise, find the power consumption of the program executing on 1, 2, 4, or 8 cores assuming that each core is operating at 500 MHz. 1.10.6 [10] <1.5, 1.6> If using a single core, find the required CPI for this core to get an execution time equal to the time obtained by using the number of cores in the table above (execution times in problem 1.10.4). Note that the number of instructions should be the aggregate number of instructions executed across all the cores. 1.11 Exercises 67
clipped_hennesy_Page_65_Chunk5422
68 Chapter 1 Computer Abstractions and Technology Exercise 1.11 The following table shows manufacturing data for various processors. Wafer Diameter Dies per Wafer Defects per Unit Area Cost per Wafer a. 15 cm 84 0.020 defects/cm2 12 b. 20 cm 100 0.031 defects/cm2 15 1.11.1 [10] <1.7> Find the yield. 1.11.2 [5] <1.7> Find the cost per die. 1.11.3 [10] <1.7> If the number of dies per wafer is increased by 10% and the defects per area unit increases by 15%, find the die area and yield. Suppose that, with the evolution of the electronic devices manufacturing tech­ nology, the yield varies as shown in the following table. T1 T2 T3 T4 Yield 0.85 0.89 0.92 0.95 1.11.4 [10] <1.7> Find the defects per area unit for each technology given a die area of 200 mm2. 1.11.5 [5] <1.7> Represent graphically the variation of the yield together with the variation of defects per unit area. Exercise 1.12 The following table shows results for SPEC CPU2006 benchmark programs running on an AMD Barcelona. Name Intr. Count × 109 Execution Time (seconds) Reference Time (seconds) a. bzip2 2389 750 9650 b. go 1658 700 10,490 1.12.1 [5] <1.7> Find the CPI if the clock cycle time is 0.333 ns. 1.12.2 [5] <1.7> Find the SPECratio. 1.12.3 [5] <1.7> For these two benchmarks, find the geometric mean of the SPECratio.
clipped_hennesy_Page_66_Chunk5423
The following table shows data for further benchmarks. Name CPI Clock Rate SPECratio a. libquantum 1.61 4 GHz 19.8 b. astar 1.79 4 GHz 9.1 1.12.4 [5] <1.7> Find the increase in CPU time if the number of instructions of the benchmark is increased by 10% without affecting the CPI. 1.12.5 [5] <1.7> Find the increase in CPU time if the number of instructions of the benchmark is increased by 10% and the CPI is increased by 5%. 1.12.6 [5] <1.7> Find the change in the SPECratio for the change described in 1.12.5. Exercise 1.13 Suppose that we are developing a new version of the AMD Barcelona proces­ sor with a 4 GHz clock rate. We have added some additional instructions to the instruction set in such a way that the number of instructions has been reduced by 15% from the values shown for each benchmark in Exercise 1.12. The execution times obtained are shown in the following table. Name Execution Time (seconds) Reference Time (seconds) SPECratio a. bzip2 700 9650 13.7 b. go 620 10490 16.9 1.13.1 [10] <1.8> Find the new CPI. 1.13.2 [10] <1.8> In general, these CPI values are larger than those obtained in previous exercises for the same benchmarks. This is due mainly to the clock rate used in both cases, 3 GHz and 4 GHz. Determine whether the increase in the CPI is similar to that of the clock rate. If they are dissimilar, why? 1.13.3 [5] <1.8> How much has the CPU time been reduced? The following table shows data for further benchmarks. Name Execution Time (seconds) CPI Clock Rate a. libquantum 960 1.61 3 GHz b. astar 690 1.79 3 GHz 1.11 Exercises 69
clipped_hennesy_Page_67_Chunk5424
70 Chapter 1 Computer Abstractions and Technology 1.13.4 [10] <1.8> If the execution time is reduced by an additional 10% with­ out affecting to the CPI and with a clock rate of 4 GHz, determine the number of instructions. 1.13.5 [10] <1.8> Determine the clock rate required to give a further 10% reduc­ tion in CPU time while maintaining the number of instructions and with the CPI unchanged. 1.13.6 [10] <1.8> Determine the clock rate if the CPI is reduced by 15% and the CPU time by 20% while the number of instructions is unchanged. Exercise 1.14 Section 1.8 cites as a pitfall the utilization of a subset of the performance equa­ tion as a performance metric. To illustrate this, consider the following data for the execution of a program in different processors. Processor Clock Rate CPI No. Instr. a. P1 4 GHz 0.9 5.00E+06 P2 3 GHz 0.75 1.00E+06 b. P1 3 GHz 1.1 3.00E+06 P2 2.5 GHz 1.0 0.50E+06 1.14.1 [5] <1.8> One usual fallacy is to consider the computer with the largest clock rate as having the largest performance. Check if this is true for P1 and P2. 1.14.2 [10] <1.8> Another fallacy is to consider that the processor executing the largest number of instructions will need a larger CPU time. Considering that pro­ cessor P1 is executing a sequence of 106 instructions and that the CPI of proces­ sors P1 and P2 do not change, determine the number of instructions that P2 can execute in the same time that P1 needs to execute 106 instructions. 1.14.3 [10] <1.8> A common fallacy is to use MIPS (millions of instructions per second) to compare the performance of two different processors, and consider that the processor with the largest MIPS has the largest performance. Check if this is true for P1 and P2. Another common performance figure is MFLOPS (million of floating-point operations per second), defined as MFLOPS = No. FP operations / (execution time × 106) but this figure has the same problems as MIPS. Consider the program in the fol­ lowing table, running on the two processors below.
clipped_hennesy_Page_68_Chunk5425
Processor Instr. Count No. Instructions CPI L/S FP Branch L/S FP Branch Clock Rate a. P1 1.00E+06 50% 40% 10% 0.75 1.0 1.5 4 GHz P2 5.00E+06 40% 40% 20% 1.25 0.8 1.25 3 GHz b. P1 5.00E+06 30% 30% 40% 1.5 1.0 2.0 4 GHz P2 2.00E+06 40% 30% 30% 1.25 1.0 2.5 3 GHz 1.14.4 [10] <1.8> Find the MFLOPS figures for the programs. 1.14.5 [10] <1.8> Find the MIPS figures for the programs. 1.14.6 [10] <1.8> Find the performance for the programs and compare it with MIPS and MFLOPS. Exercise 1.15 Another pitfall cited in Section 1.8 is expecting to improve the overall performance of a computer by improving only one aspect of the computer. This might be true, but not always. Consider a computer running programs with CPU times shown in the following table. FP Instr. INT Instr. L/S Instr. Branch Instr. Total Time a. 70 s 85 s 55 s 40 s 250 s b. 40 s 90 s 60 s 20 s 210 s 1.15.1 [5] <1.8> How much is the total time reduced if the time for FP opera­ tions is reduced by 20%? 1.15.2 [5] <1.8> How much is the time for INT operations reduced if the total time is reduced by 20%? 1.15.3 [5] <1.8> Can the total time can be reduced by 20% by reducing only the time for branch instructions? The following table shows the instruction type breakdown per processor of given applications executed in different numbers of processors. Processors FP Instr. INT Instr. L/S Instr. Branch Instr. CPI (FP) CPI (INT) CPI (L/S) CPI (Branch) a. 2 280 × 106 1000 × 166 640 × 106 128 × 106 1 1 4 2 b. 16 50 × 106 110 × 106 80 × 106 16 × 106 1 1 4 2 1.11 Exercises 71
clipped_hennesy_Page_69_Chunk5426
72 Chapter 1 Computer Abstractions and Technology Assume that each processor has a 2 GHz clock rate. 1.15.4 [10] <1.8> How much must we improve the CPI of FP instructions if we want the program to run two times faster? 1.15.5 [10] <1.8> How much must we improve the CPI of L/S instructions if we want the program to run two times faster? 1.15.6 [5] <1.8> How much is the execution time of the program improved if the CPI of INT and FP instructions is reduced by 40% and the CPI of L/S and Branch is reduced by 30%? Exercise 1.16 Another pitfall, related to the execution of programs in multiprocessor systems, is expecting improvement in performance by improving only the execution time of part of the routines. The following table shows the execution time of five routines of a program running on different numbers of processors. No. Processors Routine A (ms) Routine B (ms) Routine C (ms) Routine D (ms) Routine E (ms) a. 4 12 45 6 36 3 b. 32 2 7 1 6 2 1.16.1 [10] <1.8> Find the total execution time and by how much it is reduced if the time of routines A, C, and E is improved by 15%. 1.16.2 [10] <1.8> How much is the total time reduced if routine B is improved by 10%? 1.16.3 [10] <1.8> How much is the total time reduced if routine D is improved by 10%? Execution time in a multiprocessor system can be split into computing time for the routines plus routing time spent sending data from one processor to another. Consider the execution time and routing time given in the following table. In this case, the routing time is an important component of the total time.
clipped_hennesy_Page_70_Chunk5427
No. Processors Routine A (ms) Routine B (ms) Routine C (ms) Routine D (ms) Routine E (ms) Routing Time (ms) 2 40 78 9 70 4 11 4 29 60 4 36 2 13 8 15 45 3 19 3 17 16 7 35 1 11 2 22 32 4 23 1 6 1 23 64 2 12 0.5 3 1 26 1.16.4 [10] <1.8> For each doubling of the number of processors, determine the ratio of new to old computing time and the ratio of new to old routing time. 1.16.5 [5] <1.8> Using the geometric means of the ratios, extrapolate to find the computing time and routing time in a 128-processor system. 1.16.6 [10] <1.8> Find the computing time and routing time for a system with one processor. §1.1, page 9: Discussion questions: many answers are acceptable. §1.3, page 25: Disk memory: nonvolatile, long access time (milliseconds), and cost $0.20–$2.00/GB. Semiconductor memory: volatile, short access time (nanosec­onds), and cost $20–$75/GB. §1.4, page 31: 1. a: both, b: latency, c: neither. 2. 7 seconds. §1.4, page 38: b. §1.7, page 50: 1, 3, and 4 are valid reasons. Answer 5 can be generally true because high volume can make the extra investment to reduce die size by, say, 10% a good economic decision, but it doesn’t have to be true. §1.8, page 53: a. Computer A has the higher MIPS rating. b. Computer B is faster. Answers to Check Yourself 1.11 Exercises 73
clipped_hennesy_Page_71_Chunk5428
2 I speak Spanish to God, Italian to women, French to men, and German to my horse. Charles V, Holy Roman Emperor (1500–1558) Instructions: Language of the Computer 2.1 Introduction 76 2.2 Operations of the Computer Hardware 77 2.3 Operands of the Computer Hardware 80 2.4 Signed and Unsigned Numbers 87 2.5 Representing Instructions in the Computer 94 2.6 Logical Operations 102 2.7 Instructions for Making Decisions 105 Computer Organization and Design. DOI: 10.1016/B978-0-12-374750-1.00002-5 © 2012 Elsevier, Inc. All rights reserved.
clipped_hennesy_Page_72_Chunk5429
2.8 Supporting Procedures in Computer Hardware 112 2.9 Communicating with People 122 2.10 MIPS Addressing for 32-Bit Immediates and Addresses 128 2.11 Parallelism and Instructions: Synchronization 137 2.12 Translating and Starting a Program 139 2.13 A C Sort Example to Put It All Together 149 2.14 Arrays versus Pointers 157 2.15 Advanced Material: Compiling C and Interpreting Java 161 2.16 Real Stuff: ARM Instructions 161 2.17 Real Stuff: x86 Instructions 165 2.18 Fallacies and Pitfalls 174 2.19 Concluding Remarks 176 2.20 Historical Perspective and Further Reading 179 2.21 Exercises 179 The Five Classic Components of a Computer
clipped_hennesy_Page_73_Chunk5430
76 Chapter 2 Instructions: Language of the Computer 2.1 Introduction To command a computer’s hardware, you must speak its language. The words of a computer’s language are called instructions, and its vocabulary is called an instruction set. In this chapter, you will see the instruction set of a real computer, both in the form written by people and in the form read by the computer. We introduce instructions in a top-down fashion. Starting from a notation that looks like a restricted programming language, we refine it step-by-step until you see the real language of a real computer. Chapter 3 continues our downward descent, unveiling the hardware for arithmetic and the representation of floating-point numbers. You might think that the languages of computers would be as diverse as those of people, but in reality computer languages are quite similar, more like regional dialects than like independent languages. Hence, once you learn one, it is easy to pick up others. This similarity occurs because all computers are constructed from hardware technologies based on similar underlying principles and because there are a few basic operations that all computers must provide. Moreover, computer designers have a common goal: to find a language that makes it easy to build the hardware and the compiler while maximizing performance and minimizing cost and power. This goal is time honored; the following quote was written before you could buy a computer, and it is as true today as it was in 1947: It is easy to see by formal-logical methods that there exist certain [instruction sets] that are in abstract adequate to control and cause the execution of any se­quence of operations . . . . The really decisive considerations from the present point of view, in selecting an [instruction set], are more of a practical nature: simplicity of the equipment demanded by the [instruction set], and the clarity of its application to the actually important problems together with the speed of its handling of those problems. Burks, Goldstine, and von Neumann, 1947 The “simplicity of the equipment” is as valuable a consideration for today’s computers as it was for those of the 1950s. The goal of this chapter is to teach an instruction set that follows this advice, showing both how it is represented in hardware and the relationship between high-level programming languages and this more primitive one. Our examples are in the C programming language; Section 2.15 on the CD shows how these would change for an object-oriented language like Java. instruction set The vocabu­lary of commands understood by a given architecture.
clipped_hennesy_Page_74_Chunk5431
By learning how to represent instructions, you will also discover the ­secret of computing: the stored-program concept. Moreover, you will exercise your “for­eign language” skills by writing programs in the language of the computer and running them on the simulator that comes with this book. You will also see the impact of programming languages and compiler optimization on performance. We conclude with a look at the historical evolution of instruction sets and an overview of other computer dialects. The chosen instruction set comes from MIPS Technologies, which is an elegant example of the instruction sets designed since the 1980s. Later, we will take a quick look at two other popular instruction sets. ARM is quite similar to MIPS, and more than three bil­lion ARM processors were shipped in embedded devices in 2008. The other exam­ple, the Intel x86, is inside almost all of the 330 million PCs made in 2008. We reveal the MIPS instruction set a piece at a time, giving the rationale along with the computer structures. This top-down, step-by-step tutorial weaves the components with their explanations, making the computer’s language more palat­ able. Figure 2.1 gives a sneak preview of the instruction set covered in this chapter. 2.2 Operations of the Computer Hardware Every computer must be able to perform arithmetic. The MIPS assembly language notation add a, b, c instructs a computer to add the two variables b and c and to put their sum in a. This notation is rigid in that each MIPS arithmetic instruction performs only one operation and must always have exactly three variables. For example, suppose we want to place the sum of four variables b, c, d, and e into variable a. (In this section we are being deliberately vague about what a “variable” is; in the next section we’ll explain in detail.) The following sequence of instructions adds the four variables: add a, b, c # The sum of b and c is placed in a. add a, a, d # The sum of b, c, and d is now in a. add a, a, e # The sum of b, c, d, and e is now in a. Thus, it takes three instructions to sum the four variables. The words to the right of the sharp symbol (#) on each line above are comments for the human reader, and the computer ignores them. Note that unlike other pro­ gramming languages, each line of this language can contain at most one instruction. Another difference from C is that comments always terminate at the end of a line. stored-program concept The idea that instructions and data of many types can be stored in memory as numbers, leading to the stored- program computer. There must certainly be instructions for performing the fundamental arithmetic operations. Burks, Goldstine, and von Neumann, 1947 2.2 Operations of the Computer Hardware 77
clipped_hennesy_Page_75_Chunk5432
78 Chapter 2 Instructions: Language of the Computer MIPS operands Name Example Comments 32 registers $s0–$s7, $t0–$t9, $zero, $a0–$a3, $v0–$v1, $gp, $fp, $sp, $ra, $at Fast locations for data. In MIPS, data must be in registers to perform arithmetic, register $zero always equals 0, and register $at is reserved by the assembler to handle large constants. 230 memory words Memory[0], Memory[4], . . . , Memory[4294967292] Accessed only by data transfer instructions. MIPS uses byte addresses, so sequential word addresses differ by 4. Memory holds data structures, arrays, and spilled registers. MIPS assembly language Category Instruction Example Meaning Comments Arithmetic add add $s1,$s2,$s3 $s1 = $s2 + $s3 Three register operands subtract sub $s1,$s2,$s3 $s1 = $s2 – $s3 Three register operands add immediate addi $s1,$s2,20 $s1 = $s2 + 20 Used to add constants 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 lh $s1,20($s2) $s1 = Memory[$s2 + 20] Halfword memory to register 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 lb $s1,20($s2) $s1 = Memory[$s2 + 20] Byte from memory to register 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 condition. word sc $s1,20($s2) Memory[$s2+20]=$s1;$s1=0 or 1 Store word as 2nd half of atomic swap load upper immed. lui $s1,20 $s1 = 20 * 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,20 $s1 = $s2 & 20 Bit-by-bit AND reg with constant or immediate ori $s1,$s2,20 $s1 = $s2 | 20 Bit-by-bit OR reg 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 Conditional 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; for beq, bne set on less than unsigned sltu $s1,$s2,$s3 if ($s2 < $s3) $s1 = 1; else $s1 = 0 Compare less than unsigned set less than immediate slti $s1,$s2,20 if ($s2 < 20) $s1 = 1; else $s1 = 0 Compare less than constant set less than immediate unsigned sltiu $s1,$s2,20 if ($s2 < 20) $s1 = 1; else $s1 = 0 Compare less than constant unsigned Unconditional 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 2.1 MIPS assembly language revealed in this chapter. This information is also found in Column 1 of the MIPS Reference Data Card at the front of this book.
clipped_hennesy_Page_76_Chunk5433
The natural number of operands for an operation like addition is three: the two numbers being added together and a place to put the sum. Requiring every instruction to have exactly three operands, no more and no less, conforms to the philosophy of keeping the hardware simple: hardware for a variable number of operands is more complicated than hardware for a fixed number. This situation illustrates the first of four underlying principles of hardware ­design: Design Principle 1: Simplicity favors regularity. We can now show, in the two examples that follow, the relationship of pro­grams written in higher-level programming languages to programs in this more primitive notation. Compiling Two C Assignment Statements into MIPS This segment of a C program contains the five variables a, b, c, d, and e. Since Java evolved from C, this example and the next few work for either high-level programming language: a = b + c; d = a – e; The translation from C to MIPS assembly language instructions is performed by the compiler. Show the MIPS code produced by a compiler. A MIPS instruction operates on two source operands and places the result in one destination operand. Hence, the two simple statements above compile directly into these two MIPS assembly language instructions: add a, b, c sub d, a, e Compiling a Complex C Assignment into MIPS A somewhat complex statement contains the five variables f, g, h, i, and j: f = (g + h) – (i + j); What might a C compiler produce? EXAMPLE ANSWER EXAMPLE 2.2 Operations of the Computer Hardware 79
clipped_hennesy_Page_77_Chunk5434
80 Chapter 2 Instructions: Language of the Computer The compiler must break this statement into several assembly instructions, since only one operation is performed per MIPS instruction. The first MIPS instruction calculates the sum of g and h. We must place the result some­where, so the compiler creates a temporary variable, called t0: add t0,g,h # temporary variable t0 contains g + h Although the next operation is subtract, we need to calculate the sum of i and j before we can subtract. Thus, the second instruction places the sum of i and j in another temporary variable created by the compiler, called t1: add t1,i,j # temporary variable t1 contains i + j Finally, the subtract instruction subtracts the second sum from the first and places the difference in the variable f, completing the compiled code: sub f,t0,t1 # f gets t0 – t1, which is (g + h) – (i + j) For a given function, which programming language likely takes the most lines of code? Put the three representations below in order. 1. Java 2. C 3. MIPS assembly language Elaboration: To increase portability, Java was originally envisioned as relying on a soft­ware interpreter. The instruction set of this interpreter is called Java bytecodes (see Section 2.15 on the CD), which is quite different from the MIPS instruction set. To get performance close to the equivalent C program, Java systems today typically compile Java bytecodes into the native instruction sets like MIPS. Because this compilation is normally done much later than for C programs, such Java compilers are often called Just In Time (JIT) compilers. Section 2.12 shows how JITs are used later than C compilers in the start-up process, and Section 2.13 shows the performance consequences of compiling versus interpreting Java programs. 2.3 Operands of the Computer Hardware Unlike programs in high-level languages, the operands of arithmetic instructions are restricted; they must be from a limited number of special locations built directly in hardware called registers. Registers are primitives used in hardware design that ANSWER Check Yourself
clipped_hennesy_Page_78_Chunk5435
are also visible to the programmer when the computer is completed, so you can think of registers as the bricks of computer construction. The size of a register in the MIPS architecture is 32 bits; groups of 32 bits occur so frequently that they are given the name word in the MIPS architecture. One major difference between the variables of a programming language and registers is the limited number of registers, typically 32 on current computers, like MIPS. (See Section 2.20 on the CD for the history of the number of reg- isters.) Thus, continu­ing in our top-down, stepwise evolution of the symbolic ­representation of the MIPS language, in this section we have added the restriction that the three oper­ands of MIPS arithmetic instructions must each be chosen from one of the 32 32-bit registers. The reason for the limit of 32 registers may be found in the second of our four underlying design principles of hardware technology: Design Principle 2: Smaller is faster. A very large number of registers may increase the clock cycle time simply because it takes electronic signals longer when they must travel farther. Guidelines such as “smaller is faster” are not absolutes; 31 registers may not be faster than 32. Yet, the truth behind such observations causes computer designers to take them seriously. In this case, the designer must balance the craving of pro­ grams for more registers with the designer’s desire to keep the clock cycle fast. Another reason for not using more than 32 is the number of bits it would take in the instruction format, as Section 2.5 demonstrates. Chapter 4 shows the central role that registers play in hardware construction; as we shall see in this chapter, effective use of registers is critical to program perfor­mance. Although we could simply write instructions using numbers for registers, from 0 to 31, the MIPS convention is to use two-character names following a dollar sign to represent a register. Section 2.8 will explain the reasons behind these names. For now, we will use $s0, $s1, . . . for registers that correspond to variables in C and Java programs and $t0, $t1, . . . for temporary registers needed to compile the program into MIPS instructions. Compiling a C Assignment Using Registers It is the compiler’s job to associate program variables with registers. Take, for instance, the assignment statement from our earlier example: f = (g + h) – (i + j); The variables f, g, h, i, and j are assigned to the registers $s0, $s1, $s2, $s3, and $s4, respectively. What is the compiled MIPS code? word The natural unit of access in a computer, usually a group of 32 bits; corresponds to the size of a register in the MIPS architecture. EXAMPLE 2.3 Operands of the Computer Hardware 81
clipped_hennesy_Page_79_Chunk5436
82 Chapter 2 Instructions: Language of the Computer The compiled program is very similar to the prior example, except we replace the variables with the register names mentioned above plus two temporary registers, $t0 and $t1, which correspond to the temporary variables above: add $t0,$s1,$s2 # register $t0 contains g + h add $t1,$s3,$s4 # register $t1 contains i + j sub $s0,$t0,$t1 # f gets $t0 – $t1, which is (g + h)–(i + j) Memory Operands Programming languages have simple variables that contain single data elements, as in these examples, but they also have more complex data structures—arrays and structures. These complex data structures can contain many more data ­elements than there are registers in a computer. How can a computer represent and access such large structures? Recall the five components of a computer introduced in Chapter 1 and repeated on page 75. The processor can keep only a small amount of data in regis­ters, but computer memory contains billions of data elements. Hence, data struc­tures (arrays and structures) are kept in memory. As explained above, arithmetic operations occur only on registers in MIPS instructions; thus, MIPS must include instructions that transfer data between memory and registers. Such instructions are called data transfer instructions. To access a word in memory, the instruction must supply the memory address. Memory is just a large, single-dimensional array, with the address acting as the index to that array, starting at 0. For example, in Figure 2.2, the address of the third data element is 2, and the value of Memory[2] is 10. ANSWER data transfer instruction A command that moves data between memory and registers. address A value used to delin­eate the location of a ­specific data element within a memory array. FIGURE 2.2 Memory addresses and contents of memory at those locations. If these ele­ments were words, these addresses would be incorrect, since MIPS actually uses byte addressing, with each word representing four bytes. Figure 2.3 shows the memory addressing for sequential word addresses. Processor Memory Address Data 1 101 10 100 0 1 2 3
clipped_hennesy_Page_80_Chunk5437
The data transfer instruction that copies data from memory to a register is traditionally called load. The format of the load instruction is the name of the opera­tion followed by the register to be loaded, then a constant and register used to access memory. The sum of the constant portion of the instruction and the con­ tents of the second register forms the memory address. The ­actual MIPS name for this instruction is lw, standing for load word. Compiling an Assignment When an Operand Is in Memory Let’s assume that A is an array of 100 words and that the compiler has asso- ciated the variables g and h with the registers $s1 and $s2 as before. Let’s also assume that the starting address, or base address, of the array is in $s3. ­Compile this C assignment statement: g = h + A[8]; Although there is a single operation in this assignment statement, one of the operands is in memory, so we must first transfer A[8] to a register. The address of this array element is the sum of the base of the array A, found in reg­ister $s3, plus the number to select element 8. The data should be placed in a temporary register for use in the next instruction. Based on ­Figure 2.2, the first compiled instruction is lw $t0,8($s3) # Temporary reg $t0 gets A[8] (On the next page we’ll make a slight adjustment to this instruction, but we’ll use this simplified version for now.) The following instruction can operate on the value in $t0 (which equals A[8]) since it is in a register. The instruction must add h (contained in $s2) to A[8] ($t0) and put the sum in the register corresponding to g (associated with $s1): add $s1,$s2,$t0 # g = h + A[8] The constant in a data transfer instruction (8) is called the offset, and the reg­ ister added to form the address ($s3) is called the base register. EXAMPLE ANSWER 2.3 Operands of the Computer Hardware 83
clipped_hennesy_Page_81_Chunk5438
84 Chapter 2 Instructions: Language of the Computer In addition to associating variables with registers, the compiler allocates data structures like arrays and structures to locations in memory. The compiler can then place the proper starting address into the data transfer instructions. Since 8-bit bytes are useful in many programs, most architectures address indi­ vidual bytes. Therefore, the address of a word matches the address of one of the 4 bytes within the word, and addresses of sequential words differ by 4. For example, ­Figure 2.3 shows the actual MIPS addresses for the words in Figure 2.2; the byte address of the third word is 8. In MIPS, words must start at addresses that are multiples of 4. This require­ ment is called an alignment restriction, and many architectures have it. (Chapter 4 suggests why alignment leads to faster data transfers.) Computers divide into those that use the address of the leftmost or “big end” byte as the word address versus those that use the rightmost or “little end” byte. MIPS is in the big-endian camp. (Appendix B, shows the two options to number bytes in a word.) Byte addressing also affects the array index. To get the proper byte address in the code above, the offset to be added to the base register $s3 must be 4 × 8, or 32, so that the load address will select A[8] and not A[8/4]. (See the related pitfall on page 175 of Section 2.18.) Hardware/ Software Interface alignment restriction A requirement that data be aligned in memory on natural boundaries. FIGURE 2.3 Actual MIPS memory addresses and contents of memory for those words. The changed addresses are highlighted to contrast with Figure 2.2. Since MIPS addresses each byte, word addresses are multiples of 4: there are 4 bytes in a word. Processor Memory Byte Address Data 1 101 10 100 0 4 8 12
clipped_hennesy_Page_82_Chunk5439
The instruction complementary to load is traditionally called store; it copies data from a register to memory. The format of a store is similar to that of a load: the name of the operation, followed by the register to be stored, then offset to select the array element, and finally the base register. Once again, the MIPS address is specified in part by a constant and in part by the contents of a register. The actual MIPS name is sw, standing for store word. Compiling Using Load and Store Assume variable h is associated with register $s2 and the base address of the array A is in $s3. What is the MIPS assembly code for the C assignment state­ ment below? A[12] = h + A[8]; Although there is a single operation in the C statement, now two of the oper­ ands are in memory, so we need even more MIPS instructions. The first two instructions are the same as the prior example, except this time we use the proper offset for byte addressing in the load word instruction to select A[8], and the add instruction places the sum in $t0: lw $t0,32($s3) # Temporary reg $t0 gets A[8] add $t0,$s2,$t0 # Temporary reg $t0 gets h + A[8] The final instruction stores the sum into A[12], using 48 (4 × 12) as the off­set and register $s3 as the base register. sw $t0,48($s3) # Stores h + A[8] back into A[12] Load word and store word are the instructions that copy words between memory and registers in the MIPS architecture. Other brands of computers use other instructions along with load and store to transfer data. An architecture with such alternatives is the Intel x86, described in Section 2.17. EXAMPLE ANSWER 2.3 Operands of the Computer Hardware 85
clipped_hennesy_Page_83_Chunk5440
86 Chapter 2 Instructions: Language of the Computer Many programs have more variables than computers have registers. Consequently, the compiler tries to keep the most frequently used variables in registers and places the rest in memory, using loads and stores to move variables between regis­ters and memory. The process of putting less commonly used variables (or those needed later) into memory is called spilling registers. The hardware principle relating size and speed suggests that memory must be slower than registers, since there are fewer registers. This is indeed the case; data accesses are faster if data is in registers instead of memory. Moreover, data is more useful when in a register. A MIPS arithmetic instruc­ tion can read two registers, operate on them, and write the result. A MIPS data transfer instruction only reads one operand or writes one operand, without oper­ ating on it. Thus, registers take less time to access and have higher throughput than mem­ory, making data in registers both faster to access and simpler to use. Accessing registers also uses less energy than accessing memory. To achieve highest performance and conserve energy, compilers must use registers ­efficiently. Constant or Immediate Operands Many times a program will use a constant in an operation—for example, incre­ menting an index to point to the next element of an array. In fact, more than half of the MIPS arithmetic instructions have a constant as an operand when running the SPEC CPU2006 benchmarks. Using only the instructions we have seen so far, we would have to load a con­stant from memory to use one. (The constants would have been placed in mem­ory when the program was loaded.) For example, to add the constant 4 to register $s3, we could use the code lw $t0, AddrConstant4($s1) # $t0 = constant 4 add $s3,$s3,$t0 # $s3 = $s3 + $t0 ($t0 == 4) assuming that $s1 + AddrConstant4 is the memory address of the constant 4. An alternative that avoids the load instruction is to offer versions of the arith­ metic instructions in which one operand is a constant. This quick add instruction with one constant operand is called add immediate or addi. To add 4 to register $s3, we just write addi $s3,$s3,4 # $s3 = $s3 + 4 Immediate instructions illustrate the third hardware design principle, first mentioned in the Fallacies and Pitfalls of Chapter 1: Design Principle 3: Make the common case fast. Hardware/ Software Interface
clipped_hennesy_Page_84_Chunk5441
Constant operands occur frequently, and by including constants inside arithmetic instructions, operations are much faster and use less energy than if constants were loaded from memory. The constant zero has another role, which is to simplify the instruction set by offering useful variations. For example, the move operation is just an add instruc­ tion where one operand is zero. Hence, MIPS dedicates a register $zero to be hard­ wired to the value zero. (As you might expect, it is register number 0.) Given the importance of registers, what is the rate of increase in the number of registers in a chip over time? 1. Very fast: They increase as fast as Moore’s law, which predicts doubling the number of transistors on a chip every 18 months. 2. Very slow: Since programs are usually distributed in the language of the computer, there is inertia in instruction set architecture, and so the number of registers increases only as fast as new instruction sets become viable. Elaboration: Although the MIPS registers in this book are 32 bits wide, there is a 64-bit version of the MIPS instruction set with 32 64-bit registers. To keep them straight, they are offi­cially called MIPS-32 and MIPS-64. In this chapter, we use a subset of MIPS-32. Appendix E shows the differences between MIPS-32 and MIPS-64. The MIPS offset plus base register addressing is an excellent match to structures as well as arrays, since the register can point to the beginning of the structure and the offset can select the desired element. We’ll see such an example in Section 2.13. The register in the data transfer instructions was originally invented to hold an index of an array with the offset used for the starting address of an array. Thus, the base register is also called the index register. Today’s memories are much larger and the software model of data allocation is more sophisticated, so the base address of the array is normally passed in a register since it won’t fit in the offset, as we shall see. Since MIPS supports negative constants, there is no need for subtract immediate in MIPS. 2.4 Signed and Unsigned Numbers First, let’s quickly review how a computer represents numbers. Humans are taught to think in base 10, but numbers may be represented in any base. For example, 123 base 10 = 1111011 base 2. Numbers are kept in computer hardware as a series of high and low electronic signals, and so they are considered base 2 numbers. (Just as base 10 numbers are called decimal numbers, base 2 numbers are called binary numbers.) A single digit of a binary number is thus the “atom” of computing, since all information is composed of binary digits or bits. This fundamental building block Check Yourself binary digit Also called binary bit. One of the two ­numbers in base 2, 0 or 1, that are the components of information. 2.4 Signed and Unsigned Numbers 87
clipped_hennesy_Page_85_Chunk5442
88 Chapter 2 Instructions: Language of the Computer can be one of two values, which can be thought of as several alternatives: high or low, on or off, true or false, or 1 or 0. Generalizing the point, in any number base, the value of ith digit d is d × Basei where i starts at 0 and increases from right to left. This leads to an obvious way to number the bits in the word: simply use the power of the base for that bit. We subscript decimal numbers with ten and binary numbers with two. For example, 1011two represents (1 × 23) + (0 × 22) + (1 × 21) + (1 × 20)ten = (1 × 8) + (0 × 4) + (1 × 2) + (1 × 1)ten = 8 + 0 + 2 + 1ten = 11ten We number the bits 0, 1, 2, 3, . . . from right to left in a word. The drawing below shows the numbering of bits within a MIPS word and the placement of the num­ber 1011two: 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1 (32 bits wide) Since words are drawn vertically as well as horizontally, leftmost and rightmost may be unclear. Hence, the phrase least significant bit is used to refer to the right­ most bit (bit 0 above) and most significant bit to the leftmost bit (bit 31). The MIPS word is 32 bits long, so we can represent 232 different 32‑bit patterns. It is natural to let these combinations represent the numbers from 0 to 232 - 1 (4,294,967,295ten): 0000 0000 0000 0000 0000 0000 0000 0000two = 0ten 0000 0000 0000 0000 0000 0000 0000 0001two = 1ten 0000 0000 0000 0000 0000 0000 0000 0010two = 2ten . . . . . . 1111 1111 1111 1111 1111 1111 1111 1101two = 4,294,967,293ten 1111 1111 1111 1111 1111 1111 1111 1110two = 4,294,967,294ten 1111 1111 1111 1111 1111 1111 1111 1111two = 4,294,967,295ten That is, 32-bit binary numbers can be represented in terms of the bit value times a power of 2 (here xi means the ith bit of x): least significant bit The right­most bit in a MIPS word. most significant bit The left­most bit in a MIPS word.
clipped_hennesy_Page_86_Chunk5443
(x31 × 231) + (x30 × 230) + (x29 × 229) + . . . + (x1 × 21) + (x0 × 20) Keep in mind that the binary bit patterns above are simply representatives of numbers. Numbers really have an infinite number of digits, with almost all being 0 except for a few of the rightmost digits. We just don’t normally show leading 0s. Hardware can be designed to add, subtract, multiply, and divide these binary bit patterns. If the number that is the proper result of such operations cannot be represented by these rightmost hardware bits, overflow is said to have occurred. It’s up to the programming language, the operating system, and the program to determine what to do if overflow occurs. Computer programs calculate both positive and negative numbers, so we need a representation that distinguishes the positive from the negative. The most obvi­ous solution is to add a separate sign, which conveniently can be represented in a single bit; the name for this representation is sign and magnitude. Alas, sign and magnitude representation has several shortcomings. First, it’s not obvious where to put the sign bit. To the right? To the left? Early computers tried both. Second, adders for sign and magnitude may need an extra step to set the sign because we can’t know in advance what the proper sign will be. Finally, a separate sign bit means that sign and magnitude has both a positive and a negative zero, which can lead to problems for inattentive programmers. As a result of these shortcomings, sign and magnitude representation was soon abandoned. In the search for a more attractive alternative, the question arose as to what would be the result for unsigned numbers if we tried to subtract a large number from a small one. The answer is that it would try to borrow from a string of lead­ing 0s, so the result would have a string of leading 1s. Given that there was no obvious better alternative, the final solution was to pick the representation that made the hardware simple: leading 0s mean positive, and leading 1s mean negative. This convention for representing signed binary numbers is called two’s complement representation: 0000 0000 0000 0000 0000 0000 0000 0000two = 0ten 0000 0000 0000 0000 0000 0000 0000 0001two = 1ten 0000 0000 0000 0000 0000 0000 0000 0010two = 2ten . . . . . . 0111 1111 1111 1111 1111 1111 1111 1101two = 2,147,483,645ten 0111 1111 1111 1111 1111 1111 1111 1110two = 2,147,483,646ten 0111 1111 1111 1111 1111 1111 1111 1111two = 2,147,483,647ten 1000 0000 0000 0000 0000 0000 0000 0000two = –2,147,483,648ten 1000 0000 0000 0000 0000 0000 0000 0001two = –2,147,483,647ten 1000 0000 0000 0000 0000 0000 0000 0010two = –2,147,483,646ten . . . . . . 1111 1111 1111 1111 1111 1111 1111 1101two = –3ten 1111 1111 1111 1111 1111 1111 1111 1110two = –2ten 1111 1111 1111 1111 1111 1111 1111 1111two = –1ten 2.4 Signed and Unsigned Numbers 89
clipped_hennesy_Page_87_Chunk5444
90 Chapter 2 Instructions: Language of the Computer The positive half of the numbers, from 0 to 2,147,483,647ten (231 - 1), use the same representation as before. The following bit pattern (1000 . . . 0000two) rep­ resents the most negative number -2,147,483,648ten (-231). It is followed by a declining set of negative numbers: -2,147,483,647ten (1000 . . . 0001two) down to -1ten (1111 . . . 1111two). Two’s complement does have one negative number, -2,147,483,648ten, that has no corresponding positive number. Such imbalance was also a worry to the inat­ tentive programmer, but sign and magnitude had problems for both the program­ mer and the hardware designer. Consequently, every computer today uses two’s complement binary representations for signed numbers. Two’s complement representation has the advantage that all negative numbers have a 1 in the most significant bit. Consequently, hardware needs to test only this bit to see if a number is positive or negative (with the number 0 considered posi­ tive). This bit is often called the sign bit. By recognizing the role of the sign bit, we can represent positive and negative 32-bit numbers in terms of the bit value times a power of 2: (x31 × -231) + (x30 × 230) + (x29 × 229) + . . . + (x1 × 21) + (x0 × 20) The sign bit is multiplied by -231, and the rest of the bits are then multiplied by positive versions of their respective base values. Binary to Decimal Conversion What is the decimal value of this 32‑bit two’s complement number? 1111 1111 1111 1111 1111 1111 1111 1100two Substituting the number’s bit values into the formula above: (1 × -231) + (1 × 230) + (1 × 229) + . . . + (1 × 22) + (0 × 21) + (0 × 20) = -231 + 230 + 229 + . . . + 22 + 0 + 0 = -2,147,483,648ten + 2,147,483,644ten = - 4ten We’ll see a shortcut to simplify conversion from negative to positive soon. Just as an operation on unsigned numbers can overflow the capacity of hard­ ware to represent the result, so can an operation on two’s complement numbers. Overflow occurs when the leftmost retained bit of the binary bit pattern is not the same as the infinite number of digits to the left (the sign bit is incorrect): a 0 on the left of the bit pattern when the number is negative or a 1 when the number is positive. EXAMPLE ANSWER
clipped_hennesy_Page_88_Chunk5445
Unlike the numbers discussed above, memory addresses naturally start at 0 and con- tinue to the largest address. Put another way, negative addresses make no sense. Thus, programs want to deal sometimes with numbers that can be positive or negative and sometimes with numbers that can be only positive. Some pro­gramming languages reflect this distinction. C, for example, names the former integers (declared as int in the program) and the latter unsigned integers (unsigned int). Some C style guides even recommend declaring the former as signed int to keep the distinction clear. Let’s examine two useful shortcuts when working with two’s complement numbers. The first shortcut is a quick way to negate a two’s complement binary number. Simply invert every 0 to 1 and every 1 to 0, then add one to the result. This shortcut is based on the observation that the sum of a number and its inverted representation must be 111 . . . 111two, which represents -1. Since x + x– = -1, therefore x + x– + 1 = 0 or x– + 1 = -x. Negation Shortcut Negate 2ten, and then check the result by negating -2ten. 2ten = 0000 0000 0000 0000 0000 0000 0000 0010two Negating this number by inverting the bits and adding one, 1111 1111 1111 1111 1111 1111 1111 1101two + 1two = 1111 1111 1111 1111 1111 1111 1111 1110two = –2ten Hardware/ Software Interface EXAMPLE ANSWER 2.4 Signed and Unsigned Numbers 91
clipped_hennesy_Page_89_Chunk5446
92 Chapter 2 Instructions: Language of the Computer Going the other direction, 1111 1111 1111 1111 1111 1111 1111 1110two is first inverted and then incremented: 0000 0000 0000 0000 0000 0000 0000 0001two + 1two = 0000 0000 0000 0000 0000 0000 0000 0010two = 2ten Our next shortcut tells us how to convert a binary number represented in n bits to a number represented with more than n bits. For example, the immediate field in the load, store, branch, add, and set on less than instructions ­contains a two’s complement 16‑bit number, representing -32,768ten (-215) to 32,767ten (215 - 1). To add the immediate field to a 32‑bit register, the computer must convert that 16‑bit number to its 32‑bit equivalent. The shortcut is to take the most significant bit from the smaller quantity—the sign bit—and replicate it to fill the new bits of the larger quantity. The old bits are simply copied into the right portion of the new word. This shortcut is commonly called sign ­extension. Sign Extension Shortcut Convert 16‑bit binary versions of 2ten and -2ten to 32‑bit binary numbers. The 16‑bit binary version of the number 2 is 0000 0000 0000 0010two = 2ten It is converted to a 32‑bit number by making 16 copies of the value in the most significant bit (0) and placing that in the left-hand half of the word. The right half gets the old value: 0000 0000 0000 0000 0000 0000 0000 0010two = 2ten EXAMPLE ANSWER
clipped_hennesy_Page_90_Chunk5447
Let’s negate the 16‑bit version of 2 using the earlier shortcut. Thus, 0000 0000 0000 0010two becomes 1111 1111 1111 1101two + 1two = 1111 1111 1111 1110two Creating a 32‑bit version of the negative number means copying the sign bit 16 times and placing it on the left: 1111 1111 1111 1111 1111 1111 1111 1110two = –2ten This trick works because positive two’s complement numbers really have an infinite number of 0s on the left and negative two’s complement numbers have an infinite number of 1s. The binary bit pattern representing a number hides leading bits to fit the width of the hardware; sign extension simply restores some of them. Summary The main point of this section is that we need to represent both positive and neg­ ative integers within a computer word, and although there are pros and cons to any option, the overwhelming choice since 1965 has been two’s complement. What is the decimal value of this 64-bit two’s complement number? 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1000two 1) –4ten 2) –8ten 3) –16ten 4) 18,446,744,073,709,551,609ten Elaboration: Two’s complement gets its name from the rule that the unsigned sum of an n‑bit number and its negative is 2n; hence, the complement or negation of a two’s complement number x is 2n – x. Check Yourself 2.4 Signed and Unsigned Numbers 93
clipped_hennesy_Page_91_Chunk5448
94 Chapter 2 Instructions: Language of the Computer A third alternative representation to two’s complement and sign and magnitude is called one’s complement. The negative of a one’s complement is found by inverting each bit, from 0 to 1 and from 1 to 0, which helps explain its name since the complement of x is 2n – x – 1. It was also an attempt to be a better solution than sign and magnitude, and several early scientific com­puters did use the notation. This representation is similar to two’s complement except that it also has two 0s: 00 . . . 00two is positive 0 and 11 . . . 11two is negative 0. The most negative number, 10 . . . 000two, represents –2,147,483,647ten, and so the positives and negatives are bal­anced. One’s complement adders did need an extra step to subtract a number, and hence two’s complement dominates today. A final notation, which we will look at when we discuss floating point in Chapter 3, is to represent the most negative value by 00 . . . 000two and the most positive value by 11 . . . 11two, with 0 typi­cally having the value 10 . . . 00two. This is called a biased notation, since it biases the number such that the number plus the bias has a non­neg­ ative representation. Elaboration: For signed decimal numbers, we used “–” to represent negative because there are no limits to the size of a decimal number. Given a fixed word size, binary and hexadecimal (see Figure 2.4) bit strings can encode the sign; hence we do not normally use “+” or “–” with binary or hexadecimal notation. 2.5 Representing Instructions in the Computer We are now ready to explain the difference between the way humans instruct computers and the way computers see instructions. Instructions are kept in the computer as a series of high and low electronic signals and may be represented as numbers. In fact, each piece of an instruction can be considered as an individual number, and placing these numbers side by side forms the instruction. Since registers are referred to by almost all instructions, there must be a con­ vention to map register names into numbers. In MIPS assembly language, regis­ters $s0 to $s7 map onto registers 16 to 23, and registers $t0 to $t7 map onto registers 8 to 15. Hence, $s0 means register 16, $s1 means register 17, $s2 means register 18, . . . , $t0 means register 8, $t1 means register 9, and so on. We’ll describe the convention for the rest of the 32 registers in the following sections. one’s complement A notation that represents the most ­negative value by 10 . . . 000two and the most positive value by 01 . . . 11two, leaving an equal number of negatives and posi­tives but ending up with two zeros, one positive (00 . . . 00two) and one negative (11 . . . 11two). The term is also used to mean the inversion of every bit in a pattern: 0 to 1 and 1 to 0. biased notation A notation that represents the most negative value by 00 . . . 000two and the most positive value by 11 . . . 11two, with 0 typically having the value 10 . . . 00two, thereby biasing the number such that the number plus the bias has a nonnegative representation.
clipped_hennesy_Page_92_Chunk5449
Translating a MIPS Assembly Instruction into a Machine Instruction Let’s do the next step in the refinement of the MIPS language as an example. We’ll show the real MIPS language version of the instruction represented symbolically as add $t0,$s1,$s2 first as a combination of decimal numbers and then of binary numbers. The decimal representation is EXAMPLE ANSWER 0 17 18 8 0 32 Each of these segments of an instruction is called a field. The first and last fields (containing 0 and 32 in this case) in combination tell the MIPS computer that this instruction performs addition. The second field gives the number of the reg­ ister that is the first source operand of the addition operation (17 = $s1), and the third field gives the other source operand for the addition (18 = $s2). The fourth field contains the number of the register that is to receive the sum (8 = $t0). The fifth field is unused in this instruction, so it is set to 0. Thus, this instruction adds register $s1 to register $s2 and places the sum in register $t0. This instruction can also be represented as fields of binary numbers as opposed to decimal: 000000 10001 10010 01000 00000 100000 6 bits 5 bits 5 bits 5 bits 5 bits 6 bits This layout of the instruction is called the instruction format. As you can see from counting the number of bits, this MIPS instruction takes exactly 32 bits—the same size as a data word. In keeping with our design principle that simplicity favors regularity, all MIPS instructions are 32 bits long. To distinguish it from assembly language, we call the numeric version of instruc- tions machine language and a sequence of such instructions machine code. It would appear that you would now be reading and writing long, tedious strings of binary numbers. We avoid that tedium by using a higher base than binary that converts easily into binary. Since almost all computer data sizes are multiples of 4, hexadecimal (base 16) numbers are popular. Since base 16 is a power of 2, we can trivially convert by replacing each group of four binary digits by a single hexadeci- mal digit, and vice versa. Figure 2.4 converts between hexadecimal and binary. instruction format A form of representation of an instruction composed of fields of binary numbers. machine language Binary rep­resentation used for communi­cation within a computer system. hexadecimal Numbers in base 16. 2.5 Representing Instructions in the Computer 95
clipped_hennesy_Page_93_Chunk5450
96 Chapter 2 Instructions: Language of the Computer Hexadecimal Binary Hexadecimal Binary Hexadecimal Binary Hexadecimal Binary 0hex 0000two 4hex 0100two 8hex 1000two chex 1100two 1hex 0001two 5hex 0101two 9hex 1001two dhex 1101two 2hex 0010two 6hex 0110two ahex 1010two ehex 1110two 3hex 0011two 7hex 0111two bhex 1011two fhex 1111two FIGURE 2.4 The hexadecimal-binary conversion table. Just replace one hexadecimal digit by the corresponding four binary digits, and vice versa. If the length of the binary number is not a multiple of 4, go from right to left. Because we frequently deal with different number bases, to avoid confusion we will subscript decimal numbers with ten, binary numbers with two, and hexadeci­ mal numbers with hex. (If there is no subscript, the default is base 10.) By the way, C and Java use the notation 0xnnnn for hexadecimal numbers. Binary to Hexadecimal and Back Convert the following hexadecimal and binary numbers into the other base: eca8 6420hex 0001 0011 0101 0111 1001 1011 1101 1111 two Using Figure 2.4, the answer is just a table lookup one way: EXAMPLE ANSWER eca8 6420hex 1110 1100 1010 1000 0110 0100 0010 0000two And then the other direction: 0001 0011 0101 0111 1001 1011 1101 1111two 1357 9bdfhex MIPS Fields MIPS fields are given names to make them easier to discuss: op rs rt rd shamt funct 6 bits 5 bits 5 bits 5 bits 5 bits 6 bits
clipped_hennesy_Page_94_Chunk5451
2.5 Representing Instructions in the Computer 97 Here is the meaning of each name of the fields in MIPS instructions: ■ ■op: Basic operation of the instruction, traditionally called the opcode. ■ ■rs: The first register source operand. ■ ■rt: The second register source operand. ■ ■rd: The register destination operand. It gets the result of the operation. ■ ■shamt: Shift amount. (Section 2.6 explains shift instructions and this term; it will not be used until then, and hence the field contains zero in this sec­tion.) ■ ■funct: Function. This field, often called the function code, selects the specific variant of the operation in the op field. A problem occurs when an instruction needs longer fields than those shown above. For example, the load word instruction must specify two registers and a constant. If the address were to use one of the 5-bit fields in the format above, the constant within the load word instruction would be limited to only 25 or 32. This constant is used to select elements from arrays or data structures, and it often needs to be much larger than 32. This 5-bit field is too small to be useful. Hence, we have a conflict between the desire to keep all instructions the same length and the desire to have a single instruction format. This leads us to the final hardware design principle: Design Principle 4: Good design demands good compromises. The compromise chosen by the MIPS designers is to keep all instructions the same length, thereby requiring different kinds of instruction formats for different kinds of instructions. For example, the format above is called R‑type (for register) or R-format. A second type of instruction format is called I-type (for immediate) or I-format and is used by the immediate and data transfer instructions. The fields of I-format are op rs rt constant or address 6 bits 5 bits 5 bits 16 bits The 16-bit address means a load word instruction can load any word within a region of ±215 or 32,768 bytes (±213 or 8192 words) of the address in the base reg­ister rs. Similarly, add immediate is limited to constants no larger than ±215. We see that more than 32 registers would be difficult in this format, as the rs and rt fields would each need another bit, making it harder to fit everything in one word. Let’s look at the load word instruction from page 83: lw $t0,32($s3) # Temporary reg $t0 gets A[8] opcode The field that denotes the operation and format of an instruction.
clipped_hennesy_Page_95_Chunk5452
98 Chapter 2 Instructions: Language of the Computer Here, 19 (for $s3) is placed in the rs field, 8 (for $t0) is placed in the rt field, and 32 is placed in the address field. Note that the meaning of the rt field has changed for this instruction: in a load word instruction, the rt field specifies the destination register, which receives the result of the load. Although multiple formats complicate the hardware, we can reduce the complex- ity by keeping the formats similar. For example, the first three fields of the R-type and I-type formats are the same size and have the same names; the length of the fourth field in I‑type is equal to the sum of the lengths of the last three fields of R‑type. In case you were wondering, the formats are distinguished by the values in the first field: each format is assigned a distinct set of values in the first field (op) so that the hardware knows whether to treat the last half of the instruction as three fields (R-type) or as a single field (I-type). Figure 2.5 shows the numbers used in each field for the MIPS instructions covered here. Instruction Format op rs rt rd shamt funct address add R 0 reg reg reg 0 32ten n.a. sub (subtract) R 0 reg reg reg 0 34ten n.a. add immediate I 8ten reg reg n.a. n.a. n.a. constant lw (load word) I 35ten reg reg n.a. n.a. n.a. address sw (store word) I 43ten reg reg n.a. n.a. n.a. address FIGURE 2.5 MIPS instruction encoding. In the table above, “reg” means a register number between 0 and 31, “address” means a 16-bit address, and “n.a.” (not applicable) means this field does not appear in this format. Note that add and sub instructions have the same value in the op field; the hardware uses the funct field to decide the variant of the operation: add (32) or subtract (34). Translating MIPS Assembly Language into Machine Language We can now take an example all the way from what the programmer writes to what the computer executes. If $t1 has the base of the array A and $s2 corre­ sponds to h, the assignment statement A[300] = h + A[300]; is compiled into lw $t0,1200($t1) # Temporary reg $t0 gets A[300] add $t0,$s2,$t0 # Temporary reg $t0 gets h + A[300] sw $t0,1200($t1) # Stores h + A[300] back into A[300] What is the MIPS machine language code for these three instructions? EXAMPLE
clipped_hennesy_Page_96_Chunk5453
For convenience, let’s first represent the machine language instructions using decimal numbers. From Figure 2.5, we can determine the three machine lan­ guage instructions: ANSWER Note the similarity of the binary representations of the first and last instruc­ tions. The only difference is in the third bit from the left, which is highlighted here. Figure 2.6 summarizes the portions of MIPS machine language described in this section. As we shall see in Chapter 4, the similarity of the binary representa­tions of related instructions simplifies hardware design. These similarities are another example of regularity in the MIPS architecture. 2.5 Representing Instructions in the Computer 99 op rs rt rd address/ shamt funct 35 9 8 1200 0 18 8 8 0 32 43 9 8 1200 The lw instruction is identified by 35 (see Figure 2.5) in the first field (op). The base register 9 ($t1) is specified in the second field (rs), and the destination reg­ister 8 ($t0) is specified in the third field (rt). The offset to select A[300] (1200 = 300 × 4) is found in the final field (address). The add instruction that follows is specified with 0 in the first field (op) and 32 in the last field (funct). The three register operands (18, 8, and 8) are found in the second, third, and fourth fields and correspond to $s2, $t0, and $t0. The sw instruction is identified with 43 in the first field. The rest of this final instruction is identical to the lw instruction. Since 1200ten = 0000 0100 1011 0000two, the binary equivalent to the decimal form is: 100011 01001 01000 0000 0100 1011 0000 000000 10010 01000 01000 00000 100000 101011 01001 01000 0000 0100 1011 0000
clipped_hennesy_Page_97_Chunk5454
100 Chapter 2 Instructions: Language of the Computer Today’s computers are built on two key principles: 1. Instructions are represented as numbers. 2. Programs are stored in memory to be read or written, just like numbers. These principles lead to the stored-program concept; its invention let the computing genie out of its bottle. Figure 2.7 shows the power of the concept; specifically, memory can contain the source code for an editor program, the corresponding compiled machine code, the text that the compiled program is using, and even the compiler that generated the machine code. One consequence of instructions as numbers is that programs are often shipped as files of binary numbers. The commercial implication is that computers can inherit ready-made software provided they are compatible with an existing instruction set. Such “binary compatibility” often leads industry to align around a small number of instruction set architectures. The BIG Picture MIPS machine language Name Format Example Comments add R 0 18 19 17 0 32 add $s1,$s2,$s3 sub R 0 18 19 17 0 34 sub $s1,$s2,$s3 addi I 8 18 17 100 addi $s1,$s2,100 lw I 35 18 17 100 lw $s1,100($s2) sw I 43 18 17 100 sw $s1,100($s2) Field size 6 bits 5 bits 5 bits 5 bits 5 bits 6 bits All MIPS instructions are 32 bits long R-format R op rs rt rd shamt funct Arithmetic instruction format I-format I op rs rt address Data transfer format FIGURE 2.6 MIPS architecture revealed through Section 2.5. The two MIPS instruction formats so far are R and I. The first 16 bits are the same: both contain an op field, giving the base operation; an rs field, giving one of the sources; and the rt field, which speci­fies the other source operand, except for load word, where it specifies the destination register. R-format divides the last 16 bits into an rd field, specifying the destination register; the shamt field, which Section 2.6 explains; and the funct field, which specifies the specific operation of R-format instructions. I-format combines the last 16 bits into a single address field.
clipped_hennesy_Page_98_Chunk5455
What MIPS instruction does this represent? Chose from one of the four options below. Check Yourself FIGURE 2.7 The stored-program concept. Stored programs allow a computer that performs accounting to become, in the blink of an eye, a computer that helps an author write a book. The switch hap­ pens simply by loading memory with programs and data and then telling the computer to begin executing at a given location in memory. Treating instructions in the same way as data greatly simplifies both the memory hardware and the software of computer systems. Specifically, the memory technology needed for data can also be used for programs, and programs like compilers, for instance, can translate code written in a notation far more convenient for humans into code that the computer can understand. Memory Accounting program (machine code) Processor Editor program (machine code) C compiler (machine code) Payroll data Book text Source code in C for editor program op rs rt rd shamt funct 0 8 9 10 0 34 1. sub $t0, $t1, $t2 2. add $t2, $t0, $t1 3. sub $t2, $t1, $t0 4. sub $t2, $t0, $t1 2.5 Representing Instructions in the Computer 101
clipped_hennesy_Page_99_Chunk5456
102 Chapter 2 Instructions: Language of the Computer 2.6 Logical Operations Although the first computers operated on full words, it soon became clear that it was useful to operate on fields of bits within a word or even on individual bits. Examining characters within a word, each of which is stored as 8 bits, is one exam­ple of such an operation (see Section 2.9). It follows that operations were added to programming languages and instruction set architectures to simplify, among other things, the packing and unpacking of bits into words. These instructions are called logical operations. Figure 2.8 shows logical operations in C, Java, and MIPS. Logical operations C operators Java operators MIPS instructions Shift left << << sll Shift right >> >>> srl Bit-by-bit AND & & and, andi Bit-by-bit OR | | or, ori Bit-by-bit NOT ~ ~ nor FIGURE 2.8 C and Java logical operators and their corresponding MIPS instructions. MIPS implements NOT using a NOR with one operand being zero. The first class of such operations is called shifts. They move all the bits in a word to the left or right, filling the emptied bits with 0s. For example, if register $s0 contained 0000 0000 0000 0000 0000 0000 0000 1001two = 9ten and the instruction to shift left by 4 was executed, the new value would be: 0000 0000 0000 0000 0000 0000 1001 0000two= 144ten The dual of a shift left is a shift right. The actual name of the two MIPS shift instructions are called shift left logical (sll) and shift right logical (srl). The fol­lowing “Contrariwise,” continued Tweedledee, “if it was so, it might be; and if it were so, it would be; but as it isn’t, it ain’t. That’s logic.” Lewis Carroll, Alice’s Adven­tures in Wonderland, 1865
clipped_hennesy_Page_100_Chunk5457
instruction performs the operation above, assuming that the original value was in register $s0 and the result should go in register $t2: sll $t2,$s0,4 # reg $t2 = reg $s0 << 4 bits We delayed explaining the shamt field in the R-format. Used in shift instruc­tions, it stands for shift amount. Hence, the machine language version of the instruction above is op rs rt rd shamt funct 0 0 16 10 4 0 The encoding of sll is 0 in both the op and funct fields, rd contains 10 (register $t2), rt contains 16 (register $s0), and shamt contains 4. The rs field is unused and thus is set to 0. Shift left logical provides a bonus benefit. Shifting left by i bits gives the same result as multiplying by 2i, just as shifting a decimal number by i digits is equivalent to multiplying by 10i. For example, the above sll shifts by 4, which gives the same result as multiplying by 24 or 16. The first bit pattern above represents 9, and 9 × 16 = 144, the value of the second bit pattern. Another useful operation that isolates fields is AND. (We capitalize the word to avoid confusion between the operation and the English conjunction.) AND is a bit-by‑bit operation that leaves a 1 in the result only if both bits of the operands are 1. For example, if register $t2 contains 0000 0000 0000 0000 0000 1101 1100 0000two and register $t1 contains 0000 0000 0000 0000 0011 1100 0000 0000two then, after executing the MIPS instruction and $t0,$t1,$t2 # reg $t0 = reg $t1 & reg $t2 the value of register $t0 would be 0000 0000 0000 0000 0000 1100 0000 0000two AND A logical bit-by- bit oper­ation with two operands that calculates a 1 only if there is a 1 in both operands. 2.6 Logical Operations 103
clipped_hennesy_Page_101_Chunk5458
104 Chapter 2 Instructions: Language of the Computer As you can see, AND can apply a bit pattern to a set of bits to force 0s where there is a 0 in the bit pattern. Such a bit pattern in conjunction with AND is tradition­ally called a mask, since the mask “conceals” some bits. To place a value into one of these seas of 0s, there is the dual to AND, called OR. It is a bit-by‑bit operation that places a 1 in the result if either operand bit is a 1. To elaborate, if the registers $t1 and $t2 are unchanged from the preceding example, the result of the MIPS instruction or $t0,$t1,$t2 # reg $t0 = reg $t1 | reg $t2 is this value in register $t0: 0000 0000 0000 0000 0011 1101 1100 0000two The final logical operation is a contrarian. NOT takes one operand and places a 1 in the result if one operand bit is a 0, and vice versa. In keeping with the three-operand format, the designers of MIPS decided to include the instruction NOR (NOT OR) instead of NOT. If one operand is zero, then it is equivalent to NOT: A NOR 0 = NOT (A OR 0) = NOT (A). If the register $t1 is unchanged from the preceding example and register $t3 has the value 0, the result of the MIPS instruction nor $t0,$t1,$t3 # reg $t0 = ~ (reg $t1 | reg $t3) is this value in register $t0: 1111 1111 1111 1111 1100 0011 1111 1111two Figure 2.8 above shows the relationship between the C and Java operators and the MIPS instructions. Constants are useful in AND and OR logical operations as well as in arithmetic operations, so MIPS also provides the instructions and immediate (andi) and or immediate (ori). Constants are rare for NOR, since its main use is to invert the bits of a single operand; thus, the MIPS instruction set architecture has no immediate version. Elaboration: The full MIPS instruction set also includes exclusive or (XOR), which sets the bit to 1 when two corresponding bits differ, and to 0 when they are the same. C allows bit fields or fields to be defined within words, both allowing objects to be OR A logical bit-by- bit opera­tion with two operands that cal­culates a 1 if there is a 1 in either operand. NOT A logical bit-by- bit oper­ation with one operand that inverts the bits; that is, it replaces every 1 with a 0, and every 0 with a 1. NOR A logical bit-by- bit oper­ation with two operands that calculates the NOT of the OR of the two operands. That is, it cal­culates a 1 only if there is a 0 in both operands.
clipped_hennesy_Page_102_Chunk5459
packed within a word and to match an externally enforced interface such as an I/O device. All fields must fit within a single word. Fields are unsigned integers that can be as short as 1 bit. C compilers insert and extract fields using logical instructions in MIPS: and, or, sll, and srl. Which operations can isolate a field in a word? 1. AND 2. A shift left followed by a shift right 2.7 Instructions for Making Decisions What distinguishes a computer from a simple calculator is its ability to make deci- sions. Based on the input data and the values created during ­computation, different instructions execute. Decision making is commonly ­represented in programming languages using the if statement, sometimes combined with go to statements and labels. MIPS assembly language includes two ­decision-making instructions, simi- lar to an if statement with a go to. The first ­instruction is beq register1, register2, L1 This instruction means go to the statement labeled L1 if the value in register1 equals the value in register2. The mnemonic beq stands for branch if equal. The second instruction is bne register1, register2, L1 It means go to the statement labeled L1 if the value in register1 does not equal the value in register2. The mnemonic bne stands for branch if not equal. These two instructions are traditionally called conditional branches. Check Yourself The utility of an automatic computer lies in the possibility of using a given sequence of instructions repeatedly, the number of times it is iterated being dependent upon the results of the computation. ...This choice can be made to depend upon the sign of a number (zero being reckoned as plus for machine purposes). Consequently, we introduce an [instruction] (the conditional transfer [instruction]) which will, depending on the sign of a given number, cause the proper one of two routines to be exe­cuted. Burks, Goldstine, and von Neumann, 1947 conditional branch An instruction that requires the comparison of two values and that allows for a subsequent transfer of control to a new address in the program based on the outcome of the comparison. 2.7 Instructions for Making Decisions 105
clipped_hennesy_Page_103_Chunk5460
106 Chapter 2 Instructions: Language of the Computer Compiling if-then-else into Conditional Branches In the following code segment, f, g, h, i, and j are variables. If the five vari­ ables f through j correspond to the five registers $s0 through $s4, what is the compiled MIPS code for this C if statement? if (i == j) f = g + h; else f = g – h; Figure 2.9 is a flowchart of what the MIPS code should do. The first expres­ sion compares for equality, so it would seem that we would want the branch if registers are equal instruction (beq). In general, the code will be more effi­cient if we test for the opposite condition to branch over the code that per­forms the subsequent then part of the if (the label Else is defined below) and so we use the branch if registers are not equal instruction (bne): bne $s3,$s4,Else # go to Else if i ≠ j The next assignment statement performs a single operation, and if all the operands are allocated to registers, it is just one instruction: add $s0,$s1,$s2 # f = g + h (skipped if i ≠ j) We now need to go to the end of the if statement. This example introduces another kind of branch, often called an unconditional branch. This instruc­ tion says that the processor always follows the branch. To distinguish between conditional and unconditional branches, the MIPS name for this type of instruction is jump, abbreviated as j (the label Exit is defined below). j Exit # go to Exit The assignment statement in the else portion of the if statement can again be compiled into a single instruction. We just need to append the label Else to this instruction. We also show the label Exit that is after this instruction, showing the end of the if-then-else compiled code: Else:sub $s0,$s1,$s2 # f = g – h (skipped if i = j) Exit: EXAMPLE ANSWER
clipped_hennesy_Page_104_Chunk5461
Notice that the assembler relieves the compiler and the assembly language pro­ grammer from the tedium of calculating addresses for branches, just as it does for calculating data addresses for loads and stores (see Section 2.12). Compilers frequently create branches and labels where they do not appear in the programming language. Avoiding the burden of writing explicit labels and branches is one benefit of writing in high-level programming languages and is a reason coding is faster at that level. Loops Decisions are important both for choosing between two alternatives—found in if statements—and for iterating a computation—found in loops. The same assem­bly instructions are the building blocks for both cases. Compiling a while Loop in C Here is a traditional loop in C: while (save[i] == k) i += 1; Assume that i and k correspond to registers $s3 and $s5 and the base of the array save is in $s6. What is the MIPS assembly code corresponding to this C segment? Hardware/ Software Interface EXAMPLE FIGURE 2.9 Illustration of the options in the if statement above. The left box corresponds to the then part of the if statement, and the right box corresponds to the else part. f=g+h f = g – h i=j i ≠ j i= =j? Else: Exit: 2.7 Instructions for Making Decisions 107
clipped_hennesy_Page_105_Chunk5462
108 Chapter 2 Instructions: Language of the Computer The first step is to load save[i] into a temporary register. Before we can load save[i] into a temporary register, we need to have its address. Before we can add i to the base of array save to form the address, we must multiply the index i by 4 due to the byte addressing problem. Fortunately, we can use shift left logical, since shifting left by 2 bits multiplies by 22 or 4 (see page 103 in the prior section). We need to add the label Loop to it so that we can branch back to that instruction at the end of the loop: Loop: sll $t1,$s3,2 # Temp reg $t1 = i * 4 To get the address of save[i], we need to add $t1 and the base of save in $s6: add $t1,$t1,$s6 # $t1 = address of save[i] Now we can use that address to load save[i] into a temporary register: lw $t0,0($t1) # Temp reg $t0 = save[i] The next instruction performs the loop test, exiting if save[i] ≠ k: bne $t0,$s5, Exit # go to Exit if save[i] ≠ k The next instruction adds 1 to i: addi $s3,$s3,1 # i = i + 1 The end of the loop branches back to the while test at the top of the loop. We just add the Exit label after it, and we’re done: j Loop # go to Loop Exit: (See the exercises for an optimization of this sequence.) Such sequences of instructions that end in a branch are so fundamental to compil­ing that they are given their own buzzword: a basic block is a sequence of instruc­tions without branches, except possibly at the end, and without branch targets or branch labels, except possibly at the beginning. One of the first early phases of compilation is breaking the program into basic blocks. The test for equality or inequality is probably the most popular test, but some­ times it is useful to see if a variable is less than another variable. For example, a for loop may want to test to see if the index variable is less than 0. Such comparisons are accomplished in MIPS assembly language with an instruction that compares two ANSWER Hardware/ Software Interface basic block A sequence of instructions without branches (except possibly at the end) and without branch t­argets or branch labels (except possibly at the ­beginning).
clipped_hennesy_Page_106_Chunk5463
registers and sets a third register to 1 if the first is less than the second; otherwise, it is set to 0. The MIPS instruction is called set on less than, or slt. For example, slt $t0, $s3, $s4 # $t0 = 1 if $s3 < $s4 means that register $t0 is set to 1 if the value in register $s3 is less than the value in register $s4; otherwise, register $t0 is set to 0. Constant operands are popular in comparisons, so there is an immediate ver­ sion of the set on less than instruction. To test if register $s2 is less than the con­ stant 10, we can just write slti $t0,$s2,10 # $t0 = 1 if $s2 < 10 MIPS compilers use the slt, slti, beq, bne, and the fixed value of 0 (always available by reading register $zero) to create all relative conditions: equal, not equal, less than, less than or equal, greater than, greater than or equal. Heeding von Neumann’s warning about the simplicity of the “equipment,” the MIPS architecture doesn’t include branch on less than because it is too compli­ cated; either it would stretch the clock cycle time or it would take extra clock cycles per instruction. Two faster instructions are more useful. Comparison instructions must deal with the dichotomy between signed and unsigned numbers. Sometimes a bit pattern with a 1 in the most significant bit represents a negative number and, of course, is less than any positive number, which must have a 0 in the most significant bit. With unsigned integers, on the other hand, a 1 in the most significant bit represents a number that is larger than any that begins with a 0. (We’ll soon take advantage of this dual meaning of the most significant bit to reduce the cost of the array bounds checking.) MIPS offers two versions of the set on less than comparison to handle these alternatives. Set on less than (slt) and set on less than immediate (slti) work with signed integers. Unsigned integers are compared using set on less than unsigned (sltu) and set on less than immediate unsigned (sltiu). Hardware/ Software Interface Hardware/ Software Interface 2.7 Instructions for Making Decisions 109
clipped_hennesy_Page_107_Chunk5464
110 Chapter 2 Instructions: Language of the Computer Signed versus Unsigned Comparison Suppose register $s0 has the binary number 1111 1111 1111 1111 1111 1111 1111 1111two and that register $s1 has the binary number 0000 0000 0000 0000 0000 0000 0000 0001two What are the values of registers $t0 and $t1 after these two instructions? slt $t0, $s0, $s1 # signed comparison sltu $t1, $s0, $s1 # unsigned comparison The value in register $s0 represents -1ten if it is an integer and 4,294,967,295ten if it is an unsigned integer. The value in register $s1 repre­sents 1ten in either case. Then register $t0 has the value 1, since -1ten < 1ten, and register $t1 has the value 0, since 4,294,967,295ten > 1ten. Treating signed numbers as if they were unsigned gives us a low cost way of checking if 0 ≤ x < y, which matches the index out-of-bounds check for arrays. The key is that negative integers in two’s complement notation look like large numbers in unsigned notation; that is, the most significant bit is a sign bit in the former notation but a large part of the number in the latter. Thus, an unsigned comparison of x < y also checks if x is negative as well as if x is less than y. Bounds Check Shortcut Use this shortcut to reduce an index-out-of-bounds check: jump to IndexOutOfBounds if $s1 ≥ $t2 or if $s1 is negative. The checking code just uses sltu to do both checks: sltu $t0,$s1,$t2 # $t0=0 if $s1>=length or $s1<0 beq $t0,$zero,IndexOutOfBounds #if bad, goto Error EXAMPLE ANSWER EXAMPLE ANSWER
clipped_hennesy_Page_108_Chunk5465
Case/Switch Statement Most programming languages have a case or switch statement that allows the pro­ grammer to select one of many alternatives depending on a single ­value. The sim­plest way to implement switch is via a sequence of conditional tests, turning the switch statement into a chain of if-then-else statements. Sometimes the alternatives may be more efficiently encoded as a table of addresses of alternative instruction sequences, called a jump address table or jump table, and the program needs only to index into the table and then jump to the appropriate sequence. The jump table is then just an array of words containing addresses that correspond to labels in the code. The program loads the appropri­ate entry from the jump table into a register. It then needs to jump using the address in the register. To support such situations, computers like MIPS include a jump register instruction (jr), meaning an unconditional jump to the address specified in a register. Then it jumps to the proper address using this instruction, which is described in the next section. Although there are many statements for decisions and loops in programming lan­guages like C and Java, the bedrock statement that implements them at the instruction set level is the conditional branch. Elaboration: If you have heard about delayed branches, covered in Chapter 4, don’t worry: the MIPS assembler makes them invisible to the assembly language programmer. I. C has many statements for decisions and loops, while MIPS has few. Which of the following do or do not explain this imbalance? Why? 1. More decision statements make code easier to read and understand. 2. Fewer decision statements simplify the task of the underlying layer that is responsible for execution. 3. More decision statements mean fewer lines of code, which generally reduces coding time. 4. More decision statements mean fewer lines of code, which generally results in the execution of fewer operations. jump address table Also called jump table. A table of ­addresses of alternative instruction sequences. Hardware/ Software Interface Check Yourself 2.7 Instructions for Making Decisions 111
clipped_hennesy_Page_109_Chunk5466
112 Chapter 2 Instructions: Language of the Computer II. Why does C provide two sets of operators for AND (& and &&) and two sets of operators for OR (| and ||), while MIPS doesn’t? 1. Logical operations AND and OR implement & and |, while conditional branches implement && and ||. 2. The previous statement has it backwards: && and || correspond to logical operations, while & and | map to conditional branches. 3. They are redundant and mean the same thing: && and || are simply inher­ited from the programming language B, the predecessor of C. 2.8 Supporting Procedures in Computer Hardware A procedure or function is one tool programmers use to structure pro­grams, both to make them easier to understand and to allow code to be reused. Procedures allow the programmer to concentrate on just one portion of the task at a time; parameters act as an interface between the procedure and the rest of the program and data, since they can pass values and return results. We describe the equivalent to procedures in Java in Section 2.15 on the CD, but Java needs everything from a computer that C needs. You can think of a procedure like a spy who leaves with a secret plan, acquires resources, performs the task, covers his or her tracks, and then returns to the point of origin with the desired result. Nothing else should be perturbed once the mission is complete. Moreover, a spy operates on only a “need to know” basis, so the spy can’t make assumptions about his employer. Similarly, in the execution of a procedure, the program must follow these six steps: 1. Put parameters in a place where the procedure can access them. 2. Transfer control to the procedure. 3. Acquire the storage resources needed for the procedure. 4. Perform the desired task. 5. Put the result value in a place where the calling program can access it. 6. Return control to the point of origin, since a procedure can be called from several points in a program. procedure A stored subroutine that performs a specific task based on the parameters with which it is ­provided.
clipped_hennesy_Page_110_Chunk5467
As mentioned above, registers are the fastest place to hold data in a computer, so we want to use them as much as possible. MIPS software follows the following convention for procedure calling in allocating its 32 registers: ■ ■$a0-$a3: four argument registers in which to pass parameters ■ ■$v0-$v1: two value registers in which to return values ■ ■$ra: one return address register to return to the point of origin In addition to allocating these registers, MIPS assembly language includes an instruction just for the procedures: it jumps to an address and simultaneously saves the address of the following instruction in register $ra. The jump-and-link instruction (jal) is simply written jal ProcedureAddress The link portion of the name means that an address or link is formed that points to the calling site to allow the procedure to return to the proper address. This “link,” stored in register $ra (register 31), is called the return address. The return address is needed because the same procedure could be called from several parts of the program. To support such situations, computers like MIPS use jump register instruc­tion (jr), introduced above to help with case statements, meaning an uncondi­tional jump to the address specified in a register: jr $ra Jump register instruction jumps to the address stored in register $ra—which is just what we want. Thus, the calling program, or caller, puts the parameter val­ues in $a0-$a3 and uses jal X to jump to procedure X (sometimes named the callee). The callee then performs the calculations, places the results in $v0 and $v1, and returns control to the caller using jr $ra. Implicit in the stored-program idea is the need to have a register to hold the address of the current instruction being executed. For historical reasons, this reg­ ister is almost always called the program counter, abbreviated PC in the MIPS architecture, although a more sensible name would have been instruction ­address register. The jal instruction actually saves PC + 4 in register $ra to link to the following instruction to set up the procedure return. jump-and-link instruction An instruction that jumps to an address and simultaneously saves the address of the following instruction in a register ($ra in MIPS). return address A link to the calling site that allows a proce­dure to return to the proper address; in MIPS it is stored in register $ra. caller The program that insti­gates a procedure and ­provides the necessary parameter values. callee A procedure that executes a series of stored ­instructions based on parameters provided by the caller and then returns con­trol to the caller. program counter (PC) The register containing the ­address of the instruction in the pro­ gram being ­executed. 2.8 Supporting Procedures in Computer Hardware 113
clipped_hennesy_Page_111_Chunk5468
114 Chapter 2 Instructions: Language of the Computer Using More Registers Suppose a compiler needs more registers for a procedure than the four argument and two return value registers. Since we must cover our tracks after our mission is complete, any registers needed by the caller must be restored to the values that they contained before the procedure was invoked. This situation is an example in which we need to spill registers to memory, as mentioned in the Hardware/­Software Interface section. The ideal data structure for spilling registers is a stack—a last-in-first-out queue. A stack needs a pointer to the most recently allocated address in the stack to show where the next procedure should place the registers to be spilled or where old register values are found. The stack pointer is adjusted by one word for each register that is saved or restored. MIPS software reserves register 29 for the stack pointer, giving it the obvious name $sp. Stacks are so popular that they have their own buzzwords for transferring data to and from the stack: placing data onto the stack is called a push, and removing data from the stack is called a pop. By historical precedent, stacks “grow” from higher addresses to lower addresses. This convention means that you push values onto the stack by sub­tracting from the stack ­pointer. Adding to the stack pointer shrinks the stack, thereby popping values off the stack. Compiling a C Procedure That Doesn’t Call Another Procedure Let’s turn the example on page 79 from Section 2.2 into a C procedure: int leaf_example (int g, int h, int i, int j) { int f; f = (g + h) – (i + j); return f; } What is the compiled MIPS assembly code? The parameter variables g, h, i, and j correspond to the argument registers $a0, $a1, $a2, and $a3, and f corresponds to $s0. The compiled program starts with the label of the procedure: leaf_example: stack A data structure for spill­ing registers organized as a last-in- first-out queue. stack pointer A value denoting the most recently allocated address in a stack that shows where registers should be spilled or where old register values can be found. In MIPS, it is register $sp. push Add element to stack. pop Remove element from stack. EXAMPLE ANSWER
clipped_hennesy_Page_112_Chunk5469
The next step is to save the registers used by the procedure. The C assignment statement in the procedure body is identical to the example on page 79, which uses two temporary registers. Thus, we need to save three ­registers: $s0, $t0, and $t1. We “push” the old values onto the stack by creating space for three words (12 bytes) on the stack and then store them: addi $sp, $sp, –12 # adjust stack to make room for 3 items sw $t1, 8($sp) # save register $t1 for use afterwards sw $t0, 4($sp) # save register $t0 for use afterwards sw $s0, 0($sp) # save register $s0 for use afterwards Figure 2.10 shows the stack before, during, and after the procedure call. The next three statements correspond to the body of the procedure, which follows the example on page 79: add $t0,$a0,$a1 # register $t0 contains g + h add $t1,$a2,$a3 # register $t1 contains i + j sub $s0, $t0, $t1 # f = $t0 – $t1, which is (g + h)–(i + j) To return the value of f, we copy it into a return value register: add $v0,$s0,$zero # returns f ($v0 = $s0 + 0) Before returning, we restore the three old values of the registers we saved by “popping” them from the stack: lw $s0, 0($sp) # restore register $s0 for caller lw $t0, 4($sp) # restore register $t0 for caller lw $t1, 8($sp) # restore register $t1 for caller addi $sp,$sp,12 # adjust stack to delete 3 items The procedure ends with a jump register using the return address: jr $ra # jump back to calling routine In the previous example, we used temporary registers and assumed their old values must be saved and restored. To avoid saving and restoring a register whose value is never used, which might happen with a temporary register, MIPS software sepa­rates 18 of the registers into two groups: ■ ■$t0-$t9:ten temporary registers that are not preserved by the callee (called procedure) on a procedure call ■ ■$s0-$s7:eight saved registers that must be preserved on a procedure call (if used, the callee saves and restores them) This simple convention reduces register spilling. In the example above, since the caller does not expect registers $t0 and $t1 to be preserved across a procedure call, 2.8 Supporting Procedures in Computer Hardware 115
clipped_hennesy_Page_113_Chunk5470
116 Chapter 2 Instructions: Language of the Computer we can drop two stores and two loads from the code. We still must save and restore $s0, since the callee must assume that the caller needs its value. FIGURE 2.10 The values of the stack pointer and the stack (a) before, (b) during, and (c) after the procedure call. The stack pointer always points to the “top” of the stack, or the last word in the stack in this drawing. High address Low address Contents of register $t1 Contents of register $t0 Contents of register $s0 $sp $sp $sp a. b. c. Nested Procedures Procedures that do not call others are called leaf procedures. Life would be simple if all procedures were leaf procedures, but they aren’t. Just as a spy might employ other spies as part of a mission, who in turn might use even more spies, so do procedures invoke other procedures. Moreover, recursive procedures even invoke “clones” of themselves. Just as we need to be careful when using registers in procedures, more care must also be taken when invok­ing nonleaf procedures. For example, suppose that the main program calls procedure A with an argument of 3, by placing the value 3 into register $a0 and then using jal A. Then suppose that procedure A calls procedure B via jal B with an argument of 7, also placed in $a0. Since A hasn’t finished its task yet, there is a conflict over the use of register $a0. Similarly, there is a conflict over the return address in register $ra, since it now has the return address for B. Unless we take steps to prevent the problem, this conflict will eliminate procedure A’s ability to return to its caller. One solution is to push all the other registers that must be preserved onto the stack, just as we did with the saved registers. The caller pushes any argument registers ($a0-$a3) or temporary registers ($t0-$t9) that are needed after the call. The callee pushes the return address register $ra and any saved registers ($s0-$s7) used by the callee. The stack pointer $sp is adjusted to account for the num­ber of registers placed on the stack. Upon the return, the registers are restored from memory and the stack pointer is readjusted.
clipped_hennesy_Page_114_Chunk5471
Compiling a Recursive C Procedure, Showing Nested Procedure ­Linking Let’s tackle a recursive procedure that calculates factorial: int fact (int n) { if (n < 1) return (1); else return (n * fact(n – 1)); } What is the MIPS assembly code? The parameter variable n corresponds to the argument register $a0. The compiled program starts with the label of the procedure and then saves two registers on the stack, the return address and $a0: fact: addi $sp, $sp, –8 # adjust stack for 2 items sw $ra, 4($sp) # save the return address sw $a0, 0($sp) # save the argument n The first time fact is called, sw saves an address in the program that called fact. The next two instructions test whether n is less than 1, going to L1 if n ≥ 1. slti $t0,$a0,1 # test for n < 1 beq $t0,$zero,L1 # if n >= 1, go to L1 If n is less than 1, fact returns 1 by putting 1 into a value register: it adds 1 to 0 and places that sum in $v0. It then pops the two saved values off the stack and jumps to the return address: addi $v0,$zero,1 # return 1 addi $sp,$sp,8 # pop 2 items off stack jr $ra # return to caller Before popping two items off the stack, we could have loaded $a0 and $ra. Since $a0 and $ra don’t change when n is less than 1, we skip those instructions. If n is not less than 1, the argument n is decremented and then fact is called again with the decremented value: L1: addi $a0,$a0,–1 # n >= 1: argument gets (n – 1) jal fact # call fact with (n – 1) EXAMPLE ANSWER 2.8 Supporting Procedures in Computer Hardware 117
clipped_hennesy_Page_115_Chunk5472
118 Chapter 2 Instructions: Language of the Computer The next instruction is where fact returns. Now the old return address and old argument are restored, along with the stack pointer: lw $a0, 0($sp) # return from jal: restore argument n lw $ra, 4($sp) # restore the return address addi $sp, $sp, 8 # adjust stack pointer to pop 2 items Next, the value register $v0 gets the product of old argument $a0 and the current value of the value register. We assume a multiply instruction is avail­ able, even though it is not covered until Chapter 3: mul $v0,$a0,$v0 # return n * fact (n – 1) Finally, fact jumps again to the return address: jr $ra # return to the caller A C variable is generally a location in storage, and its interpretation depends both on its type and storage class. Examples include integers and characters (see Section 2.9). C has two storage classes: automatic and static. Automatic variables are local to a procedure and are discarded when the procedure exits. Static variables exist across exits from and entries to procedures. C variables declared outside all procedures are considered static, as are any variables de­clared using the keyword static. The rest are automatic. To simplify access to static data, MIPS software reserves another reg­ ister, called the global pointer, or $gp. Figure 2.11 summarizes what is preserved across a procedure call. Note that sev­ eral schemes preserve the stack, guaranteeing that the caller will get the same data back on a load from the stack as it stored onto the stack. The stack above $sp is pre­served simply by making sure the callee does not write above $sp; $sp is itself pre­served by the callee adding exactly the same amount that was subtracted from it; and the other registers are preserved by saving them on the stack (if they are used) and restoring them from there. Hardware/ Software Interface global pointer The register that is reserved to point to the static area. FIGURE 2.11 What is and what is not preserved across a procedure call. If the software relies on the frame pointer register or on the global pointer register, discussed in the following subsec­tions, they are also preserved. Preserved Not preserved Saved registers: $s0–$s7 Temporary registers: $t0–$t9 Stack pointer register: $sp Argument registers: $a0–$a3 Return address register: $ra Return value registers: $v0–$v1 Stack above the stack pointer Stack below the stack pointer
clipped_hennesy_Page_116_Chunk5473
Allocating Space for New Data on the Stack The final complexity is that the stack is also used to store variables that are local to the procedure but do not fit in registers, such as local arrays or structures. The segment of the stack containing a procedure’s saved registers and local variables is called a procedure frame or activation record. Figure 2.12 shows the state of the stack before, during, and after the procedure call. Some MIPS software uses a frame pointer ($fp) to point to the first word of the frame of a procedure. A stack pointer might change during the procedure, and so references to a local variable in memory might have different offsets depending on where they are in the procedure, making the procedure harder to understand. Alternatively, a frame pointer offers a stable base register within a procedure for local memory-references. Note that an activation record appears on the stack whether or not an explicit frame pointer is used. We’ve been avoiding using $fp by avoiding changes to $sp within a procedure: in our examples, the stack is adjusted only on entry and exit of the procedure. procedure frame Also called activation record. The ­segment of the stack containing a proce­dure’s saved registers and local variables. frame pointer A value denot­ing the location of the saved registers and local variables for a given procedure. FIGURE 2.12 Illustration of the stack allocation (a) before, (b) during, and (c) after the procedure call. The frame pointer ($fp) points to the first word of the frame, often a saved argument register, and the stack pointer ($sp) points to the top of the stack. The stack is adjusted to make room for all the saved registers and any memory-resident local variables. Since the stack pointer may change during pro­gram execution, it’s easier for programmers to reference variables via the stable frame pointer, although it could be done just with the stack pointer and a little address arithmetic. If there are no local variables on the stack within a procedure, the compiler will save time by not setting and restoring the frame pointer. When a frame pointer is used, it is initialized using the address in $sp on a call, and $sp is restored using $fp. This information is also found in Column 4 of the MIPS Reference Data Card at the front of this book. High address Low address a. b. c. Saved argument registers (if any) $sp $sp $sp $fp $fp $fp Saved return address Saved saved registers (if any) Local arrays and structures (if any) 2.8 Supporting Procedures in Computer Hardware 119
clipped_hennesy_Page_117_Chunk5474
120 Chapter 2 Instructions: Language of the Computer Allocating Space for New Data on the Heap In addition to automatic variables that are local to procedures, C programmers need space in memory for static variables and for dynamic data structures. ­Figure 2.13 shows the MIPS convention for allocation of memory. The stack starts in the high end of memory and grows down. The first part of the low end of memory is reserved, followed by the home of the MIPS machine code, traditionally called the text segment. Above the code is the static data segment, which is the place for con- stants and other static variables. Although arrays tend to be a fixed length and thus are a good match to the static data segment, data structures like linked lists tend to grow and shrink during their lifetimes. The segment for such data structures is tra- ditionally called the heap, and it is placed next in memory. Note that this allocation allows the stack and heap to grow toward each other, thereby allowing the efficient use of memory as the two seg­ments wax and wane. text segment The segment of a UNIX object file that ­contains the machine language code for rou­tines in the source file. FIGURE 2.13 The MIPS memory allocation for program and data. These addresses are only a software convention, and not part of the MIPS architecture. The stack pointer is initialized to 7fff fffchex and grows down toward the data segment. At the other end, the program code (“text”) starts at 0040 0000hex. The static data starts at 1000 0000hex. Dynamic data, allocated by malloc in C and by new in Java, is next. It grows up toward the stack in an area called the heap. The global pointer, $gp, is set to an address to make it easy to access data. It is initialized to 1000 8000hex so that it can access from 1000 0000hex to 1000 ffffhex using the positive and negative 16-bit offsets from $gp. This information is also found in Column 4 of the MIPS Reference Data Card at the front of this book. Stack Dynamic data Static data Text Reserved $sp 7fff fffchex $gp 1000 8000hex 1000 0000hex pc 0040 0000hex 0 C allocates and frees space on the heap with explicit functions. malloc() ­allo­ cates space on the heap and returns a pointer to it, and free() releases space on the heap to which the pointer points. Memory allocation is controlled by programs in C, and it is the source of many common and difficult bugs. Forgetting to free space leads to a “memory leak,” which eventually uses up so much memory that the oper­ ating system may crash. Freeing space too early leads to “dangling pointers,” which can cause pointers to point to things that the program never intended. Java uses automatic memory allocation and garbage collection just to avoid such bugs.
clipped_hennesy_Page_118_Chunk5475
Figure 2.14 summarizes the register conventions for the MIPS assembly l­anguage. Name Register number Usage Preserved on call? $zero 0 The constant value 0 n.a. $v0–$v1 2–3 Values for results and expression evaluation no $a0–$a3 4–7 Arguments no $t0–$t7 8–15 Temporaries no $s0–$s7 16–23 Saved yes $t8–$t9 24–25 More temporaries no $gp 28 Global pointer yes $sp 29 Stack pointer yes $fp 30 Frame pointer yes $ra 31 Return address yes FIGURE 2.14 MIPS register conventions. Register 1, called $at, is reserved for the assembler (see Section 2.12), and registers 26-27, called $k0-$k1, are reserved for the operating system. This information is also found in Column 2 of the MIPS Reference Data Card at the front of this book. Elaboration: What if there are more than four parameters? The MIPS convention is to place the extra parameters on the stack just above the frame pointer. The procedure then expects the first four parameters to be in registers $a0 through $a3 and the rest in memory, addressable via the frame pointer. As mentioned in the caption of Figure 2.12, the frame pointer is convenient because all ref­erences to variables in the stack within a procedure will have the same offset. The frame pointer is not necessary, however. The GNU MIPS C compiler uses a frame pointer, but the C compiler from MIPS does not; it treats register 30 as another save register ($s8). Elaboration: Some recursive procedures can be implemented iteratively without using recursion. Iteration can significantly improve performance by removing the overhead associ­ ated with procedure calls. For example, consider a procedure used to accumulate a sum: int sum (int n, int acc) { if (n > 0) return sum(n – 1, acc + n); else return acc; } Consider the procedure call sum(3,0). This will result in recursive calls to sum(2,3), sum(1,5), and sum(0,6), and then the result 6 will be returned four times. This recursive call of sum is referred to as a tail call, and this example use of tail recursion can be imple­mented very efficiently (assume $a0 = n and $a1 = acc): sum: slti $t0, $a0, 1 # test if n <= 0 bne $t0, $zero, sum_exit # go to sum_exit if n <= 0 add$a1, $a1, $a0 # add n to acc 2.8 Supporting Procedures in Computer Hardware 121
clipped_hennesy_Page_119_Chunk5476
122 Chapter 2 Instructions: Language of the Computer addi$a0, $a0, –1 # subtract 1 from n j sum # go to sum sum_exit: add$v0, $a1, $zero # return value acc jr $ra # return to caller Which of the following statements about C and Java are generally true? 1. C programmers manage data explicitly, while it’s automatic in Java. 2. C leads to more pointer bugs and memory leak bugs than does Java. 2.9 Communicating with People Computers were invented to crunch numbers, but as soon as they became com­ mercially viable they were used to process text. Most computers today offer 8-bit bytes to represent characters, with the American Standard Code for Informa­ tion Interchange (ASCII) being the representation that nearly everyone follows. Figure 2.15 summarizes ASCII. ASCII value Char- acter ASCII value Char- acter ASCII value Char- acter ASCII value Char- acter ASCII value Char- acter ASCII value Char- acter 32 space 48 0 64 @ 80 P 096 ` 112 p 33 ! 49 1 65 A 81 Q 097 a 113 q 34 " 50 2 66 B 82 R 098 b 114 r 35 # 51 3 67 C 83 S 099 c 115 s 36 $ 52 4 68 D 84 T 100 d 116 t 37 % 53 5 69 E 85 U 101 e 117 u 38 & 54 6 70 F 86 V 102 f 118 v 39 ' 55 7 71 G 87 W 103 g 119 w 40 ( 56 8 72 H 88 X 104 h 120 x 41 ) 57 9 73 I 89 Y 105 i 121 y 42 * 58 : 74 J 90 Z 106 j 122 z 43 + 59 ; 75 K 91 [ 107 k 123 { 44 , 60 < 76 L 92 \ 108 l 124 | 45 - 61 = 77 M 93 ] 109 m 125 } 46 . 62 > 78 N 94 ^ 110 n 126 ~ 47 / 63 ? 79 O 95 _ 111 o 127 DEL FIGURE 2.15 ASCII representation of characters. Note that upper- and lowercase letters differ by exactly 32; this observation can lead to short­cuts in checking or changing upper- and lowercase. Values not shown include formatting characters. For example, 8 represents a backspace, 9 represents a tab character, and 13 a carriage return. Another useful value is 0 for null, the value the programming language C uses to mark the end of a string. This information is also found in Column 3 of the MIPS Reference Data Card at the front of this book. Check Yourself !(@ | = > (wow open tab at bar is great) Fourth line of the keyboard poem “Hatless Atlas,” 1991 (some give names to ASCII characters: “!” is “wow,” “(” is open, “|” is bar, and so on).
clipped_hennesy_Page_120_Chunk5477
Base 2 is not natural to human beings; we have 10 fingers and so find base 10 natural. Why didn’t computers use decimal? In fact, the first commercial computer did offer decimal arithmetic. The problem was that the computer still used on and off signals, so a decimal digit was simply represented by several binary digits. Decimal proved so inefficient that subsequent computers reverted to all binary, con­verting to base 10 only for the relatively infrequent input/output events. ASCII versus Binary Numbers We could represent numbers as strings of ASCII digits instead of as integers. How much does storage increase if the number 1 billion is represented in ASCII versus a 32-bit integer? One billion is 1,000,000,000, so it would take 10 ASCII digits, each 8 bits long. Thus the storage expansion would be (10 × 8)/32 or 2.5. In addition to the expansion in storage, the hardware to add, subtract, multiply, and divide such decimal numbers is difficult. Such difficulties explain why computing profes­ sionals are raised to believe that binary is natural and that the occasional dec­ imal computer is bizarre. A series of instructions can extract a byte from a word, so load word and store word are sufficient for transferring bytes as well as words. Because of the popularity of text in some programs, however, MIPS provides instructions to move bytes. Load byte (lb) loads a byte from memory, placing it in the rightmost 8 bits of a register. Store byte (sb) takes a byte from the rightmost 8 bits of a register and writes it to memory. Thus, we copy a byte with the sequence lb $t0,0($sp) # Read byte from source sb $t0,0($gp) # Write byte to destination Hardware/ Software Interface EXAMPLE ANSWER 2.9 Communicating with People 123
clipped_hennesy_Page_121_Chunk5478
124 Chapter 2 Instructions: Language of the Computer Signed versus unsigned applies to loads as well as to arithmetic. The function of a signed load is to copy the sign repeatedly to fill the rest of the register—called sign extension—but its purpose is to place a correct representation of the number within that register. Unsigned loads simply fill with 0s to the left of the data, since the number represented by the bit pattern is unsigned. When loading a 32-bit word into a 32-bit register, the point is moot; signed and unsigned loads are identical. MIPS does offer two flavors of byte loads: load byte (lb) treats the byte as a signed number and thus sign-extends to fill the 24 left­ most bits of the register, while load byte unsigned (lbu) works with unsigned inte­gers. Since C programs almost always use bytes to represent characters rather than consider bytes as very short signed integers, lbu is used practically exclusively for byte loads. Characters are normally combined into strings, which have a variable number of characters. There are three choices for representing a string: (1) the first posi­tion of the string is reserved to give the length of a string, (2) an accompanying variable has the length of the string (as in a structure), or (3) the last position of a string is indicated by a character used to mark the end of a string. C uses the third choice, terminating a string with a byte whose value is 0 (named null in ASCII). Thus, the string “Cal” is represented in C by the following 4 bytes, shown as deci­mal numbers: 67, 97, 108, 0. (As we shall see, Java uses the first option.) Compiling a String Copy Procedure, Showing How to Use C Strings The procedure strcpy copies string y to string x using the null byte ­termination convention of C: void strcpy (char x[], char y[]) { int i; i = 0; while ((x[i] = y[i]) != ‘\0’) /* copy & test byte */ i += 1; } What is the MIPS assembly code? Hardware/ Software Interface EXAMPLE
clipped_hennesy_Page_122_Chunk5479
Below is the basic MIPS assembly code segment. Assume that base addresses for arrays x and y are found in $a0 and $a1, while i is in $s0. strcpy adjusts the stack pointer and then saves the saved register $s0 on the stack: strcpy: addi $sp,$sp,–4 # adjust stack for 1 more item sw $s0, 0($sp) # save $s0 To initialize i to 0, the next instruction sets $s0 to 0 by adding 0 to 0 and plac­ ing that sum in $s0: add $s0,$zero,$zero # i = 0 + 0 This is the beginning of the loop. The address of y[i] is first formed by add­ ing i to y[]: L1: add $t1,$s0,$a1 # address of y[i] in $t1 Note that we don’t have to multiply i by 4 since y is an array of bytes and not of words, as in prior examples. To load the character in y[i], we use load byte unsigned, which puts the character into $t2: lbu $t2, 0($t1) # $t2 = y[i] A similar address calculation puts the address of x[i] in $t3, and then the character in $t2 is stored at that address. add $t3,$s0,$a0 # address of x[i] in $t3 sb $t2, 0($t3) # x[i] = y[i] Next, we exit the loop if the character was 0. That is, we exit if it is the last character of the string: beq $t2,$zero,L2 # if y[i] == 0, go to L2 If not, we increment i and loop back: addi $s0, $s0,1 # i = i + 1 j L1 # go to L1 ANSWER 2.9 Communicating with People 125
clipped_hennesy_Page_123_Chunk5480
126 Chapter 2 Instructions: Language of the Computer If we don’t loop back, it was the last character of the string; we restore $s0 and the stack pointer, and then return. L2: lw $s0, 0($sp) # y[i] == 0: end of string. Re­ store old $s0 addi $sp,$sp,4 # pop 1 word off stack jr $ra # return String copies usually use pointers instead of arrays in C to avoid the opera­tions on i in the code above. See Section 2.14 for an explanation of arrays versus pointers. Since the procedure strcpy above is a leaf procedure, the compiler could allo­ cate i to a temporary register and avoid saving and restoring $s0. Hence, instead of thinking of the $t registers as being just for temporaries, we can think of them as registers that the callee should use whenever convenient. When a compiler finds a leaf procedure, it exhausts all temporary registers before using registers it must save. Characters and Strings in Java Unicode is a universal encoding of the alphabets of most human languages. Figure 2.16 is a list of Unicode alphabets; there are almost as many alphabets in Unicode as there are useful symbols in ASCII. To be more inclusive, Java uses Unicode for characters. By default, it uses 16 bits to represent a character. The MIPS instruction set has explicit instructions to load and store such 16-bit quantities, called halfwords. Load half (lh) loads a halfword from memory, placing it in the rightmost 16 bits of a register. Like load byte, load half (lh) treats the halfword as a signed number and thus sign-extends to fill the 16 leftmost bits of the register, while load halfword unsigned (lhu) works with unsigned integers. Thus, lhu is the more popular of the two. Store half (sh) takes a halfword from the rightmost 16 bits of a register and writes it to memory. We copy a halfword with the sequence lhu $t0,0($sp) # Read halfword (16 bits) from source sh $t0,0($gp) # Write halfword (16 bits) to destination Strings are a standard Java class with special built-in support and predefined methods for concatenation, comparison, and conversion. Unlike C, Java includes a word that gives the length of the string, similar to Java arrays. Elaboration: MIPS software tries to keep the stack aligned to word addresses, allowing the program to always use lw and sw (which must be aligned) to access the stack. This convention means that a char variable allocated on the stack occupies 4 bytes, even though it needs less. However, a C string variable or an array of bytes will pack 4 bytes per word, and a Java string vari­able or array of shorts packs 2 halfwords per word.
clipped_hennesy_Page_124_Chunk5481
Latin Malayalam Tagbanwa General Punctuation Greek Sinhala Khmer Spacing Modifier Letters Cyrillic Thai Mongolian Currency Symbols Armenian Lao Limbu Combining Diacritical Marks Hebrew Tibetan Tai Le Combining Marks for Symbols Arabic Myanmar Kangxi Radicals Superscripts and Subscripts Syriac Georgian Hiragana Number Forms Thaana Hangul Jamo Katakana Mathematical Operators Devanagari Ethiopic Bopomofo Mathematical Alphanumeric Symbols Bengali Cherokee Kanbun Braille Patterns Gurmukhi Unified Canadian Aboriginal Syllabic Shavian Optical Character Recognition Gujarati Ogham Osmanya Byzantine Musical Symbols Oriya Runic Cypriot Syllabary Musical Symbols Tamil Tagalog Tai Xuan Jing Symbols Arrows Telugu Hanunoo Yijing Hexagram Symbols Box Drawing Kannada Buhid Aegean Numbers Geometric Shapes FIGURE 2.16 Example alphabets in Unicode. Unicode version 4.0 has more than 160 “blocks,” which is their name for a collection of symbols. Each block is a multiple of 16. For example, Greek starts at 0370hex, and Cyrillic at 0400hex. The first three columns show 48 blocks that correspond to human languages in roughly Unicode numerical order. The last column has 16 blocks that are multilingual and are not in order. A 16-bit encoding, called UTF-16, is the default. A variable-length encoding, called UTF-8, keeps the ASCII subset as eight bits and uses 16-32 bits for the other characters. UTF-32 uses 32 bits per character. To learn more, see www.unicode.org. I. Which of the following statements about characters and strings in C and Java are true? 1. A string in C takes about half the memory as the same string in Java. 2. Strings are just an informal name for single-dimension arrays of characters in C and Java. 3. Strings in C and Java use null (0) to mark the end of a string. 4. Operations on strings, like length, are faster in C than in Java. II. Which type of variable that can contain 1,000,000,000ten takes the most mem­ory space? 1. int in C 2. string in C 3. string in Java Check Yourself 2.9 Communicating with People 127
clipped_hennesy_Page_125_Chunk5482
128 Chapter 2 Instructions: Language of the Computer 2.10 MIPS Addressing for 32-Bit Immediates and Addresses Although keeping all MIPS instructions 32 bits long simplifies the hardware, there are times where it would be convenient to have a 32-bit constant or 32-bit address. This section starts with the general solution for large constants, and then shows the optimizations for instruction addresses used in branches and jumps. 32-Bit Immediate Operands Although constants are frequently short and fit into the 16-bit field, sometimes they are bigger. The MIPS instruction set includes the instruction load upper immediate (lui) specifically to set the upper 16 bits of a constant in a register, allowing a subsequent instruction to specify the lower 16 bits of the constant. Fig­ure 2.17 shows the operation of lui. Loading a 32-Bit Constant What is the MIPS assembly code to load this 32-bit constant into register $s0? 0000 0000 0011 1101 0000 1001 0000 0000 First, we would load the upper 16 bits, which is 61 in decimal, using lui: lui $s0, 61 # 61 decimal = 0000 0000 0011 1101 binary The value of register $s0 afterward is 0000 0000 0011 1101 0000 0000 0000 0000 The next step is to insert the lower 16 bits, whose decimal value is 2304: ori $s0, $s0, 2304 # 2304 decimal = 0000 1001 0000 0000 The final value in register $s0 is the desired value: 0000 0000 0011 1101 0000 1001 0000 0000 EXAMPLE ANSWER
clipped_hennesy_Page_126_Chunk5483
The machine language version of lui $t0, 255 # $t0 is register 8: 001111 00000 01000 0000 0000 1111 1111 Contents of register $t0 after executing lui $t0, 255: 0000 0000 1111 1111 0000 0000 0000 0000 FIGURE 2.17 The effect of the lui instruction. The instruction lui transfers the 16-bit immediate constant field value into the leftmost 16 bits of the register, filling the lower 16 bits with 0s. Either the compiler or the assembler must break large constants into pieces and then reassemble them into a register. As you might expect, the immediate field’s size restriction may be a problem for memory addresses in loads and stores as well as for constants in immediate instructions. If this job falls to the assembler, as it does for MIPS software, then the assembler must have a temporary register avail­ able in which to create the long values. This is a reason for the register $at, which is reserved for the assembler. Hence, the symbolic representation of the MIPS machine language is no longer limited by the hardware, but by whatever the creator of an assembler chooses to include (see Section 2.12). We stick close to the hardware to explain the architecture of the computer, noting when we use the enhanced language of the assembler that is not found in the processor. Elaboration: Creating 32-bit constants needs care. The instruction addi copies the left­most bit of the 16-bit immediate field of the instruction into the upper 16 bits of a word. Logical or immediate from Section 2.6 loads 0s into the upper 16 bits and hence is used by the assem­bler in conjunction with lui to create 32-bit constants. Addressing in Branches and Jumps The MIPS jump instructions have the simplest addressing. They use the final MIPS instruction format, called the J-type, which consists of 6 bits for the opera­tion field and the rest of the bits for the address field. Thus, j 10000 # go to location 10000 could be assembled into this format (it’s actually a bit more complicated, as we will see): Hardware/ Software Interface 2.10 MIPS Addressing for 32-Bit Immediates and Addresses 129
clipped_hennesy_Page_127_Chunk5484
130 Chapter 2 Instructions: Language of the Computer 2 10000 6 bits 26 bits where the value of the jump opcode is 2 and the jump address is 10000. Unlike the jump instruction, the conditional branch instruction must specify two operands in addition to the branch address. Thus, bne $s0,$s1,Exit # go to Exit if $s0 ≠ $s1 is assembled into this instruction, leaving only 16 bits for the branch address: 5 16 17 Exit 6 bits 5 bits 5 bits 16 bits If addresses of the program had to fit in this 16-bit field, it would mean that no program could be bigger than 216, which is far too small to be a realistic ­option today. An alternative would be to specify a register that would always be added to the branch address, so that a branch instruction would calculate the following: Program counter = Register + Branch address This sum allows the program to be as large as 232 and still be able to use condi­tional branches, solving the branch address size problem. Then the question is, which register? The answer comes from seeing how conditional branches are used. Conditional branches are found in loops and in if statements, so they tend to branch to a nearby instruction. For example, about half of all conditional branches in SPEC benchmarks go to locations less than 16 instructions away. Since the program counter (PC) contains the address of the current instruction, we can branch within ± 215 words of the current instruction if we use the PC as the register to be added to the address. Almost all loops and if statements are much smaller than 216 words, so the PC is the ideal choice. This form of branch addressing is called PC-relative addressing. As we shall see in Chapter 4, it is convenient for the hardware to increment the PC early to point to the next instruction. Hence, the MIPS address is actually relative to the address of the following instruction (PC + 4) as opposed to the current instruction (PC). Like most recent computers, MIPS uses PC-relative addressing for all condi­ tional branches, because the destination of these instructions is likely to be close to the branch. On the other hand, jump-and-link instructions invoke procedures that have no reason to be near the call, so they normally use other forms of addressing. Hence, the MIPS architecture offers long addresses for procedure calls by using the J-type format for both jump and jump-and-link instructions. Since all MIPS instructions are 4 bytes long, MIPS stretches the distance of the branch by having PC-relative addressing refer to the number of words to the next instruction instead of the number of bytes. Thus, the 16-bit field can branch four PC-relative addressing An addressing regime in which the address is the sum of the pro­gram counter (PC) and a con­ stant in the instruction.
clipped_hennesy_Page_128_Chunk5485
times as far by interpreting the field as a relative word address rather than as a rel­ative byte address. Similarly, the 26-bit field in jump instructions is also a word address, meaning that it represents a 28-bit byte address. Elaboration: Since the PC is 32 bits, 4 bits must come from somewhere else for jumps. The MIPS jump instruction replaces only the lower 28 bits of the PC, leaving the upper 4 bits of the PC unchanged. The loader and linker (Section 2.12) must be careful to avoid placing a program across an address boundary of 256 MB (64 million instructions); otherwise, a jump must be replaced by a jump register instruction preceded by other instructions to load the full 32-bit address into a register. Showing Branch Offset in Machine Language The while loop on page 107–108 was compiled into this MIPS assembler code: Loop:sll $t1,$s3,2 # Temp reg $t1 = 4 * i add $t1,$t1,$s6 # $t1 = address of save[i] lw $t0,0($t1) # Temp reg $t0 = save[i] bne $t0,$s5, Exit # go to Exit if save[i] ≠ k addi $s3,$s3,1 # i = i + 1 j Loop # go to Loop Exit: If we assume we place the loop starting at location 80000 in memory, what is the MIPS machine code for this loop? The assembled instructions and their addresses are: EXAMPLE ANSWER 80000 0 0 19 9 2 0 80004 0 9 22 9 0 32 80008 35 9 8 0 80012 5 8 21 2 80016 8 19 19 1 80020 2 20000 80024 . . . 2.10 MIPS Addressing for 32-Bit Immediates and Addresses 131
clipped_hennesy_Page_129_Chunk5486
132 Chapter 2 Instructions: Language of the Computer Remember that MIPS instructions have byte addresses, so addresses of se­quential words differ by 4, the number of bytes in a word. The bne instruc­ tion on the fourth line adds 2 words or 8 bytes to the address of the following instruction (80016), specifying the branch destination relative to that follow­ing instruction (8 + 80016) instead of relative to the branch instruction (12 + 80012) or using the full destination address (80024). The jump instruction on the last line does use the full address (20000 × 4 = 80000), corresponding to the label Loop. Most conditional branches are to a nearby location, but occasionally they branch far away, farther than can be represented in the 16 bits of the conditional branch instruction. The assembler comes to the rescue just as it did with large addresses or constants: it inserts an unconditional jump to the branch target, and inverts the condition so that the branch decides whether to skip the jump. Branching Far Away Given a branch on register $s0 being equal to register $s1, beq $s0, $s1, L1 replace it by a pair of instructions that offers a much greater branching distance. These instructions replace the short-address conditional branch: bne $s0, $s1, L2 j L1 L2: MIPS Addressing Mode Summary Multiple forms of addressing are generically called addressing modes. Figure 2.18 shows how operands are identified for each addressing mode. The MIPS address­ ing modes are the following: 1. Immediate addressing, where the operand is a constant within the instruc­ tion itself 2. Register addressing, where the operand is a register Hardware/ Software Interface EXAMPLE ANSWER addressing mode One of sev­eral addressing regimes ­delimited by their varied use of operands and/or ­addresses.
clipped_hennesy_Page_130_Chunk5487
3. Base or displacement addressing, where the operand is at the memory loca­ tion whose address is the sum of a register and a constant in the instruction 4. PC-relative addressing, where the branch address is the sum of the PC and a con­stant in the instruction 5. Pseudodirect addressing, where the jump address is the 26 bits of the instruc­ tion concatenated with the upper bits of the PC FIGURE 2.18 Illustration of the five MIPS addressing modes. The operands are shaded in color. The operand of mode 3 is in memory, whereas the operand for mode 2 is a register. Note that versions of load and store access bytes, halfwords, or words. For mode 1, the operand is 16 bits of the instruction itself. Modes 4 and 5 address instructions in memory, with mode 4 adding a 16-bit address shifted left 2 bits to the PC and mode 5 concatenating a 26-bit address shifted left 2 bits with the 4 upper bits of the PC. 1. Immediate addressing 2. Register addressing 3. Base addressing 4. PC-relative addressing 5. Pseudodirect addressing Immediate op rs rt op rs rt . . . funct rd Register Registers op rs rt Address Word Memory + Register Halfword Byte op rs rt Address Word Memory + PC op Word Memory PC Address 2.10 MIPS Addressing for 32-Bit Immediates and Addresses 133
clipped_hennesy_Page_131_Chunk5488
134 Chapter 2 Instructions: Language of the Computer Although we show MIPS as having 32-bit addresses, nearly all microprocessors (including MIPS) have 64-bit address extensions (see Appendix E). These exten­ sions were in response to the needs of software for larger programs. The process of instruction set extension allows architectures to expand in such a way that is able to move software compatibly upward to the next generation of architecture. Note that a single operation can use more than one addressing mode. Add, for example, uses both immediate (addi) and register (add) addressing. Decoding Machine Language Sometimes you are forced to reverse-engineer machine language to create the origi­ nal assembly language. One example is when looking at “core dump.” Figure 2.19 shows the MIPS encoding of the fields for the MIPS machine language. This figure helps when translating by hand between assembly language and machine language. Decoding Machine Code What is the assembly language statement corresponding to this machine instruction? 00af8020hex The first step in converting hexadecimal to binary is to find the op fields: (Bits: 31 28 26 5 2 0) 0000 0000 1010 1111 1000 0000 0010 0000 We look at the op field to determine the operation. Referring to Figure 2.19, when bits 31-29 are 000 and bits 28-26 are 000, it is an ­R-format instruction. Let’s reformat the binary instruction into R-format fields, listed in Figure 2.20: op rs rt rd shamt funct 000000 00101 01111 10000 00000 100000 The bottom portion of Figure 2.19 determines the operation of an R-format instruction. In this case, bits 5-3 are 100 and bits 2-0 are 000, which means this binary pattern represents an add instruction. We decode the rest of the instruction by looking at the field values. The decimal values are 5 for the rs field, 15 for rt, and 16 for rd (shamt is unused). Figure 2.14 shows that these numbers represent registers $a1, $t7, and $s0. Now we can reveal the assembly instruction: add $s0,$a1,$t7 EXAMPLE ANSWER Hardware/ Software Interface
clipped_hennesy_Page_132_Chunk5489
op(31:26) 28–26 31–29 0(000) 1(001) 2(010) 3(011) 4(100) 5(101) 6(110) 7(111) 0(000) R­format Bltz/gez jump jump & link branch eq branch ne blez bgtz 1(001) add immediate addiu set less than imm. set less than imm. unsigned andi ori xori load upper immediate 2(010) TLB FlPt 3(011) 4(100) load byte load half lwl load word load byte unsigned load half unsigned lwr 5(101) store byte store half swl store word swr 6(110) load linked word lwc1 7(111) store cond. word swc1 op(31:26)=010000 (TLB), rs(25:21) 23–21 25–24 0(000) 1(001) 2(010) 3(011) 4(100) 5(101) 6(110) 7(111) 0(00) mfc0 cfc0 mtc0 ctc0 1(01) 2(10) 3(11) op(31:26)=000000 (R-format), funct(5:0) 2–0 5–3 0(000) 1(001) 2(010) 3(011) 4(100) 5(101) 6(110) 7(111) 0(000) shift left logical shift right logical sra sllv srlv srav 1(001) jump register jalr syscall break 2(010) mfhi mthi mflo mtlo 3(011) mult multu div divu 4(100) add addu subtract subu and or xor not or (nor) 5(101) set l.t. set l.t. unsigned 6(110) 7(111) FIGURE 2.19 MIPS instruction encoding. This notation gives the value of a field by row and by column. For example, the top portion of the figure shows load word in row number 4 (100two for bits 31-29 of the instruction) and column number 3 (011two for bits 28-26 of the instruction), so the corresponding value of the op field (bits 31-26) is 100011two. Underscore means the field is used elsewhere. For example, R-format in row 0 and column 0 (op = 000000two) is defined in the bottom part of the figure. Hence, subtract in row 4 and column 2 of the bottom section means that the funct field (bits 5-0) of the instruction is 100010two and the op field (bits 31-26) is 000000two. The floating point value in row 2, col­umn 1 is defined in Figure 3.18 in Chapter 3. Bltz/gez is the opcode for four instructions found in Appendix B: bltz, bgez, bltzal, and bgezal. This chapter describes instructions given in full name using color, while Chapter 3 describes instructions given in mnemonics using color. Appendix B covers all instructions. 2.10 MIPS Addressing for 32-Bit Immediates and Addresses 135
clipped_hennesy_Page_133_Chunk5490
136 Chapter 2 Instructions: Language of the Computer Figure 2.20 shows all the MIPS instruction formats. Figure 2.1 on page 78 shows the MIPS assembly language revealed in this chapter. The remaining hid­den portion of MIPS instructions deals mainly with arithmetic and real numbers, which are covered in the next chapter. I. What is the range of addresses for conditional branches in MIPS (K = 1024)? 1. Addresses between 0 and 64K - 1 2. Addresses between 0 and 256K - 1 3. Addresses up to about 32K before the branch to about 32K after 4. Addresses up to about 128K before the branch to about 128K after II. What is the range of addresses for jump and jump and link in MIPS (M = 1024K)? 1. Addresses between 0 and 64M - 1 2. Addresses between 0 and 256M - 1 3. Addresses up to about 32M before the branch to about 32M after 4. Addresses up to about 128M before the branch to about 128M after 5. Anywhere within a block of 64M addresses where the PC supplies the upper 6 bits 6. Anywhere within a block of 256M addresses where the PC supplies the upper 4 bits III. What is the MIPS assembly language instruction corresponding to the machine instruction with the value 0000 0000hex? 1. j 2. R-format 3. addi 4. sll 5. mfc0 6. Undefined opcode: there is no legal instruction that corresponds to 0 Check Yourself Name Fields Comments Field size 6 bits 5 bits 5 bits 5 bits 5 bits 6 bits All MIPS instructions are 32 bits long R-format op rs rt rd shamt funct Arithmetic instruction format I-format op rs rt address/immediate Transfer, branch, imm. format J-format op target address Jump instruction format FIGURE 2.20 MIPS instruction formats.
clipped_hennesy_Page_134_Chunk5491
2.11 Parallelism and Instructions: Synchronization Parallel execution is easier when tasks are independent, but often they need to cooperate. Cooperation usually means some tasks are writing new values that others must read. To know when a task is finished writing so that it is safe for another to read, the tasks need to synchronize. If they don’t synchronize, there is a danger of a data race, where the results of the program can change depending on how events happen to occur. For example, recall the analogy of the eight reporters writing a story on page 43 of Chapter 1. Suppose one reporter needs to read all the prior sections before writing a conclusion. Hence, he must know when the other reporters have finished their sections, so that he or she need not worry about them being changed after- wards. That is, they had better synchronize the writing and reading of each section so that the con­clusion will be consistent with what is printed in the prior sections. In computing, synchronization mechanisms are typically built with user-level software routines that rely on hardware-supplied synchronization instructions. In this section, we focus on the implementation of lock and unlock synchronization operations. Lock and unlock can be used straightforwardly to create regions where only a single processor can operate, called mutual exclusion, as well as to implement more complex synchronization mechanisms. The critical ability we require to implement synchronization in a multiproces­ sor is a set of hardware primitives with the ability to atomically read and modify a memory location. That is, nothing else can interpose itself between the read and the write of the memory location. Without such a capability, the cost of building basic synchronization primitives will be too high and will increase as the proces­sor count increases. There are a number of alternative formulations of the basic hardware primi­ tives, all of which provide the ability to atomically read and modify a location, together with some way to tell if the read and write were performed atomically. In general, architects do not expect users to employ the basic hardware primitives, but instead expect that the primitives will be used by system programmers to build a synchronization library, a process that is often complex and tricky. Let’s start with one such hardware primitive and show how it can be used to build a basic synchronization primitive. One typical operation for building syn­ chronization operations is the atomic exchange or atomic swap, which inter­changes a value in a register for a value in memory. To see how to use this to build a basic synchronization primitive, assume that we want to build a simple lock where the value 0 is used to indicate that the lock is free and 1 is used to indicate that the lock is unavailable. A processor tries to set the lock by doing an exchange of 1, which is in a register, with the memory address corresponding to the lock. The value returned from the exchange instruc­tion is 1 if data race Two memory accesses form a data race if they are from different threads to same location, at least one is a write, and they occur one after another. 2.11 Parallelism and Instructions: Synchronization 137
clipped_hennesy_Page_135_Chunk5492
138 Chapter 2 Instructions: Language of the Computer some other processor had already claimed access and 0 otherwise. In the latter case, the value is also changed to 1, preventing any competing exchange in another processor from also retrieving a 0. For example, consider two processors that each try to do the exchange simulta­ neously: this race is broken, since exactly one of the processors will perform the exchange first, returning 0, and the second processor will return 1 when it does the exchange. The key to using the exchange primitive to implement synchroniza­tion is that the operation is atomic: the exchange is indivisible, and two simulta­neous exchanges will be ordered by the hardware. It is impossible for two processors trying to set the synchronization variable in this manner to both think they have simultaneously set the variable. Implementing a single atomic memory operation introduces some challenges in the design of the processor, since it requires both a memory read and a write in a single, uninterruptible instruction. An alternative is to have a pair of instructions in which the second instruction returns a value showing whether the pair of instructions was executed as if the pair were atomic. The pair of instructions is effectively atomic if it appears as if all other operations executed by any processor occurred before or after the pair. Thus, when an instruction pair is effectively atomic, no other processor can change the value between the instruction pair. In MIPS this pair of instructions includes a special load called a load linked and a special store called a store conditional. These instructions are used in sequence: if the contents of the memory location specified by the load linked are changed before the store conditional to the same address occurs, then the store conditional fails. The store conditional is defined to both store the value of a register in mem­ ory and to change the value of that register to a 1 if it succeeds and to a 0 if it fails. Since the load linked returns the initial value, and the store conditional returns 1 only if it succeeds, the following sequence implements an atomic exchange on the memory location specified by the contents of $s1: try: add $t0,$zero,$s4 ;copy exchange value ll $t1,0($s1) ;load linked sc $t0,0($s1) ;store conditional beq $t0,$zero,try ;branch store fails add $s4,$zero,$t1 ;put load value in $s4 At the end of this sequence the contents of $s4 and the memory location speci­ fied by $s1 have been atomically exchanged. Any time a processor intervenes and modifies the value in memory between the ll and sc instructions, the sc returns 0 in $t0, causing the code sequence to try again. Elaboration: Although it was presented for multiprocessor synchronization, atomic exchange is also useful for the operating system in dealing with multiple processes in a single processor. To make sure nothing interferes in a single processor, the store
clipped_hennesy_Page_136_Chunk5493
conditional also fails if the processor does a context switch between the two instructions (see Chapter 5). Since the store conditional will fail after either another attempted store to the load linked address or any exception, care must be taken in choosing which instructions are inserted between the two instructions. In particular, only register-register instructions can safely be permitted; otherwise, it is possible to create deadlock situations where the processor can never complete the sc because of repeated page faults. In addition, the number of instructions between the load linked and the store conditional should be small to minimize the probability that either an unre­lated event or a competing processor causes the store conditional to fail frequently. An advantage of the load linked/store conditional mechanism is that it can be used to build other synchronization primitives, such as atomic compare and swap or atomic fetch-and-increment, which are used in some parallel programming models. These involve more instruc­tions between the ll and the sc. When do you use primitives like load linked and store conditional? 1. When cooperating threads of a parallel program need to synchronize to get proper behavior for reading and writing shared data 2. When cooperating processes on a uniprocessor need to synchronize for reading and writing shared data 2.12 Translating and Starting a Program This section describes the four steps in transforming a C program in a file on disk into a program running on a computer. Figure 2.21 shows the translation hierar­ chy. Some systems combine these steps to reduce translation time, but these are the logical four phases that programs go through. This section follows this trans­lation hierarchy. Compiler The compiler transforms the C program into an assembly language program, a symbolic form of what the machine understands. High-level language programs take many fewer lines of code than assembly language, so programmer productiv­ ity is much higher. In 1975, many operating systems and assemblers were written in assembly lan­ guage because memories were small and compilers were inefficient. The 500,000- fold increase in memory capacity per single DRAM chip has reduced program size concerns, and optimizing compilers today can produce assembly language pro­ grams nearly as good as an assembly language expert, and sometimes even better for large programs. Check Yourself assembly language A sym­bolic language that can be trans­lated into binary machine language. 2.12 Translating and Starting a Program 139
clipped_hennesy_Page_137_Chunk5494
140 Chapter 2 Instructions: Language of the Computer Assembler Since assembly language is an interface to higher-level software, the assembler can also treat common variations of machine language instructions as if they were instructions in their own right. The hardware need not implement these instructions; however, their appearance in assembly language simplifies translation and programming. Such instructions are called pseudoinstructions. As mentioned above, the MIPS hardware makes sure that register $zero always has the value 0. That is, whenever register $zero is used, it supplies a 0, and the programmer cannot change the value of register $zero. Register $zero is used pseudoinstruction A com­mon variation of assembly lan­guage instructions often treated as if it were an ­instruction in its own right. Loader C program Compiler Assembly language program Assembler Object: Machine language module Object: Library routine (machine language) Linker Memory Executable: Machine language program FIGURE 2.21 A translation hierarchy for C. A high-level language program is first compiled into an assembly language program and then assembled into an object module in machine language. The linker combines multiple modules with library routines to resolve all references. The loader then places the machine code into the proper memory locations for execution by the processor. To speed up the translation process, some steps are skipped or combined. Some compilers produce object modules directly, and some systems use linking loaders that perform the last two steps. To identify the type of file, UNIX follows a suffix convention for files: C source files are named x.c, assembly files are x.s, object files are named x.o, stati­cally linked library routines are x.a, dynamically linked library routes are x.so, and executable files by default are called a.out. MS-DOS uses the suffixes .C, .ASM, .OBJ, .LIB, .DLL, and .EXE to the same effect.
clipped_hennesy_Page_138_Chunk5495
to create the assembly language instruction move that copies the contents of one register to another. Thus the MIPS assembler accepts this instruction even though it is not found in the MIPS architecture: move $t0,$t1 # register $t0 gets register $t1 The assembler converts this assembly language instruction into the machine lan­ guage equivalent of the following instruction: add $t0,$zero,$t1 # register $t0 gets 0 + register $t1 The MIPS assembler also converts blt (branch on less than) into the two instructions slt and bne mentioned in the example on page 128. Other examples include bgt, bge, and ble. It also converts branches to faraway locations into a branch and jump. As mentioned above, the MIPS assembler allows 32-bit constants to be loaded into a register despite the 16-bit limit of the immediate instructions. In summary, pseudoinstructions give MIPS a richer set of assembly language instructions than those implemented by the hardware. The only cost is reserving one register, $at, for use by the assembler. If you are going to write assembly pro­ grams, use pseudoinstructions to simplify your task. To understand the MIPS architecture and be sure to get best performance, however, study the real MIPS instructions found in Figures 2.1 and 2.19. Assemblers will also accept numbers in a variety of bases. In addition to binary and decimal, they usually accept a base that is more succinct than binary yet con­ verts easily to a bit pattern. MIPS assemblers use hexadecimal. Such features are convenient, but the primary task of an assembler is assembly into machine code. The assembler turns the assembly language program into an object file, which is a combination of machine language instructions, data, and information needed to place instructions properly in memory. To produce the binary version of each instruction in the assembly language pro­gram, the assembler must determine the addresses corresponding to all ­labels. Assemblers keep track of labels used in branches and data transfer instructions in a symbol table. As you might expect, the table contains pairs of symbols and addresses. The object file for UNIX systems typically contains six distinct pieces: ■ ■The object file header describes the size and position of the other pieces of the object file. ■ ■The text segment contains the machine language code. ■ ■The static data segment contains data allocated for the life of the program. (UNIX allows programs to use both static data, which is allocated throughout the program, and dynamic data, which can grow or shrink as needed by the program. See Figure 2.13.) ■ ■The relocation information identifies instructions and data words that depend on absolute addresses when the program is loaded into memory. symbol table A table that matches names of labels to the addresses of the memory words that instructions ­occupy. 2.12 Translating and Starting a Program 141
clipped_hennesy_Page_139_Chunk5496
142 Chapter 2 Instructions: Language of the Computer ■ ■The symbol table contains the remaining labels that are not defined, such as external references. ■ ■The debugging information contains a concise description of how the mod­ ules were compiled so that a debugger can associate machine instructions with C source files and make data structures readable. The next subsection shows how to attach such routines that have already been assembled, such as library routines. Linker What we have presented so far suggests that a single change to one line of one proce­­ dure requires compiling and assembling the whole program. Complete retransla­­ tion is a terrible waste of computing resources. This repetition is particularly wasteful for standard library routines, because programmers would be compiling and assembling routines that by definition almost never change. An alternative is to compile and assemble each procedure independently, so that a change to one line would require compiling and assembling only one procedure. This alternative requires a new systems program, called a link ­editor or linker, which takes all the independently assembled machine language programs and “stitches” them together. There are three steps for the linker: 1. Place code and data modules symbolically in memory. 2. Determine the addresses of data and instruction labels. 3. Patch both the internal and external references. The linker uses the relocation information and symbol table in each object module to resolve all undefined labels. Such references occur in branch instruc­ tions, jump instructions, and data addresses, so the job of this program is much like that of an editor: it finds the old addresses and replaces them with the new addresses. Editing is the origin of the name “link editor,” or linker for short. The reason a linker is useful is that it is much faster to patch code than it is to recom­pile and reassemble. If all external references are resolved, the linker next determines the memory locations each module will occupy. Recall that Figure 2.13 on page 120 shows the MIPS convention for allocation of program and data to memory. Since the files were assembled in isolation, the assembler could not know where a module’s instructions and data would be placed relative to other modules. When the linker places a module in memory, all absolute references, that is, memory addresses that are not relative to a register, must be relocated to reflect its true location. The linker produces an executable file that can be run on a computer. Typi­cally, this file has the same format as an object file, except that it contains no unre­solved references. It is possible to have partially linked files, such as library routines, that still have unresolved addresses and hence result in object files. linker Also called link editor. A systems program that com­bines independently assembled machine ­language programs and resolves all undefined labels into an executable file. executable file A functional program in the format of an object file that contains no unre­ solved references. It can contain­ symbol tables and debugging information. A “stripped execut­able” does not contain that infor­mation. Relocation information may be included for the loader.
clipped_hennesy_Page_140_Chunk5497
Linking Object Files Link the two object files below. Show updated addresses of the first few in­structions of the completed executable file. We show the instructions in as­sembly language just to make the example understandable; in reality, the instructions would be numbers. Note that in the object files we have highlighted the addresses and symbols that must be updated in the link process: the instructions that refer to the addresses of procedures A and B and the instructions that refer to the addresses of data words X and Y. EXAMPLE Object file header Name Procedure A Text size 100hex Data size 20hex Text segment Address Instruction 0 lw $a0, 0($gp) 4 jal 0 … … Data segment 0 (X) … … Relocation information Address Instruction type Dependency 0 lw X 4 jal B Symbol table Label Address X – B – Object file header Name Procedure B Text size 200hex Data size 30hex Text segment Address Instruction 0 sw $a1, 0($gp) 4 jal 0 … … Data segment 0 (Y) … … Relocation information Address Instruction type Dependency 0 sw Y 4 jal A Symbol table Label Address Y – A – 2.12 Translating and Starting a Program 143
clipped_hennesy_Page_141_Chunk5498
144 Chapter 2 Instructions: Language of the Computer Procedure A needs to find the address for the variable labeled X to put in the load instruction and to find the address of procedure B to place in the jal in­struction. Procedure B needs the address of the variable labeled Y for the store instruction and the address of procedure A for its jal instruction. From Figure 2.13 on page 120, we know that the text segment starts at ad­dress 40 0000hex and the data segment at 1000 0000hex. The text of proce­ dure A is placed at the first address and its data at the second. The object file header for procedure A says that its text is 100hex bytes and its data is 20hex bytes, so the starting address for procedure B text is 40 0100hex, and its data starts at 1000 0020hex. Figure 2.13 also shows that the text segment starts at address 40 0000hex and the data segment at 1000 0000hex. The text of procedure A is placed at the first address and its data at the second. The object file header for proce­dure A says that its text is 100hex bytes and its data is 20hex bytes, so the start­ing address for procedure B text is 40 0100hex, and its data starts at 1000 0020hex. Now the linker updates the address fields of the instructions. It uses the instruction type field to know the format of the address to be edited. We have two types here: ANSWER Executable file header Text size 300hex Data size 50hex Text segment Address Instruction 0040 0000hex lw $a0, 8000hex($gp) 0040 0004hex jal 40 0100hex … … 0040 0100hex sw $a1, 8020hex($gp) 0040 0104hex jal 40 0000hex … … Data segment Address 1000 0000hex (X) … … 1000 0020hex (Y) … …
clipped_hennesy_Page_142_Chunk5499
1. The jals are easy because they use pseudodirect addressing. The jal at address 40 0004hex gets 40 0100hex (the address of procedure B) in its address field, and the jal at 40 0104hex gets 40 0000hex (the address of procedure A) in its address field. 2. The load and store addresses are harder because they are relative to a base register. This example uses the global pointer as the base register. Figure 2.13 shows that $gp is initialized to 1000 8000hex. To get the address 1000 0000hex (the address of word X), we place -8000hex in the address field of lw at address 40 0000hex. Similarly, we place -7980hex in the address field of sw at address 40 0100hex to get the address 1000 0020hex (the address of word Y). Elaboration: Recall that MIPS instructions are word aligned, so jal drops the right two bits to increase the instruction’s address range. Thus, it use 26 bits to create a 28-bit byte address. Hence, the actual address in the lower 26 bits of the jal instruction in this example is 10 0040hex, rather than 40 0100hex. Loader Now that the executable file is on disk, the operating system reads it to memory and starts it. The loader follows these steps in UNIX systems: 1. Reads the executable file header to determine size of the text and data segments. 2. Creates an address space large enough for the text and data. 3. Copies the instructions and data from the executable file into memory. 4. Copies the parameters (if any) to the main program onto the stack. 5. Initializes the machine registers and sets the stack pointer to the first free location. 6. Jumps to a start-up routine that copies the parameters into the argument registers and calls the main routine of the program. When the main routine returns, the start-up routine terminates the program with an exit system call. Sections B.3 and B.4 in Appendix B describe linkers and loaders in more detail. Dynamically Linked Libraries The first part of this section describes the traditional approach to linking libraries before the program is run. Although this static approach is the fastest way to call library routines, it has a few disadvantages: loader A systems program that places an object program in main memory so that it is ready to execute. 2.12 Translating and Starting a Program 145
clipped_hennesy_Page_143_Chunk5500