[go: up one dir, main page]

0% found this document useful (0 votes)
155 views231 pages

Computer Abstractions and Technology

- Computer technology has progressed rapidly due to Moore's law, enabling novel applications like cell phones, the human genome project, the World Wide Web, and search engines. - There are different classes of computers including desktops, servers, and embedded computers, each with different purposes and constraints. - This chapter will cover how programs are executed by hardware, the hardware/software interface, factors that determine performance like algorithms and hardware, and how performance is measured and improved.

Uploaded by

Mfgfgffg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
155 views231 pages

Computer Abstractions and Technology

- Computer technology has progressed rapidly due to Moore's law, enabling novel applications like cell phones, the human genome project, the World Wide Web, and search engines. - There are different classes of computers including desktops, servers, and embedded computers, each with different purposes and constraints. - This chapter will cover how programs are executed by hardware, the hardware/software interface, factors that determine performance like algorithms and hardware, and how performance is measured and improved.

Uploaded by

Mfgfgffg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 231

Chapter 1

Computer Abstractions
and Technology
§1.1 Introduction
The Computer Revolution
■ Progress in computer technology
■ Underpinned by Moore’s Law
■ Makes novel applications feasible
■ Computers in automobiles
■ Cell phones
■ Human genome project
■ World Wide Web
■ Search Engines
■ Computers are pervasive

Chapter 1 — Computer Abstractions and Technology — 2


Classes of Computers
■ Desktop computers
■ General purpose, variety of software
■ Subject to cost/performance tradeoff
■ Server computers
■ Network based
■ High capacity, performance, reliability
■ Range from small servers to building sized
■ Embedded computers
■ Hidden as components of systems
■ Stringent power/performance/cost constraints

Chapter 1 — Computer Abstractions and Technology — 3


The Processor Market

Chapter 1 — Computer Abstractions and Technology — 4


What You Will Learn
■ How programs are translated into the
machine language
■ And how the hardware executes them
■ The hardware/software interface
■ What determines program performance
■ And how it can be improved
■ How hardware designers improve
performance
■ What is parallel processing

Chapter 1 — Computer Abstractions and Technology — 5


Understanding Performance
■ Algorithm
■ Determines number of operations executed
■ Programming language, compiler, architecture
■ Determine number of machine instructions executed
per operation
■ Processor and memory system
■ Determine how fast instructions are executed
■ I/O system (including OS)
■ Determines how fast I/O operations are executed

Chapter 1 — Computer Abstractions and Technology — 6


§1.2 Below Your Program
Below Your Program
■ Application software
■ Written in high-level language
■ System software
■ Compiler: translates HLL code to
machine code
■ Operating System: service code
■ Handling input/output
■ Managing memory and storage
■ Scheduling tasks & sharing resources
■ Hardware
■ Processor, memory, I/O controllers

Chapter 1 — Computer Abstractions and Technology — 7


Levels of Program Code
■ High-level language
■ Level of abstraction closer
to problem domain
■ Provides for productivity
and portability
■ Assembly language
■ Textual representation of
instructions
■ Hardware representation
■ Binary digits (bits)
■ Encoded instructions and
data

Chapter 1 — Computer Abstractions and Technology — 8


§1.3 Under the Covers
Components of a Computer
The BIG Picture ■ Same components for
all kinds of computer
■ Desktop, server,
embedded
■ Input/output includes
■ User-interface devices
■ Display, keyboard, mouse
■ Storage devices
■ Hard disk, CD/DVD, flash
■ Network adapters
■ For communicating with
other computers

Chapter 1 — Computer Abstractions and Technology — 9


Anatomy of a Computer

Output
device

Network
cable

Input Input
device device

Chapter 1 — Computer Abstractions and Technology — 10


Anatomy of a Mouse
■ Optical mouse
■ LED illuminates
desktop
■ Small low-res camera
■ Basic image processor
■ Looks for x, y
movement
■ Buttons & wheel
■ Supersedes roller-ball
mechanical mouse

Chapter 1 — Computer Abstractions and Technology — 11


Through the Looking Glass
■ LCD screen: picture elements (pixels)
■ Mirrors content of frame buffer memory

Chapter 1 — Computer Abstractions and Technology — 12


Opening the Box

Chapter 1 — Computer Abstractions and Technology — 13


Inside the Processor (CPU)
■ Datapath: performs operations on data
■ Control: sequences datapath, memory, ...
■ Cache memory
■ Small fast SRAM memory for immediate
access to data

Chapter 1 — Computer Abstractions and Technology — 14


Inside the Processor
■ AMD Barcelona: 4 processor cores

Chapter 1 — Computer Abstractions and Technology — 15


Abstractions
The BIG Picture

■ Abstraction helps us deal with complexity


■ Hide lower-level detail
■ Instruction set architecture (ISA)
■ The hardware/software interface
■ Application binary interface
■ The ISA plus system software interface
■ Implementation
■ The details underlying and interface

Chapter 1 — Computer Abstractions and Technology — 16


A Safe Place for Data
■ Volatile main memory
■ Loses instructions and data when power off
■ Non-volatile secondary memory
■ Magnetic disk
■ Flash memory
■ Optical disk (CDROM, DVD)

Chapter 1 — Computer Abstractions and Technology — 17


Networks
■ Communication and resource sharing
■ Local area network (LAN): Ethernet
■ Within a building
■ Wide area network (WAN: the Internet
■ Wireless network: WiFi, Bluetooth

Chapter 1 — Computer Abstractions and Technology — 18


Technology Trends
■ Electronics
technology
continues to evolve
■ Increased capacity
and performance
DRAM capacity
■ Reduced cost
Year Technology Relative performance/cost
1951 Vacuum tube 1
1965 Transistor 35
1975 Integrated circuit (IC) 900
1995 Very large scale IC (VLSI) 2,400,000
2005 Ultra large scale IC 6,200,000,000

Chapter 1 — Computer Abstractions and Technology — 19


§1.4 Performance
Defining Performance
■ Which airplane has the best performance?

Chapter 1 — Computer Abstractions and Technology — 20


Response Time and Throughput
■ Response time
■ How long it takes to do a task
■ Throughput
■ Total work done per unit time
■ e.g., tasks/transactions/… per hour
■ How are response time and throughput affected
by
■ Replacing the processor with a faster version?
■ Adding more processors?
■ We’ll focus on response time for now…

Chapter 1 — Computer Abstractions and Technology — 21


Relative Performance
■ Define Performance = 1/Execution Time
■ “X is n time faster than Y”

■ Example: time taken to run a program


■ 10s on A, 15s on B
■ Execution TimeB / Execution TimeA
Pa/Pb = (1/ta)/(1/tb)= tb/ta= 15s / 10s = 1.5
■ So A is 1.5 times faster than B
Chapter 1 — Computer Abstractions and Technology — 22
Measuring Execution Time
■ Elapsed time
■ Total response time, including all aspects
■ Processing, I/O, OS overhead, idle time
■ Determines system performance
■ CPU time
■ Time spent processing a given job
■ Discounts I/O time, other jobs’ shares
■ Comprises user CPU time and system CPU
time
■ Different programs are affected differently by
CPU and system performance

Chapter 1 — Computer Abstractions and Technology — 23


CPU Clocking
■ Operation of digital hardware governed by a
constant-rate clock
T= 1 sec / cycle =Clock period

Clock (cycles)

Data transfer
and computation
Update state

■ Clock period: duration of a clock cycle


■ e.g., 250ps = 0.25ns = 250×10–12s
■ Clock frequency (rate): F = 1/T cycles per second ( Hertz =Hz)
■ e.g., 4.0GHz = 4000MHz = 4.0×109Hz

Chapter 1 — Computer Abstractions and Technology — 24


CPU Time

■ Performance improved by
■ Reducing number of clock cycles
■ Increasing clock rate
■ Hardware designer must often trade off clock
rate against cycle count

Chapter 1 — Computer Abstractions and Technology — 25


CPU Time Example
■ Computer A: 2GHz clock, 10s CPU time
■ Designing Computer B
■ Aim for 6s CPU time
■ Can do faster clock, but causes 1.2 × clock cycles
■ How fast must Computer B clock be?

Chapter 1 — Computer Abstractions and Technology — 26


Instruction Count and CPI

■ Instruction Count for a program


■ Determined by program, ISA and compiler
■ Average cycles per instruction
■ Determined by CPU hardware
■ If different instructions have different CPI
■ Average CPI affected by instruction mix

Chapter 1 — Computer Abstractions and Technology — 27


CPI Example
■ Computer A: Cycle Time = 250ps, CPI = 2.0
■ Computer B: Cycle Time = 500ps, CPI = 1.2
■ Same ISA
■ Which is faster, and by how much?

A is faster…

…by this much

Chapter 1 — Computer Abstractions and Technology — 28


CPI in More Detail
■ If different instruction classes take different
numbers of cycles

■ Weighted average CPI

Relative frequency

Chapter 1 — Computer Abstractions and Technology — 29


CPI Example
■ Alternative compiled code sequences using
instructions in classes A, B, C
Class A B C
CPI for class 1 2 3
IC in sequence 1 2 1 2
IC in sequence 2 4 1 1

■ Sequence 1: IC = 5 ■ Sequence 2: IC = 6
■ Clock Cycles ■ Clock Cycles
= 2×1 + 1×2 + 2×3 = 4×1 + 1×2 + 1×3
= 10 =9
■ Avg. CPI = 10/5 = 2.0 ■ Avg. CPI = 9/6 = 1.5
Chapter 1 — Computer Abstractions and Technology — 30
Performance Summary
The BIG Picture

■ Performance depends on
■ Algorithm: affects IC, possibly CPI
■ Programming language: affects IC, CPI
■ Compiler: affects IC, CPI
■ Instruction set architecture: affects IC, CPI, Tc

Chapter 1 — Computer Abstractions and Technology — 31


§1.5 The Power Wall
Power Trends

■ In CMOS IC technology

×30 5V → 1V ×1000

Chapter 1 — Computer Abstractions and Technology — 32


Reducing Power
■ Suppose a new CPU has
■ 85% of capacitive load of old CPU
■ 15% voltage and 15% frequency reduction

■ The power wall


■ We can’t reduce voltage further
■ We can’t remove more heat
■ How else can we improve performance?
Chapter 1 — Computer Abstractions and Technology — 33
§1.6 The Sea Change: The Switch to Multiprocessors
Uniprocessor Performance

Constrained by power, instruction-level parallelism,


memory latency

Chapter 1 — Computer Abstractions and Technology — 34


Multiprocessors
■ Multicore microprocessors
■ More than one processor per chip
■ Requires explicitly parallel programming
■ Compare with instruction level parallelism
■ Hardware executes multiple instructions at once
■ Hidden from the programmer
■ Hard to do
■ Programming for performance
■ Load balancing
■ Optimizing communication and synchronization

Chapter 1 — Computer Abstractions and Technology — 35


§1.7 Real Stuff: The AMD Opteron X4
Manufacturing ICs

■ Yield: proportion of working dies per wafer

Chapter 1 — Computer Abstractions and Technology — 36


AMD Opteron X2 Wafer

■ X2: 300mm wafer, 117 chips, 90nm technology


■ X4: 45nm technology
Chapter 1 — Computer Abstractions and Technology — 37
Integrated Circuit Cost

■ Nonlinear relation to area and defect rate


■ Wafer cost and area are fixed
■ Defect rate determined by manufacturing process
■ Die area determined by architecture and circuit design

Chapter 1 — Computer Abstractions and Technology — 38


SPEC CPU Benchmark
■ Programs used to measure performance
■ Supposedly typical of actual workload
■ Standard Performance Evaluation Corp (SPEC)
■ Develops benchmarks for CPU, I/O, Web, …
■ SPEC CPU2006
■ Elapsed time to execute a selection of programs
■ Negligible I/O, so focuses on CPU performance
■ Normalize relative to reference machine
■ Summarize as geometric mean of performance ratios
■ CINT2006 (integer) and CFP2006 (floating-point)

Chapter 1 — Computer Abstractions and Technology — 39


CINT2006 for Opteron X4 2356
Name Description IC×109 CPI Tc (ns) Exec time Ref time SPECratio
perl Interpreted string processing 2,118 0.75 0.40 637 9,777 15.3
bzip2 Block-sorting compression 2,389 0.85 0.40 817 9,650 11.8
gcc GNU C Compiler 1,050 1.72 0.47 24 8,050 11.1
mcf Combinatorial optimization 336 10.00 0.40 1,345 9,120 6.8
go Go game (AI) 1,658 1.09 0.40 721 10,490 14.6
hmmer Search gene sequence 2,783 0.80 0.40 890 9,330 10.5
sjeng Chess game (AI) 2,176 0.96 0.48 37 12,100 14.5
libquantum Quantum computer simulation 1,623 1.61 0.40 1,047 20,720 19.8
h264avc Video compression 3,102 0.80 0.40 993 22,130 22.3
omnetpp Discrete event simulation 587 2.94 0.40 690 6,250 9.1
astar Games/path finding 1,082 1.79 0.40 773 7,020 9.1
xalancbmk XML parsing 1,058 2.70 0.40 1,143 6,900 6.0
Geometric mean 11.7

High cache miss rates

Chapter 1 — Computer Abstractions and Technology — 40


SPEC Power Benchmark
■ Power consumption of server at different
workload levels
■ Performance: ssj_ops/sec
■ Power: Watts (Joules/sec)

Chapter 1 — Computer Abstractions and Technology — 41


SPECpower_ssj2008 for X4
Target Load % Performance (ssj_ops/sec) 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% 920,35 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
Chapter 1 — Computer Abstractions and Technology — 42
§1.8 Fallacies and Pitfalls
Pitfall: Amdahl’s Law
■ Improving an aspect of a computer and
expecting a proportional improvement in
overall performance

■ Example: multiply accounts for 80s/100s


■ How much improvement in multiply performance to
get 5× overall?
■ Can’t be done!

■ Corollary: make the common case fast


Chapter 1 — Computer Abstractions and Technology — 43
Fallacy: Low Power at Idle
■ Look back at X4 power benchmark
■ At 100% load: 295W
■ At 50% load: 246W (83%)
■ At 10% load: 180W (61%)
■ Google data center
■ Mostly operates at 10% – 50% load
■ At 100% load less than 1% of the time
■ Consider designing processors to make
power proportional to load

Chapter 1 — Computer Abstractions and Technology — 44


Pitfall: MIPS as a Performance Metric
■ MIPS: Millions of Instructions Per Second
■ Doesn’t account for
■ Differences in ISAs between computers
■ Differences in complexity between instructions

■ CPI varies between programs on a given CPU


Chapter 1 — Computer Abstractions and Technology — 45
§1.9 Concluding Remarks
Concluding Remarks
■ Cost/performance is improving
■ Due to underlying technology development
■ Hierarchical layers of abstraction
■ In both hardware and software
■ Instruction set architecture
■ The hardware/software interface
■ Execution time: the best performance
measure
■ Power is a limiting factor
■ Use parallelism to improve performance

Chapter 1 — Computer Abstractions and Technology — 46


Chapter 2
Instructions: Language
of the Computer
§2.1 Introduction
Instruction Set
◼ The repertoire of instructions of a
computer
◼ Different computers have different
instruction sets
◼ But with many aspects in common
◼ Early computers had very simple
instruction sets
◼ Simplified implementation
◼ Many modern computers also have simple
instruction sets

Chapter 2 — Instructions: Language of the Computer — 2


The MIPS Instruction Set
◼ Used as the example throughout the book
◼ Stanford MIPS commercialized by MIPS
Technologies (www.mips.com)
◼ Large share of embedded core market
◼ Applications in consumer electronics, network/storage
equipment, cameras, printers, …
◼ Typical of many modern ISAs
◼ See MIPS Reference Data tear-out card, and
Appendixes B and E

Chapter 2 — Instructions: Language of the Computer — 3


§2.2 Operations of the Computer Hardware
Arithmetic Operations
◼ Add and subtract, three operands
◼ Two sources and one destination
add a, b, c # a gets b + c
◼ All arithmetic operations have this form
◼ Design Principle 1: Simplicity favours
regularity
◼ Regularity makes implementation simpler
◼ Simplicity enables higher performance at
lower cost

Chapter 2 — Instructions: Language of the Computer — 4


Arithmetic Example
◼ C code:
f = (g + h) - (i + j);

◼ Compiled MIPS code:


add t0, g, h # temp t0 = g + h
add t1, i, j # temp t1 = i + j
sub f, t0, t1 # f = t0 - t1

Chapter 2 — Instructions: Language of the Computer — 5


§2.3 Operands of the Computer Hardware
Register Operands
◼ Arithmetic instructions use register
operands
◼ MIPS has a 32 × 32-bit register file
◼ Use for frequently accessed data
◼ Numbered 0 to 31
◼ 32-bit data called a “word”
◼ Assembler names
◼ $t0, $t1, …, $t9 for temporary values
◼ $s0, $s1, …, $s7 for saved variables
◼ Design Principle 2: Smaller is faster
◼ c.f. main memory: millions of locations

Chapter 2 — Instructions: Language of the Computer — 6


Register Operand Example
◼ C code:
f = (g + h) - (i + j);
◼ f, …, j in $s0, …, $s4

◼ Compiled MIPS code:


add $t0, $s1, $s2
add $t1, $s3, $s4
sub $s0, $t0, $t1

Chapter 2 — Instructions: Language of the Computer — 7


Memory Operands
◼ Main memory used for composite data
◼ Arrays, structures, dynamic data
◼ To apply arithmetic operations
◼ Load values from memory into registers
◼ Store result from register to memory
◼ Memory is byte addressed
◼ Each address identifies an 8-bit byte
◼ Words are aligned in memory
◼ Address must be a multiple of 4
◼ MIPS is Big Endian
◼ Most-significant byte at least address of a word
◼ c.f. Little Endian: least-significant byte at least address

Chapter 2 — Instructions: Language of the Computer — 8


Memory Operand Example 1
◼ C code:
g = h + A[8];
◼ g in $s1, h in $s2, base address of A in $s3

◼ Compiled MIPS code:


◼ Index 8 requires offset of 32
◼ 4 bytes per word
lw $t0, 32($s3) # load word
add $s1, $s2, $t0
offset base register

Chapter 2 — Instructions: Language of the Computer — 9


Memory Operand Example 2
◼ C code:
A[12] = h + A[8];
◼ h in $s2, base address of A in $s3

◼ Compiled MIPS code:


◼ Index 8 requires offset of 32
lw $t0, 32($s3) # load word
add $t0, $s2, $t0
sw $t0, 48($s3) # store word

Chapter 2 — Instructions: Language of the Computer — 10


Registers vs. Memory
◼ Registers are faster to access than
memory
◼ Operating on memory data requires loads
and stores
◼ More instructions to be executed
◼ Compiler must use registers for variables
as much as possible
◼ Only spill to memory for less frequently used
variables
◼ Register optimization is important!

Chapter 2 — Instructions: Language of the Computer — 11


Immediate Operands
◼ Constant data specified in an instruction
addi $s3, $s3, 4
◼ No subtract immediate instruction
◼ Just use a negative constant
addi $s2, $s1, -1
◼ Design Principle 3: Make the common
case fast
◼ Small constants are common
◼ Immediate operand avoids a load instruction

Chapter 2 — Instructions: Language of the Computer — 12


The Constant Zero
◼ MIPS register 0 ($zero) is the constant 0
◼ Cannot be overwritten
◼ Useful for common operations
◼ E.g., move between registers
add $t2, $s1, $zero

Chapter 2 — Instructions: Language of the Computer — 13


§2.4 Signed and Unsigned Numbers
Unsigned Binary Integers
◼ Given an n-bit number
n−1 n−2
x = xn−12 + x n−2 2 +  + x1 2 + x 0 2
1 0

◼ Range: 0 to +2n – 1
◼ Example
◼ 0000 0000 0000 0000 0000 0000 0000 10112
= 0 + … + 1×23 + 0×22 +1×21 +1×20
= 0 + … + 8 + 0 + 2 + 1 = 1110
◼ Using 32 bits
◼ 0 to +4,294,967,295

Chapter 2 — Instructions: Language of the Computer — 14


2s-Complement Signed Integers
◼ Given an n-bit number
n−1 n−2
x = −xn−12 + x n−2 2 +  + x1 2 + x 0 2
1 0

◼ Range: –2n – 1 to +2n – 1 – 1


◼ Example
◼ 1111 1111 1111 1111 1111 1111 1111 11002
= –1×231 + 1×230 + … + 1×22 +0×21 +0×20
= –2,147,483,648 + 2,147,483,644 = –410
◼ Using 32 bits
◼ –2,147,483,648 to +2,147,483,647

Chapter 2 — Instructions: Language of the Computer — 15


2s-Complement Signed Integers
◼ Bit 31 is sign bit
◼ 1 for negative numbers
◼ 0 for non-negative numbers
◼ –(–2n – 1) can’t be represented
◼ Non-negative numbers have the same unsigned
and 2s-complement representation
◼ Some specific numbers
◼ 0: 0000 0000 … 0000
◼ –1: 1111 1111 … 1111
◼ Most-negative: 1000 0000 … 0000
◼ Most-positive: 0111 1111 … 1111

Chapter 2 — Instructions: Language of the Computer — 16


Signed Negation
◼ Complement and add 1
◼ Complement means 1 → 0, 0 → 1

x + x = 1111...1112 = −1
x + 1 = −x

◼ Example: negate +2
◼ +2 = 0000 0000 … 00102
◼ –2 = 1111 1111 … 11012 + 1
= 1111 1111 … 11102

Chapter 2 — Instructions: Language of the Computer — 17


Sign Extension
◼ Representing a number using more bits
◼ Preserve the numeric value
◼ In MIPS instruction set
◼ addi: extend immediate value
◼ lb, lh: extend loaded byte/halfword
◼ beq, bne: extend the displacement
◼ Replicate the sign bit to the left
◼ c.f. unsigned values: extend with 0s
◼ Examples: 8-bit to 16-bit
◼ +2: 0000 0010 => 0000 0000 0000 0010
◼ –2: 1111 1110 => 1111 1111 1111 1110

Chapter 2 — Instructions: Language of the Computer — 18


§2.5 Representing Instructions in the Computer
Representing Instructions
◼ Instructions are encoded in binary
◼ Called machine code
◼ MIPS instructions
◼ Encoded as 32-bit instruction words
◼ Small number of formats encoding operation code
(opcode), register numbers, …
◼ Regularity!
◼ Register numbers
◼ $t0 – $t7 are reg’s 8 – 15
◼ $t8 – $t9 are reg’s 24 – 25
◼ $s0 – $s7 are reg’s 16 – 23

Chapter 2 — Instructions: Language of the Computer — 19


MIPS R-format Instructions
op rs rt rd shamt funct
6 bits 5 bits 5 bits 5 bits 5 bits 6 bits

◼ Instruction fields
◼ op: operation code (opcode)
◼ rs: first source register number
◼ rt: second source register number
◼ rd: destination register number
◼ shamt: shift amount (00000 for now)
◼ funct: function code (extends opcode)

Chapter 2 — Instructions: Language of the Computer — 20


R-format Example
op rs rt rd shamt funct
6 bits 5 bits 5 bits 5 bits 5 bits 6 bits

add $t0, $s1, $s2


special $s1 $s2 $t0 0 add

0 17 18 8 0 32

000000 10001 10010 01000 00000 100000

000000100011001001000000001000002 = 0232402016

Chapter 2 — Instructions: Language of the Computer — 21


Hexadecimal
◼ Base 16
◼ Compact representation of bit strings
◼ 4 bits per hex digit

0 0000 4 0100 8 1000 c 1100


1 0001 5 0101 9 1001 d 1101
2 0010 6 0110 a 1010 e 1110
3 0011 7 0111 b 1011 f 1111

◼ Example: eca8 6420


◼ 1110 1100 1010 1000 0110 0100 0010 0000

Chapter 2 — Instructions: Language of the Computer — 22


MIPS I-format Instructions
op rs rt constant or address
6 bits 5 bits 5 bits 16 bits

◼ Immediate arithmetic and load/store instructions


◼ rt: destination or source register number
◼ Constant: –215 to +215 – 1
◼ Address: offset added to base address in rs
◼ Design Principle 4: Good design demands good
compromises
◼ Different formats complicate decoding, but allow 32-bit
instructions uniformly
◼ Keep formats as similar as possible

Chapter 2 — Instructions: Language of the Computer — 23


§2.6 Logical Operations
Logical Operations
◼ Instructions for bitwise manipulation
Operation C Java MIPS
Shift left << << sll
Shift right >> >>> srl
Bitwise AND & & and, andi
Bitwise OR | | or, ori
Bitwise NOT ~ ~ nor

◼ Useful for extracting and inserting


groups of bits in a word
Chapter 2 — Instructions: Language of the Computer — 24
Shift Operations
op rs rt rd shamt funct
6 bits 5 bits 5 bits 5 bits 5 bits 6 bits

◼ shamt: how many positions to shift


◼ Shift left logical
◼ Shift left and fill with 0 bits
◼ sll by i bits multiplies by 2i
◼ Shift right logical
◼ Shift right and fill with 0 bits
◼ srl by i bits divides by 2i (unsigned only)

Chapter 2 — Instructions: Language of the Computer — 25


AND Operations
◼ Useful to mask bits in a word
◼ Select some bits, clear others to 0
and $t0, $t1, $t2

$t2 0000 0000 0000 0000 0000 1101 1100 0000

$t1 0000 0000 0000 0000 0011 1100 0000 0000

$t0 0000 0000 0000 0000 0000 1100 0000 0000

Chapter 2 — Instructions: Language of the Computer — 26


OR Operations
◼ Useful to include bits in a word
◼ Set some bits to 1, leave others unchanged
or $t0, $t1, $t2

$t2 0000 0000 0000 0000 0000 1101 1100 0000

$t1 0000 0000 0000 0000 0011 1100 0000 0000

$t0 0000 0000 0000 0000 0011 1101 1100 0000

Chapter 2 — Instructions: Language of the Computer — 27


NOT Operations
◼ Useful to invert bits in a word
◼ Change 0 to 1, and 1 to 0
◼ MIPS has NOR 3-operand instruction
◼ a NOR b == NOT ( a OR b )
nor $t0, $t1, $zero Register 0: always
read as zero

$t1 0000 0000 0000 0000 0011 1100 0000 0000

$t0 1111 1111 1111 1111 1100 0011 1111 1111

Chapter 2 — Instructions: Language of the Computer — 28


§2.7 Instructions for Making Decisions
Conditional Operations
◼ Branch to a labeled instruction if a
condition is true
◼ Otherwise, continue sequentially
◼ beq rs, rt, L1
◼ if (rs == rt) branch to instruction labeled L1;
◼ bne rs, rt, L1
◼ if (rs != rt) branch to instruction labeled L1;
◼ j L1
◼ unconditional jump to instruction labeled L1

Chapter 2 — Instructions: Language of the Computer — 29


Compiling If Statements
◼ C code:
if (i==j) f = g+h;
else f = g-h;
◼ f, g, … in $s0, $s1, …
◼ Compiled MIPS code:
bne $s3, $s4, Else
add $s0, $s1, $s2
j Exit
Else: sub $s0, $s1, $s2
Exit: …
Assembler calculates addresses

Chapter 2 — Instructions: Language of the Computer — 30


Compiling Loop Statements
◼ C code:
while (save[i] == k) i += 1;
◼ i in $s3, k in $s5, address of save in $s6
◼ Compiled MIPS code:
Loop: sll $t1, $s3, 2
add $t1, $t1, $s6
lw $t0, 0($t1)
bne $t0, $s5, Exit
addi $s3, $s3, 1
j Loop
Exit: …

Chapter 2 — Instructions: Language of the Computer — 31


Basic Blocks
◼ A basic block is a sequence of instructions
with
◼ No embedded branches (except at end)
◼ No branch targets (except at beginning)

◼ A compiler identifies basic


blocks for optimization
◼ An advanced processor
can accelerate execution
of basic blocks

Chapter 2 — Instructions: Language of the Computer — 32


More Conditional Operations
◼ Set result to 1 if a condition is true
◼ Otherwise, set to 0
◼ slt rd, rs, rt
◼ if (rs < rt) rd = 1; else rd = 0;
◼ slti rt, rs, constant
◼ if (rs < constant) rt = 1; else rt = 0;
◼ Use in combination with beq, bne
slt $t0, $s1, $s2 # if ($s1 < $s2)
bne $t0, $zero, L # branch to L

Chapter 2 — Instructions: Language of the Computer — 33


Branch Instruction Design
◼ Why not blt, bge, etc?
◼ Hardware for <, ≥, … slower than =, ≠
◼ Combining with branch involves more work
per instruction, requiring a slower clock
◼ All instructions penalized!
◼ beq and bne are the common case
◼ This is a good design compromise

Chapter 2 — Instructions: Language of the Computer — 34


Signed vs. Unsigned
◼ Signed comparison: slt, slti
◼ Unsigned comparison: sltu, sltui
◼ Example
◼ $s0 = 1111 1111 1111 1111 1111 1111 1111 1111
◼ $s1 = 0000 0000 0000 0000 0000 0000 0000 0001
◼ slt $t0, $s0, $s1 # signed
◼ –1 < +1  $t0 = 1
◼ sltu $t0, $s0, $s1 # unsigned
◼ +4,294,967,295 > +1  $t0 = 0

Chapter 2 — Instructions: Language of the Computer — 35


§2.8 Supporting Procedures in Computer Hardware
Procedure Calling
◼ Steps required
1. Place parameters in registers
2. Transfer control to procedure
3. Acquire storage for procedure
4. Perform procedure’s operations
5. Place result in register for caller
6. Return to place of call

Chapter 2 — Instructions: Language of the Computer — 36


Register Usage
◼ $a0 – $a3: arguments (reg’s 4 – 7)
◼ $v0, $v1: result values (reg’s 2 and 3)
◼ $t0 – $t9: temporaries
◼ Can be overwritten by callee
◼ $s0 – $s7: saved
◼ Must be saved/restored by callee
◼ $gp: global pointer for static data (reg 28)
◼ $sp: stack pointer (reg 29)
◼ $fp: frame pointer (reg 30)
◼ $ra: return address (reg 31)

Chapter 2 — Instructions: Language of the Computer — 37


Procedure Call Instructions
◼ Procedure call: jump and link
jal ProcedureLabel
◼ Address of following instruction put in $ra

◼ Jumps to target address

◼ Procedure return: jump register


jr $ra
◼ Copies $ra to program counter

◼ Can also be used for computed jumps

◼ e.g., for case/switch statements

Chapter 2 — Instructions: Language of the Computer — 38


§2.9 Communicating with People
Character Data
◼ Byte-encoded character sets
◼ ASCII: 128 characters
◼ 95 graphic, 33 control
◼ Latin-1: 256 characters
◼ ASCII, +96 more graphic characters
◼ Unicode: 32-bit character set
◼ Used in Java, C++ wide characters, …
◼ Most of the world’s alphabets, plus symbols
◼ UTF-8, UTF-16: variable-length encodings

Chapter 2 — Instructions: Language of the Computer — 39


Byte/Halfword Operations
◼ Could use bitwise operations
◼ MIPS byte/halfword load/store
◼ String processing is a common case
lb rt, offset(rs) lh rt, offset(rs)
◼ Sign extend to 32 bits in rt
lbu rt, offset(rs) lhu rt, offset(rs)
◼ Zero extend to 32 bits in rt
sb rt, offset(rs) sh rt, offset(rs)
◼ Store just rightmost byte/halfword

Chapter 2 — Instructions: Language of the Computer — 40


String Copy Example
◼ C code (naïve):
◼ Null-terminated string
void strcpy (char x[], char y[])
{ int i;
i = 0;
while ((x[i]=y[i])!='\0')
i += 1;
}
◼ Addresses of x, y in $a0, $a1

◼ i in $s0

Chapter 2 — Instructions: Language of the Computer — 41


String Copy Example
◼ MIPS code:
strcpy:
addi $sp, $sp, -4 # adjust stack for 1 item
sw $s0, 0($sp) # save $s0
add $s0, $zero, $zero # i = 0
L1: add $t1, $s0, $a1 # addr of y[i] in $t1
lbu $t2, 0($t1) # $t2 = y[i]
add $t3, $s0, $a0 # addr of x[i] in $t3
sb $t2, 0($t3) # x[i] = y[i]
beq $t2, $zero, L2 # exit loop if y[i] == 0
addi $s0, $s0, 1 # i = i + 1
j L1 # next iteration of loop
L2: lw $s0, 0($sp) # restore saved $s0
addi $sp, $sp, 4 # pop 1 item from stack
jr $ra # and return

Chapter 2 — Instructions: Language of the Computer — 42


§2.10 MIPS Addressing for 32-Bit Immediates and Addresses
32-bit Constants
◼ Most constants are small
◼ 16-bit immediate is sufficient
◼ For the occasional 32-bit constant
lui rt, constant
◼ Copies 16-bit constant to left 16 bits of rt
◼ Clears right 16 bits of rt to 0

lhi $s0, 61 0000 0000 0111 1101 0000 0000 0000 0000

ori $s0, $s0, 2304 0000 0000 0111 1101 0000 1001 0000 0000

Chapter 2 — Instructions: Language of the Computer — 43


Branch Addressing
◼ Branch instructions specify
◼ Opcode, two registers, target address
◼ Most branch targets are near branch
◼ Forward or backward

op rs rt constant or address
6 bits 5 bits 5 bits 16 bits

◼ PC-relative addressing
◼ Target address = PC + offset × 4
◼ PC already incremented by 4 by this time
Chapter 2 — Instructions: Language of the Computer — 44
Jump Addressing
◼ Jump (j and jal) targets could be
anywhere in text segment
◼ Encode full address in instruction

op address
6 bits 26 bits

◼ (Pseudo)Direct jump addressing


◼ Target address = PC31…28 : (address × 4)

Chapter 2 — Instructions: Language of the Computer — 45


Target Addressing Example
◼ Loop code from earlier example
◼ Assume Loop at location 80000

Loop: sll $t1, $s3, 2 80000 0 0 19 9 4 0


add $t1, $t1, $s6 80004 0 9 22 9 0 32
lw $t0, 0($t1) 80008 35 9 8 0
bne $t0, $s5, Exit 80012 5 8 21 2
addi $s3, $s3, 1 80016 8 19 19 1
j Loop 80020 2 20000
Exit: … 80024

Chapter 2 — Instructions: Language of the Computer — 46


Branching Far Away
◼ If branch target is too far to encode with
16-bit offset, assembler rewrites the code
◼ Example
beq $s0,$s1, L1

bne $s0,$s1, L2
j L1
L2: …

Chapter 2 — Instructions: Language of the Computer — 47


Addressing Mode Summary

Chapter 2 — Instructions: Language of the Computer — 48


§2.11 Parallelism and Instructions: Synchronization
Synchronization
◼ Two processors sharing an area of memory
◼ P1 writes, then P2 reads
◼ Data race if P1 and P2 don’t synchronize
◼ Result depends of order of accesses
◼ Hardware support required
◼ Atomic read/write memory operation
◼ No other access to the location allowed between the
read and write
◼ Could be a single instruction
◼ E.g., atomic swap of register ↔ memory
◼ Or an atomic pair of instructions

Chapter 2 — Instructions: Language of the Computer — 49


§2.12 Translating and Starting a Program
Translation and Startup

Many compilers produce


object modules directly

Static linking

Chapter 2 — Instructions: Language of the Computer — 50


Loading a Program
◼ Load from image file on disk into memory
1. Read header to determine segment sizes
2. Create virtual address space
3. Copy text and initialized data into memory
◼ Or set page table entries so they can be faulted in
4. Set up arguments on stack
5. Initialize registers (including $sp, $fp, $gp)
6. Jump to startup routine
◼ Copies arguments to $a0, … and calls main
◼ When main returns, do exit syscall

Chapter 2 — Instructions: Language of the Computer — 51


Dynamic Linking
◼ Only link/load library procedure when it is
called
◼ Requires procedure code to be relocatable
◼ Avoids image bloat caused by static linking of
all (transitively) referenced libraries
◼ Automatically picks up new library versions

Chapter 2 — Instructions: Language of the Computer — 52


§2.14 Arrays versus Pointers
Arrays vs. Pointers
◼ Array indexing involves
◼ Multiplying index by element size
◼ Adding to array base address
◼ Pointers correspond directly to memory
addresses
◼ Can avoid indexing complexity

Chapter 2 — Instructions: Language of the Computer — 53


Comparison of Array vs. Ptr
◼ Multiply “strength reduced” to shift
◼ Array version requires shift to be inside
loop
◼ Part of index calculation for incremented i
◼ c.f. incrementing pointer
◼ Compiler can achieve same effect as
manual use of pointers
◼ Induction variable elimination
◼ Better to make program clearer and safer

Chapter 2 — Instructions: Language of the Computer — 54


Instruction Encoding

Chapter 2 — Instructions: Language of the Computer — 55


Basic x86 Addressing Modes
◼ Two operands per instruction
Source/dest operand Second source operand
Register Register
Register Immediate
Register Memory
Memory Register
Memory Immediate

◼ Memory addressing modes


◼ Address in register
◼ Address = Rbase + displacement
◼ Address = Rbase + 2scale × Rindex (scale = 0, 1, 2, or 3)
◼ Address = Rbase + 2scale × Rindex + displacement
Chapter 2 — Instructions: Language of the Computer — 56
x86 Instruction Encoding
◼ Variable length
encoding
◼ Postfix bytes specify
addressing mode
◼ Prefix bytes modify
operation
◼ Operand length,
repetition, locking, …

Chapter 2 — Instructions: Language of the Computer — 57


Implementing IA-32
◼ Complex instruction set makes
implementation difficult
◼ Hardware translates instructions to simpler
microoperations
◼ Simple instructions: 1–1
◼ Complex instructions: 1–many
◼ Microengine similar to RISC
◼ Market share makes this economically viable
◼ Comparable performance to RISC
◼ Compilers avoid complex instructions
Chapter 2 — Instructions: Language of the Computer — 58
§2.19 Concluding Remarks
Concluding Remarks
◼ Design principles
1. Simplicity favors regularity
2. Smaller is faster
3. Make the common case fast
4. Good design demands good compromises
◼ Layers of software/hardware
◼ Compiler, assembler, hardware
◼ MIPS: typical of RISC ISAs
◼ c.f. x86

Chapter 2 — Instructions: Language of the Computer — 59


Concluding Remarks
◼ Measure MIPS instruction executions in
benchmark programs
◼ Consider making the common case fast
◼ Consider compromises
Instruction class MIPS examples SPEC2006 Int SPEC2006 FP
Arithmetic add, sub, addi 16% 48%
Data transfer lw, sw, lb, lbu, 35% 36%
lh, lhu, sb, lui
Logical and, or, nor, andi, 12% 4%
ori, sll, srl
Cond. Branch beq, bne, slt, 34% 8%
slti, sltiu
Jump j, jr, jal 2% 0%

Chapter 2 — Instructions: Language of the Computer — 60


Chapter 3
Arithmetic for
Computers
§3.1 Introduction
Arithmetic for Computers
◼ Operations on integers
◼ Addition and subtraction
◼ Multiplication and division
◼ Dealing with overflow
◼ Floating-point real numbers
◼ Representation and operations

Chapter 3 — Arithmetic for Computers — 2


§3.2 Addition and Subtraction
Integer Addition
◼ Example: 7 + 6

◼ Overflow if result out of range


◼ Adding +ve and –ve operands, no overflow
◼ Adding two +ve operands
◼ Overflow if result sign is 1
◼ Adding two –ve operands
◼ Overflow if result sign is 0

Chapter 3 — Arithmetic for Computers — 3


Integer Subtraction
◼ Add negation of second operand
◼ Example: 7 – 6 = 7 + (–6)
+7: 0000 0000 … 0000 0111
–6: 1111 1111 … 1111 1010
+1: 0000 0000 … 0000 0001
◼ Overflow if result out of range
◼ Subtracting two +ve or two –ve operands, no overflow
◼ Subtracting +ve from –ve operand
◼ Overflow if result sign is 0
◼ Subtracting –ve from +ve operand
◼ Overflow if result sign is 1

Chapter 3 — Arithmetic for Computers — 4


Dealing with Overflow
◼ Some languages (e.g., C) ignore overflow
◼ Use MIPS addu, addui, subu instructions
◼ Other languages (e.g., Ada, Fortran)
require raising an exception
◼ Use MIPS add, addi, sub instructions
◼ On overflow, invoke exception handler
◼ Save PC in exception program counter (EPC)
register
◼ Jump to predefined handler address
◼ mfc0 (move from coprocessor reg) instruction can
retrieve EPC value, to return after corrective action

Chapter 3 — Arithmetic for Computers — 5


Arithmetic for Multimedia
◼ Graphics and media processing operates
on vectors of 8-bit and 16-bit data
◼ Use 64-bit adder, with partitioned carry chain
◼ Operate on 8×8-bit, 4×16-bit, or 2×32-bit vectors
◼ SIMD (single-instruction, multiple-data)
◼ Saturating operations
◼ On overflow, result is largest representable
value
◼ c.f. 2s-complement modulo arithmetic
◼ E.g., clipping in audio, saturation in video
Chapter 3 — Arithmetic for Computers — 6
§3.3 Multiplication
Multiplication
◼ Start with long-multiplication approach
multiplicand
1000
multiplier
× 1001
1000
0000
0000
1000
product 1001000

Length of product is
the sum of operand
lengths

Chapter 3 — Arithmetic for Computers — 7


Multiplication Hardware

Initially 0

Chapter 3 — Arithmetic for Computers — 8


Optimized Multiplier
◼ Perform steps in parallel: add/shift

◼ One cycle per partial-product addition


◼ That’s ok, if frequency of multiplications is low
Chapter 3 — Arithmetic for Computers — 9
Faster Multiplier
◼ Uses multiple adders
◼ Cost/performance tradeoff

◼ Can be pipelined
◼ Several multiplication performed in parallel
Chapter 3 — Arithmetic for Computers — 10
MIPS Multiplication
◼ Two 32-bit registers for product
◼ HI: most-significant 32 bits
◼ LO: least-significant 32-bits
◼ Instructions
◼ mult rs, rt / multu rs, rt
◼ 64-bit product in HI/LO
◼ mfhi rd / mflo rd
◼ Move from HI/LO to rd
◼ Can test HI value to see if product overflows 32 bits
◼ mul rd, rs, rt
◼ Least-significant 32 bits of product –> rd

Chapter 3 — Arithmetic for Computers — 11


§3.4 Division
Division
◼ Check for 0 divisor
◼ Long division approach
quotient ◼ If divisor ≤ dividend bits
dividend ◼ 1 bit in quotient, subtract
1001 ◼ Otherwise
1000 1001010 ◼ 0 bit in quotient, bring down next
-1000 dividend bit
divisor
10 ◼ Restoring division
101 ◼ Do the subtract, and if remainder
1010 goes < 0, add divisor back
-1000 ◼ Signed division
remainder 10
◼ Divide using absolute values
◼ Adjust sign of quotient and remainder
n-bit operands yield n-bit as required
quotient and remainder

Chapter 3 — Arithmetic for Computers — 12


Division Hardware
Initially divisor
in left half

Initially dividend

Chapter 3 — Arithmetic for Computers — 13


Optimized Divider

◼ One cycle per partial-remainder subtraction


◼ Looks a lot like a multiplier!
◼ Same hardware can be used for both

Chapter 3 — Arithmetic for Computers — 14


Faster Division
◼ Can’t use parallel hardware as in multiplier
◼ Subtraction is conditional on sign of remainder
◼ Faster dividers (e.g. SRT devision)
generate multiple quotient bits per step
◼ Still require multiple steps

Chapter 3 — Arithmetic for Computers — 15


MIPS Division
◼ Use HI/LO registers for result
◼ HI: 32-bit remainder
◼ LO: 32-bit quotient
◼ Instructions
◼ div rs, rt / divu rs, rt
◼ No overflow or divide-by-0 checking
◼ Software must perform checks if required
◼ Use mfhi, mflo to access result

Chapter 3 — Arithmetic for Computers — 16


§3.5 Floating Point
Floating Point
◼ Representation for non-integral numbers
◼ Including very small and very large numbers
◼ Like scientific notation
◼ –2.34 × 1056 normalized

◼ +0.002 × 10–4 not normalized


◼ +987.02 × 109
◼ In binary
◼ ±1.xxxxxxx2 × 2yyyy
◼ Types float and double in C
Chapter 3 — Arithmetic for Computers — 17
Floating Point Standard
◼ Defined by IEEE Std 754-1985
◼ Developed in response to divergence of
representations
◼ Portability issues for scientific code
◼ Now almost universally adopted
◼ Two representations
◼ Single precision (32-bit)
◼ Double precision (64-bit)

Chapter 3 — Arithmetic for Computers — 18


IEEE Floating-Point Format
single: 8 bits single: 23 bits
double: 11 bits double: 52 bits
S Exponent Fraction

x = ( −1)S  (1+ Fraction)  2(Exponent −Bias)

◼ S: sign bit (0  non-negative, 1  negative)


◼ Normalize significand: 1.0 ≤ |significand| < 2.0
◼ Always has a leading pre-binary-point 1 bit, so no need to
represent it explicitly (hidden bit)
◼ Significand is Fraction with the “1.” restored
◼ Exponent: excess representation: actual exponent + Bias
◼ Ensures exponent is unsigned
◼ Single: Bias = 127; Double: Bias = 1203

Chapter 3 — Arithmetic for Computers — 19


Single-Precision Range
◼ Exponents 00000000 and 11111111 reserved
◼ Smallest value
◼ Exponent: 00000001
 actual exponent = 1 – 127 = –126
◼ Fraction: 000…00  significand = 1.0
◼ ±1.0 × 2–126 ≈ ±1.2 × 10–38
◼ Largest value
◼ exponent: 11111110
 actual exponent = 254 – 127 = +127
◼ Fraction: 111…11  significand ≈ 2.0
◼ ±2.0 × 2+127 ≈ ±3.4 × 10+38

Chapter 3 — Arithmetic for Computers — 20


Double-Precision Range
◼ Exponents 0000…00 and 1111…11 reserved
◼ Smallest value
◼ Exponent: 00000000001
 actual exponent = 1 – 1023 = –1022
◼ Fraction: 000…00  significand = 1.0
◼ ±1.0 × 2–1022 ≈ ±2.2 × 10–308
◼ Largest value
◼ Exponent: 11111111110
 actual exponent = 2046 – 1023 = +1023
◼ Fraction: 111…11  significand ≈ 2.0
◼ ±2.0 × 2+1023 ≈ ±1.8 × 10+308

Chapter 3 — Arithmetic for Computers — 21


Floating-Point Precision
◼ Relative precision
◼ all fraction bits are significant
◼ Single: approx 2–23
◼ Equivalent to 23 × log102 ≈ 23 × 0.3 ≈ 6 decimal
digits of precision
◼ Double: approx 2–52
◼ Equivalent to 52 × log102 ≈ 52 × 0.3 ≈ 16 decimal
digits of precision

Chapter 3 — Arithmetic for Computers — 22


Floating-Point Example
◼ Represent –0.75
◼ –0.75 = (–1)1 × 1.12 × 2–1
◼ S=1
◼ Fraction = 1000…002
◼ Exponent = –1 + Bias
◼ Single: –1 + 127 = 126 = 011111102
◼ Double: –1 + 1023 = 1022 = 011111111102
◼ Single: 1011111101000…00
◼ Double: 1011111111101000…00

Chapter 3 — Arithmetic for Computers — 23


Floating-Point Example
◼ What number is represented by the single-
precision float
11000000101000…00
◼ S=1
◼ Fraction = 01000…002
◼ Fxponent = 100000012 = 129
◼ x = (–1)1 × (1 + 012) × 2(129 – 127)
= (–1) × 1.25 × 22
= –5.0

Chapter 3 — Arithmetic for Computers — 24


Floating-Point Addition
◼ Consider a 4-digit decimal example
◼ 9.999 × 101 + 1.610 × 10–1
◼ 1. Align decimal points
◼ Shift number with smaller exponent
◼ 9.999 × 101 + 0.016 × 101
◼ 2. Add significands
◼ 9.999 × 101 + 0.016 × 101 = 10.015 × 101
◼ 3. Normalize result & check for over/underflow
◼ 1.0015 × 102
◼ 4. Round and renormalize if necessary
◼ 1.002 × 102

Chapter 3 — Arithmetic for Computers — 27


Floating-Point Addition
◼ Now consider a 4-digit binary example
◼ 1.0002 × 2–1 + –1.1102 × 2–2 (0.5 + –0.4375)
◼ 1. Align binary points
◼ Shift number with smaller exponent
◼ 1.0002 × 2–1 + –0.1112 × 2–1
◼ 2. Add significands
◼ 1.0002 × 2–1 + –0.1112 × 2–1 = 0.0012 × 2–1
◼ 3. Normalize result & check for over/underflow
◼ 1.0002 × 2–4, with no over/underflow
◼ 4. Round and renormalize if necessary
◼ 1.0002 × 2–4 (no change) = 0.0625

Chapter 3 — Arithmetic for Computers — 28


FP Adder Hardware
◼ Much more complex than integer adder
◼ Doing it in one clock cycle would take too
long
◼ Much longer than integer operations
◼ Slower clock would penalize all instructions
◼ FP adder usually takes several cycles
◼ Can be pipelined

Chapter 3 — Arithmetic for Computers — 29


FP Adder Hardware

Step 1

Step 2

Step 3

Step 4

Chapter 3 — Arithmetic for Computers — 30


FP Arithmetic Hardware
◼ FP multiplier is of similar complexity to FP
adder
◼ But uses a multiplier for significands instead of
an adder
◼ FP arithmetic hardware usually does
◼ Addition, subtraction, multiplication, division,
reciprocal, square-root
◼ FP  integer conversion
◼ Operations usually takes several cycles
◼ Can be pipelined

Chapter 3 — Arithmetic for Computers — 33


FP Instructions in MIPS
◼ FP hardware is coprocessor 1
◼ Adjunct processor that extends the ISA
◼ Separate FP registers
◼ 32 single-precision: $f0, $f1, … $f31
◼ Paired for double-precision: $f0/$f1, $f2/$f3, …
◼ Release 2 of MIPs ISA supports 32 × 64-bit FP reg’s
◼ FP instructions operate only on FP registers
◼ Programs generally don’t do integer ops on FP data,
or vice versa
◼ More registers with minimal code-size impact
◼ FP load and store instructions
◼ lwc1, ldc1, swc1, sdc1
◼ e.g., ldc1 $f8, 32($sp)

Chapter 3 — Arithmetic for Computers — 34


FP Instructions in MIPS
◼ Single-precision arithmetic
◼ add.s, sub.s, mul.s, div.s
◼ e.g., add.s $f0, $f1, $f6
◼ Double-precision arithmetic
◼ add.d, sub.d, mul.d, div.d
◼ e.g., mul.d $f4, $f4, $f6
◼ Single- and double-precision comparison
◼ c.xx.s, c.xx.d (xx is eq, lt, le, …)
◼ Sets or clears FP condition-code bit
◼ e.g. c.lt.s $f3, $f4
◼ Branch on FP condition code true or false
◼ bc1t, bc1f
◼ e.g., bc1t TargetLabel

Chapter 3 — Arithmetic for Computers — 35


FP Example: °F to °C
◼ C code:
float f2c (float fahr) {
return ((5.0/9.0)*(fahr - 32.0));
}
◼ fahr in $f12, result in $f0, literals in global memory

space
◼ Compiled MIPS code:
f2c: lwc1 $f16, const5($gp)
lwc2 $f18, const9($gp)
div.s $f16, $f16, $f18
lwc1 $f18, const32($gp)
sub.s $f18, $f12, $f18
mul.s $f0, $f16, $f18
jr $ra
Chapter 3 — Arithmetic for Computers — 36
FP Example: Array Multiplication
◼ X=X+Y×Z
◼ All 32 × 32 matrices, 64-bit double-precision elements
◼ C code:
void mm (double x[][],
double y[][], double z[][]) {
int i, j, k;
for (i = 0; i! = 32; i = i + 1)
for (j = 0; j! = 32; j = j + 1)
for (k = 0; k! = 32; k = k + 1)
x[i][j] = x[i][j]
+ y[i][k] * z[k][j];
}
◼ Addresses of x, y, z in $a0, $a1, $a2, and
i, j, k in $s0, $s1, $s2
Chapter 3 — Arithmetic for Computers — 37
FP Example: Array Multiplication
◼ MIPS code:
li $t1, 32 # $t1 = 32 (row size/loop end)
li $s0, 0 # i = 0; initialize 1st for loop
L1: li $s1, 0 # j = 0; restart 2nd for loop
L2: li $s2, 0 # k = 0; restart 3rd for loop
sll $t2, $s0, 5 # $t2 = i * 32 (size of row of x)
addu $t2, $t2, $s1 # $t2 = i * size(row) + j
sll $t2, $t2, 3 # $t2 = byte offset of [i][j]
addu $t2, $a0, $t2 # $t2 = byte address of x[i][j]
l.d $f4, 0($t2) # $f4 = 8 bytes of x[i][j]
L3: sll $t0, $s2, 5 # $t0 = k * 32 (size of row of z)
addu $t0, $t0, $s1 # $t0 = k * size(row) + j
sll $t0, $t0, 3 # $t0 = byte offset of [k][j]
addu $t0, $a2, $t0 # $t0 = byte address of z[k][j]
l.d $f16, 0($t0) # $f16 = 8 bytes of z[k][j]

Chapter 3 — Arithmetic for Computers — 38


FP Example: Array Multiplication

sll $t0, $s0, 5 # $t0 = i*32 (size of row of y)
addu $t0, $t0, $s2 # $t0 = i*size(row) + k
sll $t0, $t0, 3 # $t0 = byte offset of [i][k]
addu $t0, $a1, $t0 # $t0 = byte address of y[i][k]
l.d $f18, 0($t0) # $f18 = 8 bytes of y[i][k]
mul.d $f16, $f18, $f16 # $f16 = y[i][k] * z[k][j]
add.d $f4, $f4, $f16 # f4=x[i][j] + y[i][k]*z[k][j]
addiu $s2, $s2, 1 # $k k + 1
bne $s2, $t1, L3 # if (k != 32) go to L3
s.d $f4, 0($t2) # x[i][j] = $f4
addiu $s1, $s1, 1 # $j = j + 1
bne $s1, $t1, L2 # if (j != 32) go to L2
addiu $s0, $s0, 1 # $i = i + 1
bne $s0, $t1, L1 # if (i != 32) go to L1

Chapter 3 — Arithmetic for Computers — 39


Interpretation of Data
The BIG Picture

◼ Bits have no inherent meaning


◼ Interpretation depends on the instructions
applied
◼ Computer representations of numbers
◼ Finite range and precision
◼ Need to account for this in programs

Chapter 3 — Arithmetic for Computers — 41


§3.6 Parallelism and Computer Arithmetic: Associativity
Associativity
◼ Parallel programs may interleave
operations in unexpected orders
◼ Assumptions of associativity may fail
(x+y)+z x+(y+z)
x -1.50E+38 -1.50E+38
y 1.50E+38 0.00E+00
z 1.0 1.0 1.50E+38
1.00E+00 0.00E+00

◼ Need to validate parallel programs under


varying degrees of parallelism
Chapter 3 — Arithmetic for Computers — 42
§3.7 Real Stuff: Floating Point in the x86
x86 FP Architecture
◼ Originally based on 8087 FP coprocessor
◼ 8 × 80-bit extended-precision registers
◼ Used as a push-down stack
◼ Registers indexed from TOS: ST(0), ST(1), …
◼ FP values are 32-bit or 64 in memory
◼ Converted on load/store of memory operand
◼ Integer operands can also be converted
on load/store
◼ Very difficult to generate and optimize code
◼ Result: poor FP performance

Chapter 3 — Arithmetic for Computers — 43


x86 FP Instructions
Data transfer Arithmetic Compare Transcendental
FILD mem/ST(i) FIADDP mem/ST(i) FICOMP FPATAN
FISTP mem/ST(i) FISUBRP mem/ST(i) FIUCOMP F2XMI
FLDPI FIMULP mem/ST(i) FSTSW AX/mem FCOS
FLD1 FIDIVRP mem/ST(i) FPTAN
FLDZ FSQRT FPREM
FABS FPSIN
FRNDINT FYL2X

◼ Optional variations
◼ I: integer operand
◼ P: pop operand from stack
◼ R: reverse operand order
◼ But not all combinations allowed

Chapter 3 — Arithmetic for Computers — 44


Streaming SIMD Extension 2 (SSE2)
◼ Adds 4 × 128-bit registers
◼ Extended to 8 registers in AMD64/EM64T
◼ Can be used for multiple FP operands
◼ 2 × 64-bit double precision
◼ 4 × 32-bit double precision
◼ Instructions operate on them simultaneously
◼ Single-Instruction Multiple-Data

Chapter 3 — Arithmetic for Computers — 45


§3.8 Fallacies and Pitfalls
Right Shift and Division
◼ Left shift by i places multiplies an integer
by 2i
◼ Right shift divides by 2i?
◼ Only for unsigned integers
◼ For signed integers
◼ Arithmetic right shift: replicate the sign bit
◼ e.g., –5 / 4
◼ 111110112 >> 2 = 111111102 = –2
◼ Rounds toward –∞
◼ c.f. 111110112 >>> 2 = 001111102 = +62

Chapter 3 — Arithmetic for Computers — 46


Who Cares About FP Accuracy?
◼ Important for scientific code
◼ But for everyday consumer use?
◼ “My bank balance is out by 0.0002¢!” 
◼ The Intel Pentium FDIV bug
◼ The market expects accuracy
◼ See Colwell, The Pentium Chronicles

Chapter 3 — Arithmetic for Computers — 47


§3.9 Concluding Remarks
Concluding Remarks
◼ ISAs support arithmetic
◼ Signed and unsigned integers
◼ Floating-point approximation to reals
◼ Bounded range and precision
◼ Operations can overflow and underflow
◼ MIPS ISA
◼ Core instructions: 54 most frequently used
◼ 100% of SPECINT, 97% of SPECFP
◼ Other instructions: less frequent

Chapter 3 — Arithmetic for Computers — 48


Chapter 4
The Processor
§4.1 Introduction
Introduction
◼ CPU performance factors
◼ Instruction count
◼ Determined by ISA and compiler
◼ CPI and Cycle time
◼ Determined by CPU hardware
◼ We will examine two MIPS implementations
◼ A simplified version
◼ A more realistic pipelined version
◼ Simple subset, shows most aspects
◼ Memory reference: lw, sw
◼ Arithmetic/logical: add, sub, and, or, slt
◼ Control transfer: beq, j

Chapter 4 — The Processor — 2


Instruction Execution
◼ PC → instruction memory, fetch instruction
◼ Register numbers → register file, read registers
◼ Depending on instruction class
◼ Use ALU to calculate
◼ Arithmetic result
◼ Memory address for load/store
◼ Branch target address
◼ Access data memory for load/store
◼ PC  target address or PC + 4

Chapter 4 — The Processor — 3


CPU Overview

Chapter 4 — The Processor — 4


Multiplexers
◼ Can’t just join
wires together
◼ Use multiplexers

Chapter 4 — The Processor — 5


Control

Chapter 4 — The Processor — 6


§4.2 Logic Design Conventions
Logic Design Basics
◼ Information encoded in binary
◼ Low voltage = 0, High voltage = 1
◼ One wire per bit
◼ Multi-bit data encoded on multi-wire buses
◼ Combinational element
◼ Operate on data
◼ Output is a function of input
◼ State (sequential) elements
◼ Store information

Chapter 4 — The Processor — 7


Combinational Elements
◼ AND-gate ◼ Adder A
Y
+
◼ Y=A&B ◼ Y=A+B B

A
Y
B

◼ Arithmetic/Logic Unit
◼ Multiplexer ◼ Y = F(A, B)
◼ Y = S ? I1 : I0
A
I0 M
u Y ALU Y
I1 x
B
S F

Chapter 4 — The Processor — 8


Sequential Elements
◼ Register: stores data in a circuit
◼ Uses a clock signal to determine when to
update the stored value
◼ Edge-triggered: update when Clk changes
from 0 to 1

Clk
D Q
D

Clk
Q

Chapter 4 — The Processor — 9


Sequential Elements
◼ Register with write control
◼ Only updates on clock edge when write
control input is 1
◼ Used when stored value is required later

Clk

D Q Write

Write D
Clk
Q

Chapter 4 — The Processor — 10


Clocking Methodology
◼ Combinational logic transforms data during
clock cycles
◼ Between clock edges
◼ Input from state elements, output to state
element
◼ Longest delay determines clock period

Chapter 4 — The Processor — 11


§4.3 Building a Datapath
Building a Datapath
◼ Datapath
◼ Elements that process data and addresses
in the CPU
◼ Registers, ALUs, mux’s, memories, …
◼ We will build a MIPS datapath
incrementally
◼ Refining the overview design

Chapter 4 — The Processor — 12


R-Format Instructions
◼ Read two register operands
◼ Perform arithmetic/logical operation
◼ Write register result

Chapter 4 — The Processor — 13


Load/Store Instructions
◼ Read register operands
◼ Calculate address using 16-bit offset
◼ Use ALU, but sign-extend offset
◼ Load: Read memory and update register
◼ Store: Write register value to memory

Chapter 4 — The Processor — 14


Branch Instructions
◼ Read register operands
◼ Compare operands
◼ Use ALU, subtract and check Zero output
◼ Calculate target address
◼ Sign-extend displacement
◼ Shift left 2 places (word displacement)
◼ Add to PC + 4
◼ Already calculated by instruction fetch

Chapter 4 — The Processor — 15


Composing the Elements
◼ First-cut data path does an instruction in
one clock cycle
◼ Each datapath element can only do one
function at a time
◼ Hence, we need separate instruction and data
memories
◼ Use multiplexers where alternate data
sources are used for different instructions

Chapter 4 — The Processor — 16


§4.4 A Simple Implementation Scheme
ALU Control
◼ ALU used for
◼ Load/Store: F = add
◼ Branch: F = subtract
◼ R-type: F depends on funct field
ALU control Function
0000 AND
0001 OR
0010 add
0110 subtract
0111 set-on-less-than
1100 NOR

Chapter 4 — The Processor — 17


ALU Control
◼ Assume 2-bit ALUOp derived from opcode
◼ Combinational logic derives ALU control

opcode ALUOp Operation funct ALU function ALU control


lw 00 load word XXXXXX add 0010
sw 00 store word XXXXXX add 0010
beq 01 branch equal XXXXXX subtract 0110
R-type 10 add 100000 add 0010
subtract 100010 subtract 0110
AND 100100 AND 0000
OR 100101 OR 0001
set-on-less-than 101010 set-on-less-than 0111

Chapter 4 — The Processor — 18


The Main Control Unit
◼ Control signals derived from instruction

R-type 0 rs rt rd shamt funct


31:26 25:21 20:16 15:11 10:6 5:0

Load/
35 or 43 rs rt address
Store
31:26 25:21 20:16 15:0

Branch 4 rs rt address
31:26 25:21 20:16 15:0

opcode always read, write for sign-extend


read except R-type and add
for load and load

Chapter 4 — The Processor — 19


Implementing Jumps
Jump 2 address
31:26 25:0

◼ Jump uses word address


◼ Update PC with concatenation of
◼ Top 4 bits of old PC
◼ 26-bit jump address
◼ 00
◼ Need an extra control signal decoded from
opcode
Chapter 4 — The Processor — 20
Performance Issues
◼ Longest delay determines clock period
◼ Critical path: load instruction
◼ Instruction memory → register file → ALU →
data memory → register file
◼ Not feasible to vary period for different
instructions
◼ Violates design principle
◼ Making the common case fast
◼ We will improve performance by pipelining

Chapter 4 — The Processor — 21


§4.5 An Overview of Pipelining
Pipelining Analogy
◼ Pipelined laundry: overlapping execution
◼ Parallelism improves performance

◼ Four loads:
◼ Speedup
= 8/3.5 = 2.3
◼ Non-stop:
◼ Speedup
= 2n/0.5n + 1.5 ≈ 4
= number of stages

Chapter 4 — The Processor — 22


MIPS Pipeline
◼ Five stages, one step per stage
1. IF: Instruction fetch from memory
2. ID: Instruction decode & register read
3. EX: Execute operation or calculate address
4. MEM: Access memory operand
5. WB: Write result back to register

Chapter 4 — The Processor — 23


Pipeline Performance
◼ Assume time for stages is
◼ 100ps for register read or write
◼ 200ps for other stages
◼ Compare pipelined datapath with single-cycle
datapath

Instr Instr fetch Register ALU op Memory Register Total time


read access write
lw 200ps 100 ps 200ps 200ps 100 ps 800ps
sw 200ps 100 ps 200ps 200ps 700ps
R-format 200ps 100 ps 200ps 100 ps 600ps
beq 200ps 100 ps 200ps 500ps

Chapter 4 — The Processor — 24


Pipeline Performance
Single-cycle (Tc= 800ps)

Pipelined (Tc= 200ps)

Chapter 4 — The Processor — 25


Pipeline Speedup
◼ If all stages are balanced
◼ i.e., all take the same time
◼ Time between instructionspipelined
= Time between instructionsnonpipelined
Number of stages
◼ If not balanced, speedup is less
◼ Speedup due to increased throughput
◼ Latency (time for each instruction) does not
decrease

Chapter 4 — The Processor — 26


Pipelining and ISA Design
◼ MIPS ISA designed for pipelining
◼ All instructions are 32-bits
◼ Easier to fetch and decode in one cycle
◼ c.f. x86: 1- to 17-byte instructions
◼ Few and regular instruction formats
◼ Can decode and read registers in one step
◼ Load/store addressing
◼ Can calculate address in 3rd stage, access memory
in 4th stage
◼ Alignment of memory operands
◼ Memory access takes only one cycle

Chapter 4 — The Processor — 27


Hazards
◼ Situations that prevent starting the next
instruction in the next cycle
◼ Structure hazards
◼ A required resource is busy
◼ Data hazard
◼ Need to wait for previous instruction to
complete its data read/write
◼ Control hazard
◼ Deciding on control action depends on
previous instruction

Chapter 4 — The Processor — 28


Data Hazards
◼ An instruction depends on completion of
data access by a previous instruction
◼ add $s0, $t0, $t1
sub $t2, $s0, $t3

Chapter 4 — The Processor — 29


Forwarding (aka Bypassing)
◼ Use result when it is computed
◼ Don’t wait for it to be stored in a register
◼ Requires extra connections in the datapath

Chapter 4 — The Processor — 30


Load-Use Data Hazard
◼ Can’t always avoid stalls by forwarding
◼ If value not computed when needed
◼ Can’t forward backward in time!

Chapter 4 — The Processor — 31


Control Hazards
◼ Branch determines flow of control
◼ Fetching next instruction depends on branch
outcome
◼ Pipeline can’t always fetch correct instruction
◼ Still working on ID stage of branch
◼ In MIPS pipeline
◼ Need to compare registers and compute
target early in the pipeline
◼ Add hardware to do it in ID stage

Chapter 4 — The Processor — 32


Stall on Branch
◼ Wait until branch outcome determined
before fetching next instruction

Chapter 4 — The Processor — 33


Branch Prediction
◼ Longer pipelines can’t readily determine
branch outcome early
◼ Stall penalty becomes unacceptable
◼ Predict outcome of branch
◼ Only stall if prediction is wrong
◼ In MIPS pipeline
◼ Can predict branches not taken
◼ Fetch instruction after branch, with no delay

Chapter 4 — The Processor — 34


More-Realistic Branch Prediction
◼ Static branch prediction
◼ Based on typical branch behavior
◼ Example: loop and if-statement branches
◼ Predict backward branches taken
◼ Predict forward branches not taken
◼ Dynamic branch prediction
◼ Hardware measures actual branch behavior
◼ e.g., record recent history of each branch
◼ Assume future behavior will continue the trend
◼ When wrong, stall while re-fetching, and update history

Chapter 4 — The Processor — 35


Pipeline Summary
The BIG Picture

◼ Pipelining improves performance by


increasing instruction throughput
◼ Executes multiple instructions in parallel
◼ Each instruction has the same latency
◼ Subject to hazards
◼ Structure, data, control
◼ Instruction set design affects complexity of
pipeline implementation
Chapter 4 — The Processor — 36
Pipeline registers
◼ Need registers between stages
◼ To hold information produced in previous cycle

Chapter 4 — The Processor — 37


Pipeline Operation
◼ Cycle-by-cycle flow of instructions through
the pipelined datapath
◼ “Single-clock-cycle” pipeline diagram
◼ Shows pipeline usage in a single cycle
◼ Highlight resources used
◼ c.f. “multi-clock-cycle” diagram
◼ Graph of operation over time
◼ We’ll look at “single-clock-cycle” diagrams
for load & store

Chapter 4 — The Processor — 38


§4.7 Data Hazards: Forwarding vs. Stalling
Data Hazards in ALU Instructions
◼ Consider this sequence:
sub $2, $1,$3
and $12,$2,$5
or $13,$6,$2
add $14,$2,$2
sw $15,100($2)
◼ We can resolve hazards with forwarding
◼ How do we detect when to forward?

Chapter 4 — The Processor — 39


Detecting the Need to Forward
◼ Pass register numbers along pipeline
◼ e.g., ID/EX.RegisterRs = register number for Rs
sitting in ID/EX pipeline register
◼ ALU operand register numbers in EX stage
are given by
◼ ID/EX.RegisterRs, ID/EX.RegisterRt
◼ Data hazards when
Fwd from
1a. EX/MEM.RegisterRd = ID/EX.RegisterRs EX/MEM
pipeline reg
1b. EX/MEM.RegisterRd = ID/EX.RegisterRt
2a. MEM/WB.RegisterRd = ID/EX.RegisterRs Fwd from
MEM/WB
2b. MEM/WB.RegisterRd = ID/EX.RegisterRt pipeline reg

Chapter 4 — The Processor — 40


Detecting the Need to Forward
◼ But only if forwarding instruction will write
to a register!
◼ EX/MEM.RegWrite, MEM/WB.RegWrite
◼ And only if Rd for that instruction is not
$zero
◼ EX/MEM.RegisterRd ≠ 0,
MEM/WB.RegisterRd ≠ 0

Chapter 4 — The Processor — 41


Double Data Hazard
◼ Consider the sequence:
add $1,$1,$2
add $1,$1,$3
add $1,$1,$4
◼ Both hazards occur
◼ Want to use the most recent
◼ Revise MEM hazard condition
◼ Only fwd if EX hazard condition isn’t true

Chapter 4 — The Processor — 42


Load-Use Hazard Detection
◼ Check when using instruction is decoded
in ID stage
◼ ALU operand register numbers in ID stage
are given by
◼ IF/ID.RegisterRs, IF/ID.RegisterRt
◼ Load-use hazard when
◼ ID/EX.MemRead and
((ID/EX.RegisterRt = IF/ID.RegisterRs) or
(ID/EX.RegisterRt = IF/ID.RegisterRt))
◼ If detected, stall and insert bubble

Chapter 4 — The Processor — 43


How to Stall the Pipeline
◼ Force control values in ID/EX register
to 0
◼ EX, MEM and WB do nop (no-operation)
◼ Prevent update of PC and IF/ID register
◼ Using instruction is decoded again
◼ Following instruction is fetched again
◼ 1-cycle stall allows MEM to read data for lw
◼ Can subsequently forward to EX stage

Chapter 4 — The Processor — 44


Stalls and Performance
The BIG Picture

◼ Stalls reduce performance


◼ But are required to get correct results
◼ Compiler can arrange code to avoid
hazards and stalls
◼ Requires knowledge of the pipeline structure

Chapter 4 — The Processor — 45


Reducing Branch Delay
◼ Move hardware to determine outcome to ID
stage
◼ Target address adder
◼ Register comparator
◼ Example: branch taken
36: sub $10, $4, $8
40: beq $1, $3, 7
44: and $12, $2, $5
48: or $13, $2, $6
52: add $14, $4, $2
56: slt $15, $6, $7
...
72: lw $4, 50($7)

Chapter 4 — The Processor — 46


Dynamic Branch Prediction
◼ In deeper and superscalar pipelines, branch
penalty is more significant
◼ Use dynamic prediction
◼ Branch prediction buffer (aka branch history table)
◼ Indexed by recent branch instruction addresses
◼ Stores outcome (taken/not taken)
◼ To execute a branch
◼ Check table, expect the same outcome
◼ Start fetching from fall-through or target
◼ If wrong, flush pipeline and flip prediction

Chapter 4 — The Processor — 47


1-Bit Predictor: Shortcoming
◼ Inner loop branches mispredicted twice!
outer: …

inner: …

beq …, …, inner

beq …, …, outer

◼ Mispredict as taken on last iteration of


inner loop
◼ Then mispredict as not taken on first
iteration of inner loop next time around
Chapter 4 — The Processor — 48
2-Bit Predictor
◼ Only change prediction on two successive
mispredictions

Chapter 4 — The Processor — 49


Calculating the Branch Target
◼ Even with predictor, still need to calculate
the target address
◼ 1-cycle penalty for a taken branch
◼ Branch target buffer
◼ Cache of target addresses
◼ Indexed by PC when instruction fetched
◼ If hit and instruction is branch predicted taken, can
fetch target immediately

Chapter 4 — The Processor — 50


§4.9 Exceptions
Exceptions and Interrupts
◼ “Unexpected” events requiring change
in flow of control
◼ Different ISAs use the terms differently
◼ Exception
◼ Arises within the CPU
◼ e.g., undefined opcode, overflow, syscall, …
◼ Interrupt
◼ From an external I/O controller
◼ Dealing with them without sacrificing
performance is hard

Chapter 4 — The Processor — 51


Handling Exceptions
◼ In MIPS, exceptions managed by a System
Control Coprocessor (CP0)
◼ Save PC of offending (or interrupted) instruction
◼ In MIPS: Exception Program Counter (EPC)
◼ Save indication of the problem
◼ In MIPS: Cause register
◼ We’ll assume 1-bit
◼ 0 for undefined opcode, 1 for overflow
◼ Jump to handler at 8000 00180

Chapter 4 — The Processor — 52


An Alternate Mechanism
◼ Vectored Interrupts
◼ Handler address determined by the cause
◼ Example:
◼ Undefined opcode: C000 0000
◼ Overflow: C000 0020
◼ …: C000 0040
◼ Instructions either
◼ Deal with the interrupt, or
◼ Jump to real handler

Chapter 4 — The Processor — 53


Handler Actions
◼ Read cause, and transfer to relevant
handler
◼ Determine action required
◼ If restartable
◼ Take corrective action
◼ use EPC to return to program
◼ Otherwise
◼ Terminate program
◼ Report error using EPC, cause, …

Chapter 4 — The Processor — 54


Exceptions in a Pipeline
◼ Another form of control hazard
◼ Consider overflow on add in EX stage
add $1, $2, $1
◼ Prevent $1 from being clobbered

◼ Complete previous instructions

◼ Flush add and subsequent instructions

◼ Set Cause and EPC register values

◼ Transfer control to handler

◼ Similar to mispredicted branch


◼ Use much of the same hardware

Chapter 4 — The Processor — 55


Exception Properties
◼ Restartable exceptions
◼ Pipeline can flush the instruction
◼ Handler executes, then returns to the
instruction
◼ Refetched and executed from scratch
◼ PC saved in EPC register
◼ Identifies causing instruction
◼ Actually PC + 4 is saved
◼ Handler must adjust

Chapter 4 — The Processor — 56


Exception Example
◼ Exception on add in
40 sub $11, $2, $4
44 and $12, $2, $5
48 or $13, $2, $6
4C add $1, $2, $1
50 slt $15, $6, $7
54 lw $16, 50($7)

◼ Handler
80000180 sw $25, 1000($0)
80000184 sw $26, 1004($0)

Chapter 4 — The Processor — 57


Multiple Exceptions
◼ Pipelining overlaps multiple instructions
◼ Could have multiple exceptions at once
◼ Simple approach: deal with exception from
earliest instruction
◼ Flush subsequent instructions
◼ “Precise” exceptions
◼ In complex pipelines
◼ Multiple instructions issued per cycle
◼ Out-of-order completion
◼ Maintaining precise exceptions is difficult!

Chapter 4 — The Processor — 58


Imprecise Exceptions
◼ Just stop pipeline and save state
◼ Including exception cause(s)
◼ Let the handler work out
◼ Which instruction(s) had exceptions
◼ Which to complete or flush
◼ May require “manual” completion
◼ Simplifies hardware, but more complex handler
software
◼ Not feasible for complex multiple-issue
out-of-order pipelines

Chapter 4 — The Processor — 59


§4.10 Parallelism and Advanced Instruction Level Parallelism
Instruction-Level Parallelism (ILP)
◼ Pipelining: executing multiple instructions in
parallel
◼ To increase ILP
◼ Deeper pipeline
◼ Less work per stage  shorter clock cycle
◼ Multiple issue
◼ Replicate pipeline stages  multiple pipelines
◼ Start multiple instructions per clock cycle
◼ CPI < 1, so use Instructions Per Cycle (IPC)
◼ E.g., 4GHz 4-way multiple-issue
◼ 16 BIPS, peak CPI = 0.25, peak IPC = 4
◼ But dependencies reduce this in practice

Chapter 4 — The Processor — 60


Multiple Issue
◼ Static multiple issue
◼ Compiler groups instructions to be issued together
◼ Packages them into “issue slots”
◼ Compiler detects and avoids hazards
◼ Dynamic multiple issue
◼ CPU examines instruction stream and chooses
instructions to issue each cycle
◼ Compiler can help by reordering instructions
◼ CPU resolves hazards using advanced techniques at
runtime

Chapter 4 — The Processor — 61


Speculation
◼ “Guess” what to do with an instruction
◼ Start operation as soon as possible
◼ Check whether guess was right
◼ If so, complete the operation
◼ If not, roll-back and do the right thing
◼ Common to static and dynamic multiple issue
◼ Examples
◼ Speculate on branch outcome
◼ Roll back if path taken is different
◼ Speculate on load
◼ Roll back if location is updated

Chapter 4 — The Processor — 62


Compiler/Hardware Speculation
◼ Compiler can reorder instructions
◼ e.g., move load before branch
◼ Can include “fix-up” instructions to recover
from incorrect guess
◼ Hardware can look ahead for instructions
to execute
◼ Buffer results until it determines they are
actually needed
◼ Flush buffers on incorrect speculation

Chapter 4 — The Processor — 63


Speculation and Exceptions
◼ What if exception occurs on a
speculatively executed instruction?
◼ e.g., speculative load before null-pointer
check
◼ Static speculation
◼ Can add ISA support for deferring exceptions
◼ Dynamic speculation
◼ Can buffer exceptions until instruction
completion (which may not occur)

Chapter 4 — The Processor — 64


Static Multiple Issue
◼ Compiler groups instructions into “issue
packets”
◼ Group of instructions that can be issued on a
single cycle
◼ Determined by pipeline resources required
◼ Think of an issue packet as a very long
instruction
◼ Specifies multiple concurrent operations
◼  Very Long Instruction Word (VLIW)

Chapter 4 — The Processor — 65


Scheduling Static Multiple Issue
◼ Compiler must remove some/all hazards
◼ Reorder instructions into issue packets
◼ No dependencies with a packet
◼ Possibly some dependencies between
packets
◼ Varies between ISAs; compiler must know!
◼ Pad with nop if necessary

Chapter 4 — The Processor — 66


MIPS with Static Dual Issue
◼ Two-issue packets
◼ One ALU/branch instruction
◼ One load/store instruction
◼ 64-bit aligned
◼ ALU/branch, then load/store
◼ Pad an unused instruction with nop

Address Instruction type Pipeline Stages


n ALU/branch IF ID EX MEM WB
n+4 Load/store IF ID EX MEM WB
n+8 ALU/branch IF ID EX MEM WB
n + 12 Load/store IF ID EX MEM WB
n + 16 ALU/branch IF ID EX MEM WB
n + 20 Load/store IF ID EX MEM WB

Chapter 4 — The Processor — 67


MIPS with Static Dual Issue

Chapter 4 — The Processor — 68


Hazards in the Dual-Issue MIPS
◼ More instructions executing in parallel
◼ EX data hazard
◼ Forwarding avoided stalls with single-issue
◼ Now can’t use ALU result in load/store in same packet
◼ add $t0, $s0, $s1
load $s2, 0($t0)
◼ Split into two packets, effectively a stall
◼ Load-use hazard
◼ Still one cycle use latency, but now two instructions
◼ More aggressive scheduling required

Chapter 4 — The Processor — 69


Scheduling Example
◼ Schedule this for dual-issue MIPS
Loop: lw $t0, 0($s1) # $t0=array element
addu $t0, $t0, $s2 # add scalar in $s2
sw $t0, 0($s1) # store result
addi $s1, $s1,–4 # decrement pointer
bne $s1, $zero, Loop # branch $s1!=0

ALU/branch Load/store cycle


Loop: nop lw $t0, 0($s1) 1
addi $s1, $s1,–4 nop 2
addu $t0, $t0, $s2 nop 3
bne $s1, $zero, Loop sw $t0, 4($s1) 4

◼ IPC = 5/4 = 1.25 (c.f. peak IPC = 2)


Chapter 4 — The Processor — 70
Loop Unrolling
◼ Replicate loop body to expose more
parallelism
◼ Reduces loop-control overhead
◼ Use different registers per replication
◼ Called “register renaming”
◼ Avoid loop-carried “anti-dependencies”
◼ Store followed by a load of the same register
◼ Aka “name dependence”
◼ Reuse of a register name

Chapter 4 — The Processor — 71


Loop Unrolling Example
ALU/branch Load/store cycle
Loop: addi $s1, $s1,–16 lw $t0, 0($s1) 1
nop lw $t1, 12($s1) 2
addu $t0, $t0, $s2 lw $t2, 8($s1) 3
addu $t1, $t1, $s2 lw $t3, 4($s1) 4
addu $t2, $t2, $s2 sw $t0, 16($s1) 5
addu $t3, $t4, $s2 sw $t1, 12($s1) 6
nop sw $t2, 8($s1) 7
bne $s1, $zero, Loop sw $t3, 4($s1) 8

◼ IPC = 14/8 = 1.75


◼ Closer to 2, but at cost of registers and code size

Chapter 4 — The Processor — 72


Dynamic Multiple Issue
◼ “Superscalar” processors
◼ CPU decides whether to issue 0, 1, 2, …
each cycle
◼ Avoiding structural and data hazards
◼ Avoids the need for compiler scheduling
◼ Though it may still help
◼ Code semantics ensured by the CPU

Chapter 4 — The Processor — 73


Dynamic Pipeline Scheduling
◼ Allow the CPU to execute instructions out
of order to avoid stalls
◼ But commit result to registers in order
◼ Example
lw $t0, 20($s2)
addu $t1, $t0, $t2
sub $s4, $s4, $t3
slti $t5, $s4, 20
◼ Can start sub while addu is waiting for lw

Chapter 4 — The Processor — 74


Register Renaming
◼ Reservation stations and reorder buffer
effectively provide register renaming
◼ On instruction issue to reservation station
◼ If operand is available in register file or
reorder buffer
◼ Copied to reservation station
◼ No longer required in the register; can be
overwritten
◼ If operand is not yet available
◼ It will be provided to the reservation station by a
function unit
◼ Register update may not be required
Chapter 4 — The Processor — 75
Speculation
◼ Predict branch and continue issuing
◼ Don’t commit until branch outcome
determined
◼ Load speculation
◼ Avoid load and cache miss delay
◼ Predict the effective address
◼ Predict loaded value
◼ Load before completing outstanding stores
◼ Bypass stored values to load unit
◼ Don’t commit load until speculation cleared

Chapter 4 — The Processor — 76


Why Do Dynamic Scheduling?
◼ Why not just let the compiler schedule
code?
◼ Not all stalls are predicable
◼ e.g., cache misses
◼ Can’t always schedule around branches
◼ Branch outcome is dynamically determined
◼ Different implementations of an ISA have
different latencies and hazards

Chapter 4 — The Processor — 77


Does Multiple Issue Work?
The BIG Picture

◼ Yes, but not as much as we’d like


◼ Programs have real dependencies that limit ILP
◼ Some dependencies are hard to eliminate
◼ e.g., pointer aliasing
◼ Some parallelism is hard to expose
◼ Limited window size during instruction issue
◼ Memory delays and limited bandwidth
◼ Hard to keep pipelines full
◼ Speculation can help if done well
Chapter 4 — The Processor — 78
Power Efficiency
◼ Complexity of dynamic scheduling and
speculations requires power
◼ Multiple simpler cores may be better
Microprocessor Year Clock Rate Pipeline Issue Out-of-order/ Cores Power
Stages width Speculation
i486 1989 25MHz 5 1 No 1 5W
Pentium 1993 66MHz 5 2 No 1 10W
Pentium Pro 1997 200MHz 10 3 Yes 1 29W
P4 Willamette 2001 2000MHz 22 3 Yes 1 75W
P4 Prescott 2004 3600MHz 31 3 Yes 1 103W
Core 2006 2930MHz 14 4 Yes 2 75W
UltraSparc III 2003 1950MHz 14 4 No 1 90W
UltraSparc T1 2005 1200MHz 6 1 No 8 70W

Chapter 4 — The Processor — 79


§4.13 Fallacies and Pitfalls
Fallacies
◼ Pipelining is easy (!)
◼ The basic idea is easy
◼ The devil is in the details
◼ e.g., detecting data hazards
◼ Pipelining is independent of technology
◼ So why haven’t we always done pipelining?
◼ More transistors make more advanced techniques
feasible
◼ Pipeline-related ISA design needs to take account of
technology trends
◼ e.g., predicated instructions

Chapter 4 — The Processor — 80


Pitfalls
◼ Poor ISA design can make pipelining
harder
◼ e.g., complex instruction sets (VAX, IA-32)
◼ Significant overhead to make pipelining work
◼ IA-32 micro-op approach
◼ e.g., complex addressing modes
◼ Register update side effects, memory indirection
◼ e.g., delayed branches
◼ Advanced pipelines have long delay slots

Chapter 4 — The Processor — 81


§4.14 Concluding Remarks
Concluding Remarks
◼ ISA influences design of datapath and control
◼ Datapath and control influence design of ISA
◼ Pipelining improves instruction throughput
using parallelism
◼ More instructions completed per second
◼ Latency for each instruction not reduced
◼ Hazards: structural, data, control
◼ Multiple issue and dynamic scheduling (ILP)
◼ Dependencies limit achievable parallelism
◼ Complexity leads to the power wall

Chapter 4 — The Processor — 82

You might also like